In Java, we use abstract class and interface to achieve abstraction.
In Java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.
Ans : s1==s2 result will false, because s1 will be created in heap memory and s2 will be created in String pool hence both will not be same.
Q5. Write a multithreading program in which 1 thread will print odd number and another thread will print even number, output should be in sequence like 1,2,3,4 (I tried with sleep it work fine but interviewer was expecting it with wait and notify ).
class OddThread implements Runnable{
Print print ;
public OddThread(Print print) {
this.print = print;
}
@Override
public void run() {
for(int i =1 ; i <=100 ;i++) {
if(i%2 !=0) {
print.printOdd(i);
}else {
print.printEven(i);
}
}
}
}
class EvenThread implements Runnable{
Print print;
public EvenThread(Print print) {
this.print = print;
}
@Override
public void run() {
for(int i =1 ; i <=100 ;i++) {
if(i%2 ==0) {
print.printEven(i);
}
}
}
}
class Print{
boolean isOdd = false;
synchronized void printEven(int num) {
while(!isOdd) {
try {
wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Even : "+num);
notify();
isOdd = false;
}
synchronized void printOdd(int num) {
//System.out.println(isOdd);
while(isOdd) {
try {
wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Odd : "+num);
notify();
isOdd = true;
}
}
public class OddEvenThreads {
public static void main(String[] args) {
Print print = new Print();
Thread t1 = new Thread(new OddThread(print));
Thread t2 = new Thread(new OddThread(print));
t1.start();
t2.start();
}
}
Q8. Why we should implement equals and hashcode for hashmap.
When collision happens in map means 2 key has the same hashcode, that time they will be stored in same bucket, hence to search the correct key in the same bucket we need to compare through equals
method. Hence we should implement equals and hashcode.
-----------------------------------------------------------------------------
Goldman sachs hacker rank test:-
1. There is m*n dimension matrix like below:
1 3 5
4 . 2 9
6 7 8
to get the number of minimum and maximum is based on below:
1. 1 is minimum in row and column
2. 5 is max in row and min in column
3. 2 is minimum in row and column
4. 9 is max in row and column
5. 6 is min in row and max in col
6. 8 is max in row
7. 7 is max in col
hence output will be 7, WAP to find the output
2. A and B communicate through encoding and decoding, when message is sent code(for encode 1 and for decode 2),message and encryption key will be send as below exampl
1
open
123
output will be
oppeeen
2
oppeeen
123
output will be open,
WAP to encode and decode.
--------------------------------------------------------------------------
CME
1. When to use ArrayList and When to use Linked List.
LinkedList
and ArrayList
are two different implementations of the List interface. LinkedList
implements it with a doubly-linked list. ArrayList
implements it with a dynamically re-sizing array.
As with standard linked list and array operations, the various methods will have different algorithmic runtimes.
get(int index)
is O(n) (with n/4 steps on average)
add(E element)
is O(1)
add(int index, E element)
is O(n) (with n/4 steps on average), but O(1) when index = 0
<--- main benefit of LinkedList<E>
remove(int index)
is O(n) (with n/4 steps on average)
Iterator.remove()
is O(1). <--- main benefit of LinkedList<E>
ListIterator.add(E element)
is O(1) This is one of the main benefits of LinkedList<E>
Note: Many of the operations need n/4 steps on average, constant number of steps in the best case (e.g. index = 0), and n/2steps in worst case (middle of list)
get(int index)
is O(1) <--- main benefit of ArrayList<E>
add(E element)
is O(1) amortized, but O(n) worst-case since the array must be resized and copied
add(int index, E element)
is O(n) (with n/2 steps on average)
remove(int index)
is O(n) (with n/2 steps on average)
Iterator.remove()
is O(n) (with n/2 steps on average)
ListIterator.add(E element)
is O(n) (with n/2 steps on average)
So basically when we we want fast retrieval or search we should use ArrayList and when we want fast insertion and deletion we should use LinkedList.
2. Implement ArrayList
public class MyArrayList {
Object[] mystore;
int size = 0;
public MyArrayList() {
mystore = new Object[10];
}
public Object get(int index) {
if(index< size) {
return mystore[index];
}else {
throw new ArrayIndexOutOfBoundsException();
}
}
public void add(Object obj) {
if(mystore.length-size<=5) {
increaseSize();
}
mystore[size++] = obj;
}
public void increaseSize() {
mystore = Arrays.copyOf(mystore, mystore.length*2);
System.out.println("\nNew Length : "+ mystore.length);
}
public int size() {
return size;
}
public Object remove(int index) {
if(index < size) {
Object obj = mystore[index];
int tmp = index;
while(tmp < size) {
mystore[tmp] = mystore[tmp+1];
mystore[tmp+1] = null;
tmp++;
}
size--;
return obj;
}else {
throw new ArrayIndexOutOfBoundsException();
}
}
public static void main(String[] args) {
MyArrayList mal = new MyArrayList();
mal.add(2);
mal.add(5);
mal.add(1);
mal.add(23);
mal.add(14);
for(int i=0;i<mal.size();i++){
System.out.print(mal.get(i)+" ");
}
mal.add(29);
System.out.println("Element at Index 5:"+mal.get(5));
System.out.println("List size: "+mal.size());
System.out.println("Removing element at index 2: "+mal.remove(2));
for(int i=0;i<mal.size();i++){
System.out.print(mal.get(i)+" ");
}
}
}
3. ProduceConsumer Problem
class Producer implements Runnable{
List<Integer> buffer ;
int maxsize;
int value = 10;
public Producer(List<Integer> buffer,int size) {
this.buffer = buffer;
this.maxsize = size;
}
@Override
public void run() {
while(value<100) {
synchronized (buffer) {
if(buffer.size()== maxsize) {
try {
buffer.wait();
}catch(InterruptedException e){}
}else {
buffer.add(value);
System.out.println("Added : "+value);
value++;
buffer.notifyAll();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
class Consumer implements Runnable{
List<Integer> buffer;
public Consumer(List<Integer> buffer) {
// TODO Auto-generated constructor stub
this.buffer = buffer;
}
@Override
public void run() {
while(true) {
synchronized (buffer) {
if(buffer.size()==0) {
try {
buffer.wait();
}catch(InterruptedException e) {}
}else {
int i = buffer.remove(0);
System.out.println("Removed : "+i);
buffer.notifyAll();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
public class ProducerConsumerExample{
public static void main(String[] args) {
List<Integer> buffer = new ArrayList<>(10);
int maxSize = 10;
Producer p = new Producer(buffer, maxSize);
Consumer c = new Consumer(buffer);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
4. What if HashCode method will return 1 value
5. 2 list are there which intersect at one point , how to get the intersection point, how to improve performance
Method 1(Simply use two loops)
Use 2 nested for loops. The outer loop will be for each node of the 1st list and inner loop will be for 2nd list. In the inner loop, check if any of nodes of the 2nd list is same as the current node of the first linked list. The time complexity of this method will be O(mn) where m and n are the numbers of nodes in two lists.
Method 2 (Mark Visited Nodes)
This solution requires modifications to basic linked list data structure. Have a visited flag with each node. Traverse the first linked list and keep marking visited nodes. Now traverse the second linked list, If you see a visited node again then there is an intersection point, return the intersecting node. This solution works in O(m+n) but requires additional information with each node. A variation of this solution that doesn’t require modification to the basic data structure can be implemented using a hash. Traverse the first linked list and store the addresses of visited nodes in a hash. Now traverse the second linked list and if you see an address that already exists in the hash then return the intersecting node.
Method 3(Using difference of node counts)
1) Get count of the nodes in the first list, let count be c1.
2) Get count of the nodes in the second list, let count be c2.
3) Get the difference of counts d = abs(c1 – c2)
4) Now traverse the bigger list from the first node till d nodes so that from here onwards both the lists have equal no of nodes.
5) Then we can traverse both the lists in parallel till we come across a common node. (Note that getting a common node is done by comparing the address of the nodes
6. what is ineterprocess comunication
Inter process communication (IPC) is a mechanism which allows processes to communicate each other and synchronize their actions. The communication between these processes can be seen as a method of co-operation between them. Processes can communicate with each other using these two ways:
- Shared Memory
- Message passing
7. suppose 2 jvm are there in 2 different machine , in what all ways they can communicate.
1. Socket programming.
2. RMI
3. Sharing Files (File IO/ Serializing)
a shared DB
web services (arguably a higher form of socket comm.)
8. shellow copy , deep copy difference
9. Liverace
10. Explain concurrency maps
The ConcurrentHashMap and ConcurrentSkipListMap classes implement the
ConcurrentMap interface. A ConcurrentMap enhances a Map by adding the atomic
putIfAbsent, remove, and replace methods. For example, the putIfAbsent
method is equivalent to performing the following code as an atomic operation:
if (!map.containsKey(key))
return map.put(key, value);
else
return map.get(key);
ConcurrentSkipListMap and ConcurrentSkipListSet are sorted.
ConcurrentSkipListMap keys and ConcurrentSkipListSet elements require the
use of the Comparable or Comparator interfaces to enable ordering.
11. what is use of blocking ques
A BlockingQueue is a type of shared
collection that is used to exchange data between two or more threads while causing
one or more of the threads to wait until the point in time when the data can be
exchanged. One use case of a BlockingQueue is called the producer-consumer
problem. In a producer-consumer scenario, one thread produces data, then adds it to
a queue, and another thread must consume the data from the queue. A queue
provides the means for the producer and the consumer to exchange objects.
12. Executer thread
A java.util.concurrent.Executor is used to execute the run method in a
Runnable instance much like a thread. Unlike a more traditional new Thread(r)
.start(), an Executor can be designed to use any number of threading
approaches, including
■ Not starting any threads at all (task is run in the calling thread)
■ Starting a new thread for each task
■ Queuing tasks and processing them with only enough threads to keep the
CPU utilized
13.Observer pattern
interface Subject{
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObserver();
}
interface Observer{
public void update(float temp,float humd,float press);
}
class WeatherData implements Subject{
private ArrayList<Observer> observers;
private float temperature ;
private float humidity;
private float pressure;
public WeatherData() {
observers = new ArrayList<>();
}
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
@Override
public void removeObserver(Observer o) {
observers.remove(o);
}
@Override
public void notifyObserver() {
for(Observer o : observers) {
o.update(temperature,humidity,pressure);
}
}
public void measurementsChanged() {
notifyObserver();
}
public float getTemperature() {
return temperature;
}
public float getHumidity() {
return humidity;
}
public float getPressure() {
return pressure;
}
public void setMeasurements(float temp,float humd,float pres){
this.temperature= temp;
this.humidity = humd;
this.pressure = pres;
measurementsChanged();
}
}
class currentConditionDisplay implements Observer{
private float temperature;
private float humidity;
private float pressure;
private Subject weatherData;
public currentConditionDisplay(Subject weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
@Override
public void update(float temp, float humd, float press) {
this.temperature = temp;
this.humidity = humd;
display();
}
public void display() {
System.out.println("Current conditions: " + temperature
+ "F degrees and " + humidity + "% humidity");
}
}
public class ObserverPattern {
public static void main(String arg[]) {
WeatherData wd = new WeatherData();
currentConditionDisplay ccd = new currentConditionDisplay(wd);
wd.setMeasurements(56, 89, 78);
wd.setMeasurements(45, 80, 90);
wd.setMeasurements(00, 65, 78);
}
}
=================================================
JP Morgan Telephonic:
1. Can we serialize singleton object?
2. How can we achieve singleton behavior in distributed system or 2 jvm.
3. can we override static members (why , how ,flow must be clear here).
4. implicit object in jsp.
5. what is difference between static nested class and inner class
4. What is immutability?
5. What are the imutable classes in java other then string?
6. How will you create immutable class? if class would have reference variable how will you make it immutable?
7. public void test(Object);
public void test(String);
public void test(Integer);
Ans : It throws ambiguous error.