In this post, we will see Java interview questions for 5 to 6 years experience.
When you have 5 years of experience as java developer, you need to have a good understanding of collectionsmultithreading concepts.

If you are looking for the below queries then this post will help you as well.

  • Java interview questions for 4 years experience
  • Java interview questions for 6 years experience
  • Java interview questions for 7 years experience

Here are some questions which are most asked for 5 years of experience java programmers. You might find some of the questions very easy but believe me most developers failed to answer these questions.

1. Guess the output of below program.

12345678910111213141516171819202122232425262728 package org.arpit.java2blog;class A{    void m1()    {        System.out.println(“In m1 A”);    }}class B extends A{    void m1()    {        System.out.println(“In m1 B”);    }    void m2()    {        System.out.println(“In m2 B”);    }}public class Test {     public static void main(String[] args) {        A a=new B();        a.m2();    }} 

What will be the output?
A. In m2 B
B. Compile time error
C. Runtime errorHide AnswersB. Compile time error
There will be compile-time error. Even though we are assigning B’s object to A’s reference we can call only methods which are in A from A’s reference.Further reading:
Abstraction in java
Polymorphism in java

2. Guess the output of below program.

12345678910111213141516171819202122232425 package org.arpit.java2blog; class A{    void m1() throws ArrayIndexOutOfBoundsException    {        System.out.println(“In m1 A”);    }}class B extends A{    void m1() throws IndexOutOfBoundsException    {        System.out.println(“In m1 B”);    }}public class Test {     public static void main(String[] args) {        A a=new B();        a.m1();    }} 

What will be the output?
A. In m1 B
B. Compile time error
C. Runtime errorHide AnswersA. In m1 B
This will work fine as ArrayIndexOutOfBoundsException and IndexOutOfBoundsException are Runtime exceptions and there is no rule for runtime exceptions while method overriding.

3. Guess the output of below program.

12345678910111213141516171819202122232425262728293031 package org.arpit.java2blog; import java.io.IOException; class A{    void m1() throws IOException    {        System.out.println(“In m1 A”);    }}class B extends A{    void m1() throws Exception    {        System.out.println(“In m1 B”);    }}public class Test {     public static void main(String[] args) {        A a=new B();        try {            a.m1();        } catch (IOException e) {            e.printStackTrace();        }    }} 

What will be the output?
A. In m1 B
B. Compile-time error
C. Runtime errorHide AnswersB. Compile-time error
As IOException and Exception are checked exception, so you can not broaden the scope of Exception while method overriding.

4. What will happen in case of below program?

12345678910111213 class A{    synchronized void m1()    {        System.out.println(“In m1 A”);    }    void m2()    {        System.out.println(“In m2 A”);    }} 

There are two threads T1 and T2. T1 is accessing m1 method. Will T2 be able to access m2 method on the same instance at the same time?Hide AnswersYes, T2 will be able to access m2 as it does not require a lock to access m2 method.Further reading:Object-level locking and class level locking

5. What will happen in case of below program?

12345678910111213 class A{    synchronized void m1()    {        System.out.println(“In m1 A”);    }    synchronized void m2()    {        System.out.println(“In m2 A”);    }} 

There are two threads T1 and T2. T1 is accessing m1 method. Will T2 be able to access m2 method on the same instance at the same time?Hide AnswersNo, T2 will not be able to access m2 as it requires lock to access m2 method which is already taken by T1 thread.Further reading:Object-level locking and class level locking

6. What will happen in case of below program?

12345678910111213 class A{    synchronized static void m1()    {        System.out.println(“In m1 A”);    }    synchronized void m2()    {        System.out.println(“In m2 A”);    }} 

There are two threads T1 and T2. T1 is accessing m1 method. Will T2 be able to access m2 method on the same instance at the same time?Hide AnswersYes, T2 will be able to access m2 as it requires object level lock to access m2 method and T1 thread has taken class level lock.You can read more about Object level lock vs Class level lock.

7. Guess the output of below program.

1234567891011121314151617181920212223242526272829 package org.arpit.java2blog; import java.util.HashSet; public class Customer {     String name;    int age;     Customer(String name,int age)    {        this.name=name;        this.age=age;    }    public static void main(String[] args) {         Customer c1= new Customer(“John”,20);        Customer c2= new Customer(“John”,20);         HashSet<Customer> customerSet=new HashSet<>();        customerSet.add(c1);        customerSet.add(c2);        System.out.println(customerSet.size());    }     // getters and setters

Show AnswerFurther reading:How HashSet works in java

8. Guess the output of below program.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 package org.arpit.java2blog; public class Employee {    String name;    int age;     public Employee(String name,int age)    {        this.name=name;        this.age=age;    }     @Override    public int hashCode() {        final int prime = 31;        int result = 1;        result = prime * result + age;        result = prime * result + ((name == null) ? 0 : name.hashCode());        return result;    }     @Override    public boolean equals(Object obj) {        if (this == obj)            return true;        if (obj == null)            return false;        if (getClass() != obj.getClass())            return false;        Employee other = (Employee) obj;        if (age != other.age)            return false;        if (name == null) {            if (other.name != null)                return false;        } else if (!name.equals(other.name))            return false;        return true;    }     public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }   } 

Main class

1234567891011121314151617 package org.arpit.java2blog; import java.util.HashMap;import java.util.Map; public class HashMapMain {     public static void main(String[] args) {        Employee emp1=new Employee(“Martin”,27);        Map<Employee,String> hm=new HashMap<Employee,String>();        hm.put(emp1, “Verified”);        emp1.setName(“John”);        System.out.println(hm.get(emp1));    }} 

https://760a0aafd340c67aba8d6e30019770ac.safeframe.googlesyndication.com/safeframe/1-0-37/html/container.htmlShow Answer

9. How to decide young generation and old generation size for your application?

It depends on nature of application.
If you have lots of temporary objects then there will be lot of minor gc. You can provide arguments XX:NewRatio=1 to distribute 50% to young generation and 50% to old.
By default, NewRatio=2 hence young Generation is 1/3 of total heap.
Similarly, If you have too many long-lived objects, then you might need to increase the size of tenure space by putting high value of NewRatio.

10. What is garbage collection in java?

Garbage collection is the process of identifying used and unused objects on java heap and removing unused object from the heap.
A live object means an object is still being referred to some part of program. Unused object means object is not being referred by any part of program and is eligible for garbage collection.
Programmer does not have to do manual garbage collection like C or C++. Java takes care of

11. What are types of garbage collectors in java?

You can see a detailed answer over here.

12. What is difference between Collection.synchronizedMap(map) and ConcurrentHashMap?

When you make map thread safe by using Collection.synchronizedMap(map), it locks whole map object, but ConcurrentHashMap does not lock the whole map, it just locks part of it(Segment).
You can read more about ConcurrentHashMap over here.

13. What will happen when you run below code

1234567891011121314151617181920212223242526272829303132 package org.arpit.java2blog; import java.util.HashMap;import java.util.Iterator;import java.util.Map.Entry; public class IterateMapMain {     public static void main(String args[])    {        // HashMap with Country as key and capital as value        HashMap<String,String> map=new HashMap<String,String>();        map.put(“India”,”Delhi”);        map.put(“Japan”,”Tokyo”);        map.put(“France”,”Paris”);        map.put(“Russia”,”Moscow”);         // Iterating java iterator        System.out.println(“Iterating java Iterator”);        Iterator<String> countryKeySetIterator=map.keySet().iterator();        while(countryKeySetIterator.hasNext()){            String countryKey=countryKeySetIterator.next();            map.put(“Nepal”, “KathMandu”);            System.out.println(countryKey);         }        System.out.println(“—————————–“);    } } 

Show Answer

14. Write a program to print odd even numbers using threads in sequence?

Here is the program to print odd and even numbers using threads in sequence.

public class OddEvenPrintMain {
 
    boolean odd;
    int count = 1;
    int MAX = 20;
 
    public void printOdd() {
        synchronized (this) {
            while (count < MAX) {
                System.out.println("Checking odd loop");
 
                while (!odd) {
                    try {
                        System.out.println("Odd waiting : " + count);
                        wait();
                        System.out.println("Notified odd :" + count);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                System.out.println("Odd Thread :" + count);
                count++;
                odd = false;
                notify();
            }
        }
    }
 
    public void printEven() {
 
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        synchronized (this) {
            while (count < MAX) {
                System.out.println("Checking even loop");
 
                while (odd) {
                    try {
                        System.out.println("Even waiting: " + count);
                        wait();
                        System.out.println("Notified even:" + count);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("Even thread :" + count);
                count++;
                odd = true;
                notify();
 
            }
        }
    }
 
    public static void main(String[] args) {
 
        OddEvenPrintMain oep = new OddEvenPrintMain();
        oep.odd = true;
        Thread t1 = new Thread(new Runnable() {
 
            @Override
            public void run() {
                oep.printEven();
 
            }
        });
        Thread t2 = new Thread(new Runnable() {
 
            @Override
            public void run() {
                oep.printOdd();
 
            }
        });
 
        t1.start();
        t2.start();
 
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
 
    }
}
 

15. Which design pattern you have used in your project?

You can name few design patterns such as SingletonObserver etc. which you might have used in your project.

16. What is double level locking in singleton design pattern?

Double level locking in Singleton design pattern  is used to make it thread-safe.

123456789101112131415 public static Singleton getInstance()    {         if (_instance == null) { // Single Checked             synchronized (Singleton.class)             {                 if (_instance == null)// Double checked                  {                     _instance = new Singleton();                 }            }         } return _instance;     } 

Let’s say two threads(T1 and T2) checked for null and both reached at synchronized (Singleton.class). T1 gets the lock and create instance of Singleton and return. Now T2 enters in a synchronized block, as we have checked for null again, it will not create object again.

17. Write a program to implement producer-consumer problem using BlockingQueue?

You can find detailed answer over here

18. Have you worked on Java 8? Can you share major changes in Java 8?

If you have worked on Java 8, you can share major changes such as Stream, lambda expressiondefaults method in interface etc.

19. Have you worked on Serialization? Can you tell difference between Serializable and Externalizable?

You can find detailed answer over here

20. How will you detect memory leak in your application?

There is no simple answer to this question. You can take thread dump via JVisualVM and do the analysis in eclipse memory analyzer tool.

50% LikesVS
50% Dislikes

Leave a Reply

Your email address will not be published. Required fields are marked *