JP Morgan: -
Q.1 OPPs concepts:
Inheritence:- When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Q2,. What is encapsulation
Q3, What is polymorphism
Q4, What will be the output of the below code when you comapre starings with ==
if we call the method with test(null); which object will get called?
8. What all class loaders are present in java.
9. What are the ways to create an object in java.
Applied Materials:
1. there is a array {2,4,3,7,10,20} find the kth largest element.
2. from 1800 to 2000 century person' s birth year and death year has given, find the year in which most persons were alive.
P1(1810 - 1875) , p2(1820 - 1890) , p3(1890 - 1930), p4(1856 - 1900)
so here 1890 is the year in which most persons were alive.
3. Write implementation of blocking queue in java.
4. Write double locked singlton class.
Smarsh Telephonic :
1. There are 2 files which has 3-3 lines each, print the non duplicate lines.
2. there is directory which has 10000 of files how will you process it.(using threads,executor fmw )
3. how will you make sure that 2 threads won't process the same file
4. from the factory class of singlton how will you get 1 singlton object per thread.
5. DB optimaztion, parameter tuning how will you do?
ABNetworks:
1. In which JAva version you are working on?
2. What all the new features in java 1.7
3. in Try and catch block who does the resource closing and in which phase
4. What are the memories in Java
5. On what all data structures you have used?
6. whatis set , what arethe implementation of this,how the memory is created for it and who creates it.
7, what is polymorism,
8 what is runtime polymorphism
9 what is complie tile exception
SAP LAB by Mishraji:
Q.1 OPPs concepts:
Inheritence:- When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Abstraction: - Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't know the internal processing.
In Java, we use abstract class and interface to achieve abstraction.
polymorphism:- If one task is performed by different ways, it is known as polymorphism. For example: to convince the customer differently, to draw something, for example, shape, triangle, rectangle, etc.
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.
Encapsulation :- Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.
Q3, What is polymorphism
Q4, What will be the output of the below code when you comapre starings with ==
String s1 = new String("abc");
String s2 = "abc";
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.
Q.5
public void m1(String s) {
System.out.println("String method");
}
public void m1(Object o) {
System.out.println("Object Method");
}
t.m1(null); which method will get called?
Ans : String (because it takes from lower hierarchy )
Ans : String (because it takes from lower hierarchy )
public void m1(String s) {
System.out.println("String method");
}
public void m1(Object o) {
System.out.println("Object Method");
}
public void m1(List<String> ls) {
System.out.println("List");
}
t.m1(null);
ans : now method m1 will throw ambiguity error bcoz it will treat list method and String method same.
ans : now method m1 will throw ambiguity error bcoz it will treat list method and String method 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();
}
}
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();
}
}
Q6. Sort the HashMap based on value.
Using Comparator :
public static HashMap<String,Integer> sortByValue(HashMap<String,Integer> hm){
List<Map.Entry<String,Integer>> list = new LinkedList<Map.Entry<String,Integer>>(hm.entrySet());
for(Entry<String, Integer> a : list) {
System.out.println(a);
}
Collections.sort(list, new Comparator<Map.Entry<String,Integer> >(){
public int compare(Map.Entry<String,Integer> o1,Map.Entry<String, Integer> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
HashMap<String,Integer> temp = new LinkedHashMap<String,Integer>();
for(Map.Entry<String, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
for(Entry<String, Integer> a : temp.entrySet()) {
System.out.println(a);
}
return temp;
}
Without Comparator , with Iterator
public static LinkedHashMap<Integer,String> sortHashMapByValues(HashMap<Integer,String> passedMap){
List<Integer> mapKeys = new ArrayList<>(passedMap.keySet());
List<String> mapValues = new ArrayList<>(passedMap.values());
Collections.sort(mapKeys);
Collections.sort(mapValues);
LinkedHashMap<Integer,String> sortedMap = new LinkedHashMap<>();
Iterator<String> valueIT = mapValues.iterator();
while(valueIT.hasNext()) {
String val = valueIT.next();
Iterator<Integer> keyIT = mapKeys.iterator();
while(keyIT.hasNext()) {
Integer key = keyIT.next();
String comp1 = passedMap.get(key);
String comp2 = val;
if(comp1.equals(comp2)) {
keyIT.remove();
sortedMap.put(key, val);
break;
}
}
}
return sortedMap;
}
Using Comparator :
public static HashMap<String,Integer> sortByValue(HashMap<String,Integer> hm){
List<Map.Entry<String,Integer>> list = new LinkedList<Map.Entry<String,Integer>>(hm.entrySet());
for(Entry<String, Integer> a : list) {
System.out.println(a);
}
Collections.sort(list, new Comparator<Map.Entry<String,Integer> >(){
public int compare(Map.Entry<String,Integer> o1,Map.Entry<String, Integer> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
HashMap<String,Integer> temp = new LinkedHashMap<String,Integer>();
for(Map.Entry<String, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
for(Entry<String, Integer> a : temp.entrySet()) {
System.out.println(a);
}
return temp;
}
Without Comparator , with Iterator
public static LinkedHashMap<Integer,String> sortHashMapByValues(HashMap<Integer,String> passedMap){
List<Integer> mapKeys = new ArrayList<>(passedMap.keySet());
List<String> mapValues = new ArrayList<>(passedMap.values());
Collections.sort(mapKeys);
Collections.sort(mapValues);
LinkedHashMap<Integer,String> sortedMap = new LinkedHashMap<>();
Iterator<String> valueIT = mapValues.iterator();
while(valueIT.hasNext()) {
String val = valueIT.next();
Iterator<Integer> keyIT = mapKeys.iterator();
while(keyIT.hasNext()) {
Integer key = keyIT.next();
String comp1 = passedMap.get(key);
String comp2 = val;
if(comp1.equals(comp2)) {
keyIT.remove();
sortedMap.put(key, val);
break;
}
}
}
return sortedMap;
}
Q7. Suppose if if all the hashcode is returnig same value where exactly the data will be stored?
All the values will be stored in only one bucket.
All the values will be stored in only one bucket.
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.
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
6. what is ineterprocess comunication
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);
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.
For
LinkedList<E>
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) whenindex = 0
<--- main benefit ofLinkedList<E>
remove(int index)
is O(n) (with n/4 steps on average)Iterator.remove()
is O(1). <--- main benefit ofLinkedList<E>
ListIterator.add(E element)
is O(1) This is one of the main benefits ofLinkedList<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)
For
ArrayList<E>
get(int index)
is O(1) <--- main benefit ofArrayList<E>
add(E element)
is O(1) amortized, but O(n) worst-case since the array must be resized and copiedadd(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)
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.
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.
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
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)
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);
if we call the method with test(null); which object will get called?
Ans : It throws ambiguous error.
8. What all class loaders are present in java.
9. What are the ways to create an object in java.
Applied Materials:
1. there is a array {2,4,3,7,10,20} find the kth largest element.
2. from 1800 to 2000 century person' s birth year and death year has given, find the year in which most persons were alive.
P1(1810 - 1875) , p2(1820 - 1890) , p3(1890 - 1930), p4(1856 - 1900)
so here 1890 is the year in which most persons were alive.
3. Write implementation of blocking queue in java.
4. Write double locked singlton class.
Smarsh Telephonic :
1. There are 2 files which has 3-3 lines each, print the non duplicate lines.
2. there is directory which has 10000 of files how will you process it.(using threads,executor fmw )
3. how will you make sure that 2 threads won't process the same file
4. from the factory class of singlton how will you get 1 singlton object per thread.
5. DB optimaztion, parameter tuning how will you do?
ABNetworks:
1. In which JAva version you are working on?
2. What all the new features in java 1.7
3. in Try and catch block who does the resource closing and in which phase
4. What are the memories in Java
5. On what all data structures you have used?
6. whatis set , what arethe implementation of this,how the memory is created for it and who creates it.
7, what is polymorism,
8 what is runtime polymorphism
9 what is complie tile exception
SAP LAB by Mishraji:
Round 1 Date March 05, 2019
==============================
tell me about yourself.
Java
1.
Write Sigleton class which has memers as Date, List in it and provide
the way to access the instance members(i.e getX for Date, List).
2. Can we have variables in the Interface. Explain with the example.
3. Why variables in the interface are costants.
4. How we can add/plug new API to an existing class/interface so that client need not change what they will
get this new API feature upon upgrade.
Example Class/Interface{
toXml()
}
now we want to add new API called
toJson() such that client will get this new one as they upgrade to new jar version.
Explain this using java code.
Coding:
1. Write a program to encode given string like :
input : AABBCCAA
output: 2A2B2C2A
Round 2:
=====================
tell me about yourself.
Java:
1. Why multiple inheritance not in JAVa.
2. How to solve diamond problem in JAVA.
3. How we can achieve multiple inheritence in JAVA using interface.
Example
Class A, Class B are invidual.
Then how Class C can get behaviour from A and B.
Explain it.
4. Cam we have memory leak in java. Explain it with Examples.
5. Whats the benefit of immutable class in Java.
Coding/DS:
1. Sort the numbers.
2. Explain the merge sort. Implement the Merge() code.
3. Find the minimum from the given array in the big O(n).
4. Find the 4 minimum in one scan.i.e Kth min/max from the unsorted array.
Database:
1. What is index and how it works internally. Explain in detail.
============================== ====================
SAP:
1 what is equal and hashcode contract,
2 what is index, can we create index based on two columns which shares same kind of properties.
3. write a clean code to merge 2 sorted arrays
4. how will improve performance of query from your end
5, singlton
===========================================
FIS:
1. what will the type of b and d in below code:
int a[],b;
String c[],d;
2.what all the palaces where super keyword can be used
3. there is file which has product,date, id, create a program to sort the values by each filed.
4. Write a REST API
5. clone treeset
6. suppose if you want to block perticular ip address or geograpphical ip address how to do that in servlet.
--------------------------------------------------
Java 8 new features:
1.Lambda
2. Method refrence
3. Streams
4.Enhanced Interfaces
5.New Date and Time API
6. CompletableFuture
7. Optional
Benifits of java 8
supports functional programming
ease of high volume data processing using streams ex bigdata n all
ease of getting parameter names using reflection
reusable code with enhaced collection api
smart exception handeling using optional, so we can handle null pointer exception using optional
control on jvm with new set of parameters
enhanced encryption support with base64
faster execution with nashorn javascript engine support to exectute javascript code
What is Lambda expression in java 8
it is an anonymous function , it is like methode which doesn't need modifiers name no decalarion , it can be passed as parameter in method, so we can pas code as a data. This piece of code can be passed to other objects and methods.
what are the 3 main parts of lambda expression in java
parameter list - it can have zero or more parameters. parameter list is optional to lambda
lambda arrow operator - "-> " is known as Lambda arrow operator. It separates the list of parameters and the body of lambda.
lambda expression body - The piece of code that we want to execute is written in lambda expression body.
What is the data type of lambda expression:
A lambda expression fulfills the purpose of passing code as data. The data type of a lambda expression is a functional interface . In most of the cases this is java.lang.Runnable interface.
why did the Oracle release a new version of java like java 8?
Functional programming:- The main theme of of java 8 is support for functional programming.
cloud computing :- lambda expression are very useful.
big data:- with increase in database size and growth of multi-core cpu servers, there is need for java to support such large scale systems.(support of streams)
optional:- it is best practice of exception cases, by using this program becomes very robust.it came fro guvava library of google.
What are the advantages of a lambda expression?
compare to passing the anonymous class it is easier to pass lambda expression. We can also pass a method as a parameter to other method. we can pass the code as well to the functions.
it is very useful in functional programming, cloud computing and serverless Architecture.
What is the Functional interface in java 8?
An interface with exactly one abstract method.
it can have default methods with implementation.A default method is not abstract.
ex:-Runnable, java.util.concurrent.callable.
What is a Single Abstract Method (SAM) interface in java 8?
A functional inetrface is also known as Single Abstract Method interface,since it has exactly one abstract method.
How to define a functional interface in java 8?
To define a Functional ineterface in java 8, we can create an interface with exactly one abstract method.
Another way to mark an Interface with annotaion @FunctionalInterface.Even with the annotation we have to follow the rule of exactly one abstract method.
Why do we need functional interface in java?
Functional interfaces are mainly used in lambda expressions, Method reference and constructor references.
In functional programming code can be treated as data. For this purpose lambda expressions are introduced. They can be used to pass a block of code to another method object.
Functional interface serves as a data type for lambda expressions, Since a Functional interface contains only one abstract method, the implementation of that method becomes the code that gets passed as an arguments to another method.
Is it mandatory to use @FunctionalInterface annotation to define a Functional interface in java 8?
No, it is not mandatory to mark Functional interface with @FunctionalInterface annotation.
What are the differences between Collection and Stream API in java 8?
-version
Collection API is in use since java 1.2. Stream API is recent addition to java in version 8.
-usage
Collection API is used for storing data in different kinds of data structures. Stream API is used for computation of data on a large set of objects.
-finite
With collection API we can store a finite number of elements in a data structure. With stream API, we can handle streams of data that can contain infinite number of elemnts.
-Eager vs. Lazy
Collection API constructs objects in an eager manner. Stream API creates objects in a lazy manner.
-Multiple consumption
Most of the collection APIs support iteration and consumption of elements multiple times. With Stream API we can consume or iterate elements only once.
----------------------------------------------
SAP:
1 what is equal and hashcode contract,
2 what is index, can we create index based on two columns which shares same kind of properties.
3. write a clean code to merge 2 sorted arrays
4. how will improve performance of query from your end
5, singlton
===========================================
FIS:
1. what will the type of b and d in below code:
int a[],b;
String c[],d;
2.what all the palaces where super keyword can be used
3. there is file which has product,date, id, create a program to sort the values by each filed.
4. Write a REST API
5. clone treeset
6. suppose if you want to block perticular ip address or geograpphical ip address how to do that in servlet.
--------------------------------------------------
Java 8 new features:
1.Lambda
2. Method refrence
3. Streams
4.Enhanced Interfaces
5.New Date and Time API
6. CompletableFuture
7. Optional
Benifits of java 8
supports functional programming
ease of high volume data processing using streams ex bigdata n all
ease of getting parameter names using reflection
reusable code with enhaced collection api
smart exception handeling using optional, so we can handle null pointer exception using optional
control on jvm with new set of parameters
enhanced encryption support with base64
faster execution with nashorn javascript engine support to exectute javascript code
What is Lambda expression in java 8
it is an anonymous function , it is like methode which doesn't need modifiers name no decalarion , it can be passed as parameter in method, so we can pas code as a data. This piece of code can be passed to other objects and methods.
what are the 3 main parts of lambda expression in java
parameter list - it can have zero or more parameters. parameter list is optional to lambda
lambda arrow operator - "-> " is known as Lambda arrow operator. It separates the list of parameters and the body of lambda.
lambda expression body - The piece of code that we want to execute is written in lambda expression body.
What is the data type of lambda expression:
A lambda expression fulfills the purpose of passing code as data. The data type of a lambda expression is a functional interface . In most of the cases this is java.lang.Runnable interface.
why did the Oracle release a new version of java like java 8?
Functional programming:- The main theme of of java 8 is support for functional programming.
cloud computing :- lambda expression are very useful.
big data:- with increase in database size and growth of multi-core cpu servers, there is need for java to support such large scale systems.(support of streams)
optional:- it is best practice of exception cases, by using this program becomes very robust.it came fro guvava library of google.
What are the advantages of a lambda expression?
compare to passing the anonymous class it is easier to pass lambda expression. We can also pass a method as a parameter to other method. we can pass the code as well to the functions.
it is very useful in functional programming, cloud computing and serverless Architecture.
What is the Functional interface in java 8?
An interface with exactly one abstract method.
it can have default methods with implementation.A default method is not abstract.
ex:-Runnable, java.util.concurrent.callable.
What is a Single Abstract Method (SAM) interface in java 8?
A functional inetrface is also known as Single Abstract Method interface,since it has exactly one abstract method.
How to define a functional interface in java 8?
To define a Functional ineterface in java 8, we can create an interface with exactly one abstract method.
Another way to mark an Interface with annotaion @FunctionalInterface.Even with the annotation we have to follow the rule of exactly one abstract method.
Why do we need functional interface in java?
Functional interfaces are mainly used in lambda expressions, Method reference and constructor references.
In functional programming code can be treated as data. For this purpose lambda expressions are introduced. They can be used to pass a block of code to another method object.
Functional interface serves as a data type for lambda expressions, Since a Functional interface contains only one abstract method, the implementation of that method becomes the code that gets passed as an arguments to another method.
Is it mandatory to use @FunctionalInterface annotation to define a Functional interface in java 8?
No, it is not mandatory to mark Functional interface with @FunctionalInterface annotation.
What are the differences between Collection and Stream API in java 8?
-version
Collection API is in use since java 1.2. Stream API is recent addition to java in version 8.
-usage
Collection API is used for storing data in different kinds of data structures. Stream API is used for computation of data on a large set of objects.
-finite
With collection API we can store a finite number of elements in a data structure. With stream API, we can handle streams of data that can contain infinite number of elemnts.
-Eager vs. Lazy
Collection API constructs objects in an eager manner. Stream API creates objects in a lazy manner.
-Multiple consumption
Most of the collection APIs support iteration and consumption of elements multiple times. With Stream API we can consume or iterate elements only once.
----------------------------------------------