Thursday, November 18, 2021

 1. Blume Global 

    1. how do you debug on production environment JVM application if it stopped and you don't have logs.

    2. 12 factors of Microservice, or criteria for a project to be microservice,

    3. circuit breaker

    4. When the service will be called REST service, criteria

    5. difference between Spring MVC and Springboot application

    6. What is autowire annotation

    7. Difference in Multithreaded application and asynchronous application 

    8. Difference between Runnable and callable

    9. from thread dump how do figure out the cause from the running, blocking and waiting threads

    10. What is NIO

    11. Docker file contains what



Monday, February 17, 2020

1. How hashset works internally
2. Scenario where you can use hashcode and equals override.
3. which datastructure hashmap/set uses.
4. what all the new features were added in java 1.7
5. what all the scopes are there for bean in sprigboot
6. if singleton has a object of prototype then how will you overcome of this situation.
7. difference between @qualifier and @resources.
8. how will you implement logging framework in microservices.
9. if you get nullpointer exception in microservices how will you know from which service it is coming.
10. How will you initialize a mockito.(syntax)
11. what is the use of any in mockito.
12. SQL syntax to get Manager of an employee.
13. how do you get the duplicate records(syntax).
14. What is on demand injection, what is annotation for this.
15. What is chained constructor.
16. How to validate requestObject, and what if any request is null.

Tuesday, February 11, 2020

Questions by Mishraji

anant mishra

Sat, Jan 25, 11:06 AM

GE questions:
to me
Core Java
=======
1. Strings, StringBuilder, StringBuffer.. Definitions, Uses, Diff, etc.
2. Collections
-ArrayList vs LinkList.
-HashMap vs CHM.
-Iterator implementation does not have to add() method?
- Fail fast vs fail Safe Itratior implementation
-How we can create unmodifiable Collections like Map, List, Set
- How does serialisation work? Write a simple program to serialize a serialized the emp object.
-Depp cloning vs Shallow? Example and participants classes.

3. Multithreading
-Why thread?
-How many ways we can create threads?
-Where to use Runnable and extends Thread?
-Can be change Thread priority after t.start()?
-How Synchronisation works?
-Inter thread communication? use of wati(), notify() and notifyAll(). Why these methods are part of Object class.
-Sleep() vs wait()?
- join() vs yield()?
- Producer consumer program like Ping pong example?

4. Design questions
-Vending machine implementation. Just identify classes, interface and methods to expose to the user as Rest Endpoints
-Bookmyshow like implementation.
-There is a train with a bogi and in this bogi 9 compartment and each compartment has 8 seats. For given seat number tell use whether it is LOWER birth, UPPER ...

5. Coding Skills
-String reverse except for spacial letters.
Example
Input= V*s$ A AJ======>Output is ===>J*A$SAV
-Separate 0 and 1.
-Separate -ve and +ve numbers.
6. Spring and Springboot questions
-Spring bean scope? default bean scope. When to use what scope.
-How Autowring works?
-How Springboot application starts? Execution flow.
-ApplicationContext vs BenaFActory?
-Dependency injection?
- How to develop RESTFUL services using Springboot?
-GET vs POST, and UPDATE, DELETE, PUT

7. Architecture level interview with Ashish Sharma.
-32 bit vs 64 bit OS(platform)
- 32 bit vs 64 bit JAVA
- Diff b/w Array, Arraylist and LinkedList.
-How to do estimation of a given task?
- What are the complex task you handled so far(Prepare 1-2 stories).

8. HR/Manager discussion
-As usual happens. No technical question. Be honest anwser. Prepare few basic questions 
like project work, Arhitecture etc. You should be able to speek at least 15 mins about your past experience.




Telphonic 1:
Questions from
-Collections
-Exceptions(Exceptions rule in inheritence)
-Strings(SCP and intern() method use)
-REST based questions


F2F 1:
1. Why Static and uses of it.
class Test{
int a = 10;
p s v m(){
sop(a);
}

Whats the output for above code if compiler error then what kind error message.. Right answer is C.E
Then followup question : how we can initialise instance variable as they created?Ans: Using constructor.

2. Method hiding in parent chiled relationship.
3. Explain output and flow of below code
public class ClazzA {
    static {
        System.out.println("Static from A");
    }
   
    public ClazzA() {
        System.out.println("Constructor from A");
    }

    public void m1() {
        System.out.println("m1() from A");
       
    }

}

public class ClazzB extends ClazzA {
    static {
        System.out.println("Static from B");
    }
   
    public ClazzB() {
        System.out.println("Constructor from B");
    }

    @Override
    public void m1() {
        System.out.println("m1() from B");
       
    }
}

public class InheritanceFlowDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ClazzA a = new ClazzA();       
        ClazzA b = new ClazzB();
        a.m1();
        b.m1();
       

    }

}


4. Design Coffiee Vendor Machine. Rest API and resources etc.
How to handle exceptions.


====================
F2F 2.
1. How good you are in multithreading. Explain and write code to demonstrate the the use of join().
2. If a class implements an interface( has methods a,b) then can we write like

Interface i = new Clazz().
i.c();//c is not present in the interface what added in the class Clazz.
Full code for above question:
interface InterfaceA {
foo();
}
public class ClassA implements InterfaceA {

    @Override
    public void foo() {
        // TODO Auto-generated method stub
    }
    //Below is not present in the interface
    public void bar() {
        System.out.println("bar");
    }

    public static void main(String[]args) {
        InterfaceA ia = new ClassA();
        ia.bar();//Right Answer is C.E i.e code will not compile
    }
   

}

3. Why we should create Referece of Interface at the left hand side.
4. Spring Bean life cycle.

5. Design Restaurent application. Identify Rest APIs, Resources and questions based on the implementations.
6. What you will use between ArrayList and LinkedList with respect to q5.

======
F2F 3: Manager Round
1. Project description and general discussion.No technical.




F2F 4:
Javascript Promises- example on race, all etc,, ES6 arrow function.
Some problem on callback array loop

F2F 5:
HTTPClient, gave a code snippet on callback and told me to solve using promise.
some basic css questions

Round 6: With architect, telephonic interview.
Binary tree algorithm problem on hackerrank platform
Gave a binary tree and told me to convert it to string without using JSON.stringify and convert it back to binary tree.
I tried to do using traverse method but couldn’t complete in 45 min.

https://www.geeksforgeeks.org/vmware-interview-experience-set-13-staff-engineer-ui/


=============DS Questions===========
1. Delet/Print nth node from the last in sigly liniked list . 

---------------------------------

VM Ware

DS: Tech1
1. separate 0 and 1 in O(n).
2. Check whether given string  is rotated of another given string in O(n)
INDIAN,
ANINDI ==> something like that.
 
Java Questions: Tech 3
1. How to write immutable class.
2. Use of synchronised keyword.
3. Shuffle a deck of cards in List without using  Collections.shuffle().

4. How to design A System to generate tiny url.

Manage Round; Round 4
1. Project description.
2. Question related to current project.
3. How to do Performance testing(Memory) in the Browser(client side)
4. What are engines used in Chrome and Safari.
5. What is the current release of JDK.
6. Current release of Angularjs 2.==> 6 is the stable release.
7. What is the Swapping and Threshold in linux. Its related to Memory management in OS.
8. Why you are looking for change?


 
Round-1 Telephonic- Pair coding
Need to write working code on a shared document so that the interviewer can see if you can put your ideas into code
1) Given BST, find the pairs whose sum is equal to given number
2) Binary search.
Other basic algo questions i forgot.

Round-2 F2F Interview
I was interviewed for vcloud team so they asked me below questions
1) What is cloud ? Why cloud ? Advantages of cloud ? Challenges in cloud ?
2) My project
Then started on algos
3) Reverse every k nodes in linked list
Write working code
4) Reverse the elements in stack-inplace. No extra memory should be used.
I wrote iterative solution code but interviewer asked me to write recursive solution
 
 
 
1st Round:
1) Write a program to Reverse a number in Java without using builtin methods.
2) Write a program to Reverse a String in Java without using builtin methods.
3) He combined the above questions such that, no matter what we provide string or an integer or a double, the program should reverse it. Basically He was expecting method overloading concept.
4) A puzzle. You will be given with a 3 Litre container & a 7 Litre Container. Measure exactly 5 Litres of water.
5) Reverse a linked list.
6) Asked about one of my projects I mentioned in my resume.

2nd Round:
1) Detailed discussion about all my projects that I mentioned in my resume.
2) Find the common elements from 3 Lists.
3) Some questions on Object Oriented Programming Concepts.
4) Some Questions on Multi-Threading.
5) Asked in detail about ‘volatile’ variables.

3rd Round:
1) Which protocol is used by telnet?
2) Difference between telnet and ssh
3) What happens when we open a file using one tab and delete it from the other tab of the terminal
4) Some questions from Software development life cylce.
5) Basics about Virtualization & Hyperwisers.
6) Explain Cloud computing in layman’s language. (Thanks to Balaji Vishwanthan for an amazing answer for a similar question Quora) 😛 😛
 
 
 1. Search a element in a cyclic sorted array .
2.The first HackerRank challenge I had was an abstract design problem where I was told, within 90 minutes,
to write a function that detects whether a robot loops within a trajectory passed as an arbitrary commands string that controls the movement of the robot.
(e.g. GRGRGL where L stands for turn left, R for turn right and G for go one step)

-============================

Philips

Phillipse heackerearth:
1. Given a string (1-9) size N split it into groups such that each group has index started ...

Now find all possble number using all groups..
Sort the valid numbers and then find the Kth number.

2. Reduce the array size to last element such that
a[i] = [i] + [i+1]//transform until 1 element

example
1,2,3

O/p
8

Solution
1,2,3
3,5
8


=====================================

SAP -Ariba

First two rounds were completely Algorithm .

Below were te questions asked :
1st panel [ this guy had a big attitude to show to candidates]:
When i told him i am working on webservices , he asked me what do i know about Mtom .
How will you send a big binary file as a webservice call .
what is the maximum possible size of a file on a system .
Later when i told him we used ssl , following were the questions asked:
Explain the process of signing a certificate by any CA .


Later he started with algorithm :

What is arraylist . write a program simulating arraylist . I wrote the program what i have seen in jdk  library .
Later he wanted me not to use any temporary array while add operation .
What is a circular linked list .
How do find the circular link in the list [where tail points to head] .
What is the complexity of algorithm .

Panel 2 [ cool guy ]:
Write a program which returns first non repeating char from a string"google" . Very easy . Later he aske me to optimize the algo to search first non repeating char .
Write the code so that you can find find the first non repeating char in single traversal and without storing the counter in temp variable . What  is the complexity of the algoritm.
Consider array [-1,-2,-1,0,4,6,2,1,3] . Now write an algo to find the pair of all possible values which on adding returns the number  2 and later try to optimize the search algo .

Later HR told me that there panel found some area where i have to improve .
I asked HR about the process of interview as job description asked for strong OOPS and Java knowledge .
This is waht he told me:

Ariba has three kind of interview rounds .
1. Algorithm and data structure [can be any number of rounds ].
2. Database , performance tuning.
3. Design and architecture
4. java language coding skills .
5. Hiring manager round .
6. One more management round .



Three years before when i went for interview in Ariba , below is what happened .
Panel 1.
Diffrence between overriding and overloading . He was trying to change the code many times to confuse .

What is your understanding about entity beans and CMT .[ that time my resume was not having EJB in it , which i have to tell him explicitely.]
Ultimate question : what is the defference between jre running on windows and one running on unix.
What tweek can be done to make the win jre to run on unix .[ :( ]

Later i was asked to wait for a long time , and when i did nt got any response i walked away .
============================Interview @SAP===========
1. Finding connected cells in a 2d array.
https://stackoverflow.com/questions/11253027/algorithm-to-find-the-total-number-of-connected-sets-in-a-matrix
2. Desgin a data structure for below operations which works on o(1)  i.e constants time complexity.
-add(E)
-delete(E)
-getRandom()==> This is what we need to think more. For this operation we need to return element based on random number but time complexity should be constants.


3rd round java
1. Write a java program in which two threads print even odd numbers.
2. Design patters==> How to implement Adaptor pattern.
=======================================

======================================================

Sapience

First two rounds were completely Algorithm .

Below were te questions asked :
1st panel [ this guy had a big attitude to show to candidates]:
When i told him i am working on webservices , he asked me what do i know about Mtom .
How will you send a big binary file as a webservice call .
what is the maximum possible size of a file on a system .
Later when i told him we used ssl , following were the questions asked:
Explain the process of signing a certificate by any CA .


Later he started with algorithm :

What is arraylist . write a program simulating arraylist . I wrote the program what i have seen in jdk  library .
Later he wanted me not to use any temporary array while add operation .
What is a circular linked list .
How do find the circular link in the list [where tail points to head] .
What is the complexity of algorithm .

Panel 2 [ cool guy ]:
Write a program which returns first non repeating char from a string"google" . Very easy . Later he aske me to optimize the algo to search first non repeating char .
Write the code so that you can find find the first non repeating char in single traversal and without storing the counter in temp variable . What  is the complexity of the algoritm.
Consider array [-1,-2,-1,0,4,6,2,1,3] . Now write an algo to find the pair of all possible values which on adding returns the number  2 and later try to optimize the search algo .

Later HR told me that there panel found some area where i have to improve .
I asked HR about the process of interview as job description asked for strong OOPS and Java knowledge .
This is waht he told me:

Ariba has three kind of interview rounds .
1. Algorithm and data structure [can be any number of rounds ].
2. Database , performance tuning.
3. Design and architecture
4. java language coding skills .
5. Hiring manager round .
6. One more management round .



Three years before when i went for interview in Ariba , below is what happened .
Panel 1.
Diffrence between overriding and overloading . He was trying to change the code many times to confuse .

What is your understanding about entity beans and CMT .[ that time my resume was not having EJB in it , which i have to tell him explicitely.]
Ultimate question : what is the defference between jre running on windows and one running on unix.
What tweek can be done to make the win jre to run on unix .[ :( ]

Later i was asked to wait for a long time , and when i did nt got any response i walked away .
============================Interview @SAP===========
1. Finding connected cells in a 2d array.
https://stackoverflow.com/questions/11253027/algorithm-to-find-the-total-number-of-connected-sets-in-a-matrix
2. Desgin a data structure for below operations which works on o(1)  i.e constants time complexity.
-add(E)
-delete(E)
-getRandom()==> This is what we need to think more. For this operation we need to return element based on random number but time complexity should be constants.


3rd round java
1. Write a java program in which two threads print even odd numbers.
2. Design patters==> How to implement Adaptor pattern.
=======================================

=========================================================


=============DS Questions Vmware===========
1. Search a element in a cyclic sorted array . 
2.The first HackerRank challenge I had was an abstract design problem where I was told, within 90 minutes,
to write a function that detects whether a robot loops within a trajectory passed as an arbitrary commands string that controls the movement of the robot.
(e.g. GRGRGL where L stands for turn left, R for turn right and G for go one step)


Rewards360==Satessh
1. First occurence of non repeating character in Strings.
2. String with 01 and replce 0-->01 and 1--->11 or compbination of 10 to n times and then find char at kth index.

Sapeinse
1. Remove duplicate and sort in desc

MoveinSync
1.Arrays question : rain water (available on gfg), merge sort,
2. Tree questions : dfs, bfs , other traversal , zigzag traversal 
3. Coin exchange problem
4. Inorder successor in a binary tree.







 

Tuesday, March 26, 2019

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.

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.

Q2,. What is encapsulation
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 )

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.

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();
   
    }

}

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;
}


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.

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. LinkedListimplements 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:
  1. Shared Memory
  2. 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);

    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.



    ----------------------------------------------