[2021] 73 Core Java Interview Questions for 3+ Year Experienced Professionals

core java interview questions and programs

Table of Contents

Core Java Interview Questions & Programs for 5+ Year Experienced Professionals:

1.List down the few Collection API classes and interfaces you know/you used.

Collection API Classes: ArrayList, LinkedList, TreeMap, TreeSet, HashSet & HashMap

Collection API Interfaces: List, Set, Map & Collection

2. How will you print the common elements exists in the two lists/Set ?

We can do this in two ways,

  1. Using retainAll() method.
  2. For loop inside for loop to compare both the list/set and print the common elements.

Sample Program with retainAll() method:

package in.javadomain;

import java.util.ArrayList;

public class CommonElementsLst {
	public static void main(String[] args) {
		CommonElementsLst cmnElmnts = new CommonElementsLst();
		cmnElmnts.getCommonElem();
	}

	public void getCommonElem() {
		ArrayList<String> arListOne = new ArrayList<String>();
		arListOne.add("Apple");
		arListOne.add("Orange");
		arListOne.add("Pomogranate");
		arListOne.add("Pear");
		arListOne.add("Guava");
		ArrayList<String> arListTwo = new ArrayList<String>();
		arListTwo.add("Apple");
		arListTwo.add("Orange");
		arListTwo.add("Pineapple");
		arListTwo.add("Pappaya");
		arListTwo.add("Anar");
		arListOne.retainAll(arListTwo);
		System.out.println("arListOne elements" + arListOne);
		System.out.println("arListTwo elements" + arListTwo);
	}
}

Output:

arListOne elements[Apple, Orange]
arListTwo elements[Apple, Orange, Pineapple, Pappaya, Anar]

Note: arListOne.retainAll(arListTwo); updated all the values of arListOne to only common values, but same time arListTwo will have all the elements whichever we added to it.

3. What is ensureCapacity in ArrayList ?

If suppose you have ArrayList,

ArrayList<String> myLst = new ArrayList<String>();
myLst.ensureCapacity(10);

In general we don’t mention the size for ArrayList.

But in the below program I have used ensureCapacity(10) which allocates the size to 10, but still ArrayList will be extended when you try to add 11th element.

Then you would have not understanding the real purpose of ensureCapacity()?

Before understanding ensureCapacity, we should understand how ArrayList works.

Arraylist stores the data internally in array only. If you did not use ensureCapacity and trying to add the element using add() method, each time you add some element using add() method, arraylist will internally creates an array with the n+1 size and copies the existing arraylist values and stores the newly given add() method value.

Since each time we add an element all the copying thing happen internally which reduces the performance of the arraylist.

LinkedList will be a better option comparing to arraylist. But when you want improve the arraylist performance itself then Arraylist performance can be improved using ensureCapacity(10), in this case array will be created with size 10 and each time you add an element using add() method will be added direclty to the array instead of created n+1 array and copying, since capacity we have mentioned as 10 already.

Do remember: only ArrayList stores the data in an array, so LinkedList and Set will not have the ensurecapacity method.

4. What is autoboxing and unboxing ?

Autoboxing: Converting primitive data type[int,float,double,long] to wrapper class[Integer,Float,Double,Long].

Unboxing: Converting wrapper class to primitive data type.

5. What is multiple exception handling in Java 7?

Handling more than one exception in single catch block is called multiple exception handling. This feature is available only from java 7.

For example: Prior to Java 7:

try {

} catch (IOException ex) {
  logger.log(ex);
  throw ex;
} catch (SQLException ex) {
  logger.log(ex);
  throw ex;
}

From Java 7, it can be handled this way,

try {} catch (IOException | SQLException ex) {
  logger.log(ex);
  throw ex;
}

Note: It is recommended to use multiple exception handling only when you have duplicate code in catch blocks. Also jvm converts ex variable implicitly final when you handle more than one exception in the catch block, so you can not assign anything to ex variable inside the catch block.

6. What is Static Import ?

Providing access to static members without class qualification.

For example:

1 Without Static Import

package com.ngdeveloper;

public class StaticImport {
  public static void main(String[] args) {
    System.out.println(Math.PI);
  }
}

Output:

3.141592653589793

2 With Static Import

package com.ngdeveloper;

import static java.lang.Math.PI;

public class StaticImport {

  public static void main(String[] args) {
    System.out.println(PI);
  }
}

Output:

3.141592653589793

Advantages of static import:

Without qualifying the class you can directly access the static members.

Frequent use of static members from few classes will be very easy.

Readability will be good, because we have removed the class name.

Disadvantages of static import:

Maintenance is very tough if we use static imports from more than 2 or 3 classes. Because confusion happens from which file which static member is imported.

7. Where are the objects are stored in java ?

In Java, objects are created and stored in heap memory. Heap memory is one per JVM. Objects and variables/data related to the objects are also stored in the heap. So object and object related data’s will be there in the heap even after the function calls returns. But in the stack only function values will be stored and the same will be erased once it is come out of the method/function.

8. What is -Xms/-Xmx/-Xss ?

-Xms => Heap memory startup size.

-Xmx => Heap memory maximum size.

-Xss  => Stack Memory Size.

9. Iterator vs For Loop: Which is recommended for Concurrent Modification ?

Iterator allow you to remove the element, but for loop throws concurrent modification exception when you try to remove inside the for loop.

Remember: for loop internally uses iterator, but you can not use the iterator methods with for loop. But if you use iterator, you can directly use all it’s methods.

package com.ngdeveloper;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ForLoopVsIterator {

  public static void main(String[] args) {

    List <String> topSites = new ArrayList < String > ();
    topSites.add("Google");
    topSites.add("Javadomain");
    topSites.add("Facebook");

    /* For each loop - Remove - throws concurrentmodificationexception */
    for (String siteName: topSites) {
      topSites.remove(siteName);
    }

    /* Iterator allows to throw the element */
    Iterator siteNmIter = topSites.iterator();
    while (siteNmIter.hasNext()) {
      System.out.println(siteNmIter.next());
      siteNmIter.remove();
    }

  }
}

Output:

Comment iterator code & execute for loop code alone in the above program, then

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at in.javadomain.ForLoopVsIterator.main(ForLoopVsIterator.java:17)

Comment for loop & execute only iterator code,

Google
Javadomain
Facebook

10. Can we create an empty interface ?

Interface can be created without any methods/members, which is also called as marker interface.

Marker interface is marking some class and informing JVM to provide runtime behavior without any method declarations.

Marker interface examples,

java.lang.Cloneable
java.io.Serializable
java.util.EventListener
java.util.RandomAccess;

11. Can Abstract Class have main Method ?

Yes. Even you can execute the main method without any issue.

package com.ngdeveloper;

public abstract class AbstractClass {
  public static void main(String[] args) {
    System.out.println("Main method in abstract class");
  }
}

Output:

Main method in abstract class

12. Can Abstract Class have Default/Argument constructors ?

Yes.

package com.ngdeveloper;

public abstract class AbstractClass {

  public AbstractClass() {
    System.out.println("Default Constructor");
  }

  public AbstractClass(int test) {
    System.out.println("Arg Constructor");
  }

  public static void main(String[] args) {
    System.out.println("Main method in abstract class");
  }
}

Output:

Main method in abstract class

Remember: You are allowed to create an default/argument constructor inside the abstract class, but you can not instantiate it.

13. Can we create an object for Abstract class ?

We can not create an object for abstract class. If you try with the below code, you will get the “cannot instantiate the type AbstractClass” compilation error.

package com.ngdeveloper;

public abstract class AbstractClass {

  public AbstractClass() {
    System.out.println("Default Constructor");
  }

  public AbstractClass(int test) {
    System.out.println("Arg Constructor");
  }

  public static void main(String[] args) {
    AbstractClass abstractClass = new AbstractClass(); // throws compilation
    // error
    System.out.println("Main method in abstract class");
  }
}

Output:

Program can not be executed, because it will throw compilation error.

14. What is the output of the below program ?

package com.ngdeveloper;
import java.util.HashSet;
public class HashSetString {

  public static void main(String[] args) {
    String s1 = "abc";
    String s2 = new String("abc");

    HashSet & lt;
    String & gt;
    hashSet = new HashSet & lt;
    String & gt;
    ();

    hashSet.add(s1);
    hashSet.add(s2);

    System.out.println(hashSet.size());
  }
}

Output:

1

Explanation: Both s1 and s2 generates same hashcode value, so only one will be allowed inside the set. So size must be 1.

15. Will this both have/generate same hashcode ?

String s1 = "javadomain";
String s2 = new String("javadomain");

Yes. Because same string is created(“javadomain”), but one in string pool and another one in heap(new String()). Since both are same strings it will generate the same hashcode.
Note: Even “AaAa” and “BBBB” also generates same hashcode. Because same hashcode can be generated even if the two objects are different.

16. Why same hashcode generated even for different objects/String ?

Because, hashcode is just a 32 bit value, but number of objects/string is infinite. So finite hashcode values with infinite objects/strings surely creates same hashcode for different objects/strings, this we will also call as “collision”;

17. Can we create interface inside interface ?

Yes. You are allowed to create an interface inside another interface. This we also call as Nested Interface. Remember subinterface can be accessed only with parent interface/class.

Example:

package com.ngdeveloper;

public interface Interface {
  interface interfaceInside {
    public void print();
  }
}

In java, Entry is the subinterface exist in the Map interface. So we need to access Entry using Map like this(Map.Entry).

import com.ngdeveloper.Interface.interfaceInside;

Mainly nested interface is used to group all the similar interfaces.

Sample Program with Nested Interface:

Interface.java:

package com.ngdeveloper;

public interface Interface {

  interface interfaceInside {

    public void print();

  }
}

NgDeveloper.java:

package com.ngdeveloper;

import com.ngdeveloper.Interface.interfaceInside;

public class NgDeveloper implements interfaceInside {

  public static void main(String[] args) {
    Javadomain javadomain = new Javadomain();
    javadomain.print();

  }

  @Override
  public void print() {
    System.out.println("Print method in inside interface");

  }
}

Output:

Print method in inside interface

18. How to allow only unique elements in ArrayList or LinkedList ?

We know List allows duplicates. We have to use Set when we don’t want duplicates. But sometime you can expect this kind of question in interviews.
Ans: We need to override arraylist/linkedlist add() method to not to allow duplicate elements.

Program with arraylist add() method override:

package com.ngdeveloper;

import java.util.ArrayList;

public class ArrayListAddOverride extends ArrayList<Object>{
  @Override
  public boolean add(Object obj) {

    if (!contains(obj)) {
      return super.add(obj);
    } else {
      return false;
    }
  }

  public static void main(String[] args) {
    ArrayListAddOverride myOverridedList = new ArrayListAddOverride();
    myOverridedList.add("Java");
    myOverridedList.add(".Net");
    myOverridedList.add("Java");
    myOverridedList.add("C");
    System.out.println(myOverridedList);
  }
}

Output:

[Java, .Net, C]

19. Which one is most recommended out of these two ?

Set<String> mySet = new HashSet<String>();
HashSet<String> hashSet = new HashSet<String>();

Set<String> mySet = new HashSet<String>();

Creates a HashSet instance to mySet reference with the type of Set.

HashSet<String> hashSet = new HashSet<String>();

Creates a HashSet instance to hashSet reference with the type of HashSet.
Creating reference this way is most recommended,

Set<String> mySet = new HashSet<String>();

Because if you like to change from HashSet to LinkedHashSet/Treeset, you can easily change it to that, since LinkedHashSet/Treeset also implements Set interface.

If you created reference with Set interface even though you change to linkedhashset/treeset you do not want to modify in any places. But if you created reference with hashset and when you try to change to linkedhashset/treeset, then few methods which exist in the hashset may not be available in linkedhashset/treeset, so more code changes required at that time. So it’s always recommended to create and use references in collections[Set/List/Map] with interfaces than it’s implemented classes.

20. Can interface extend another interface ?

Yes.

Interfaces are,

  • Can be extended by other interfaces
  • Can be implemented by classes
  • Can not be instantiated.

21. What is generics & Why we need generics ?

Generics have been introduced with Java 1.5.

Without Generics: [Allowing all type]

List myList = new ArrayList();

With Generics: [Restricting to allow only mentioned type]

List<String> myList = new ArrayList<String>(); // allows only String
List<Employee> myList = new ArrayList<Employee>(); // allows only Employee object
List<Integer> myList = new ArrayList<Integer>(); // allows only Integers

Why we need generics ?

1. Generics avoids typecasting[because without generics, all type is allowed, so before doing any operations with the value/object, we have to cast it the required type to avoid typecast exception]

2. Generics helps to fix the issues at compile time itself, but without generics, more possibility at runtime only.

22. What is the difference between == and equals() in java ?

== will compare the reference of the object.
equals() will compare the content of the objects.

Program with detailed explanations:

package com.ngdeveloper;

public class ArrayForEach {
  public static void main(String[] args) {
    // created in the string pool
    String s1 = "Java";
    // created in the heap memory
    String s2 = new String("Java");

    // created in the string pool
    String s3 = "Java";
    // created in the string pool
    String s4 = "Java";

    // created in the heap memory
    String s5 = new String("Java");
    // created in the heap memory
    String s6 = new String("Java");

    /* hashcode of all the values */
    System.out.println(s1.hashCode());
    System.out.println(s2.hashCode());
    System.out.println(s3.hashCode());
    System.out.println(s4.hashCode());
    System.out.println(s5.hashCode());
    System.out.println(s6.hashCode());

    /* == comparisons*/
    // one in heap and another one in string pool
    if (s1 == s2) {
      System.out.println("s1 == s2 ==&gt; true");
    } else {
      System.out.println("s1 == s2 ==&gt; false");
    }

    // both in string pool
    if (s3 == s4) {
      System.out.println("s3 == s4 ==&gt; true");
    } else {
      System.out.println("s3 == s4 ==&gt; false");
    }

    // both in heap, but two different entries will be created
    if (s5 == s6) {
      System.out.println("s5 == s6 ==&gt; true");
    } else {
      System.out.println("s5 == s6 ==&gt; false");
    }
    /* equals comparisons*/
    if (s1.equals(s2)) {
      System.out.println("s1.equals(s2) ==&gt; true");
    } else {
      System.out.println("s1.equals(s2) ==&gt; false");
    }

    if (s3.equals(s4)) {
      System.out.println("s3.equals(s4) ==&gt; true");
    } else {
      System.out.println("s3.equals(s4) ==&gt; false");
    }

    if (s5.equals(s6)) {
      System.out.println("s5.equals(s6) ==&gt; true");
    } else {
      System.out.println("s5.equals(s6) ==&gt; false");
    }

  }
}

Output:

2301506
2301506
2301506
2301506
2301506
2301506
s1 == s2 ==> false
s3 == s4 ==> true
s5 == s6 ==> false
s1.equals(s2) ==> true
s3.equals(s4) ==> true
s5.equals(s6) ==> true

Explanations:

== will compare always the reference of the object.

  • s1 == s2 – FALSE (Because one object created in string pool and another one created in heap memory, so two different references so it became false.)
  • s3 == s4 – TRUE (Because first it creates an object in the string pool, second time it will not create one more string in the string pool instead, it will return the same string reference. Since string is immutable object).
  • s5 == s6 – FALSE (Because both will be created in the heap memory as two different entries, so two different references)

equals() method will compare the object.

  • s1.equals(s2) – TRUE (Because both will generate the same hashcode and also the same value(“Java”), so returns true)
  • s3.equals(s4) – TRUE (Because both will generate again the same hashcode and also the same value(“Java”), so returns true)
  • s5.equals(s6) – TRUE (Because both will generate again the same hashcode and also the same value(“Java”), so returns true)

Remember:

for Strings “AaAa” & “BBBB” same hashcode only will be generated. But as we know same hashcode can be generated for two different objects, That time both == and equals() method will become FALSE.

equals() will compare both hashcode and the object. so here object is not equal, so it returns FALSE only.

23. What is the output of the below program ?

package com.ngdeveloper;

import java.util.HashSet;

public class HashSetString {

  public static void main(String[] args) {
    String str = "100";
    Integer intr = 100;

    HashSet hashSet = new HashSet();

    hashSet.add(str);
    hashSet.add(intr);

    System.out.println(hashSet.size());
  }
}

Output:

2

Explanation: One is string object and another one is Integer wrapper class object, so both the entry will be added to the hashset eventhough we have given the same value.

24. Scenario: Think you have a arraylist with 3 values Java, C,C++ and you want to move only C and C++ to another list. How did you achieve this without loops ?

We can achieve using subList(first_index,last_index) method in arraylist.
Sample program with subList:

package com.ngdeveloper;

import java.util.ArrayList;
import java.util.List;

public class ArrayForEach {
  public static void main(String[] args) {
    List < String > myLst = new ArrayList < String > ();
    myLst.add("Java");
    myLst.add("C");
    myLst.add("C++");

    List < String > subList = myLst.subList(1, 2);
    for (String string: subList) {
      System.out.println(string);
    }
  }
}

Output: [Moved to another list named subList]

C
C++

25. Scenario: Think you have a arraylist with 3 values Java, C,C++ and I want to replace C to PHP, How did you achieve that ?

We can achieve this using set() method in arraylist. In the Set method we need to pass two values(first -> position, second->value).

myLst.set(1, “PHP”); which will replace the first position value with “PHP”.

Sample program with Set() method:

package com.ngdeveloper;

import java.util.ArrayList;
import java.util.List;

public class ArrayForEach {
  public static void main(String[] args) {
    List < String > myLst = new ArrayList < String > ();
    myLst.add("Java");
    myLst.add("C");
    myLst.add("C++");

    // before setting
    System.out.println("Before setting the value");
    for (String string: myLst) {
      System.out.println(string);
    }

    System.out.println("--------------------");
    myLst.set(1, "PHP");
    System.out.println("After setting the value");
    // after setting
    for (String string: myLst) {
      System.out.println(string);
    }
  }
}

Output:

Before setting the value
Java
C
C++
--------------------
After setting the value
Java
PHP
C++

26. Scenario: Think you have a ArrayList with 4 values [google,gmail,flipkart and amazon], you need to append .com to all the values of the list. Final list should be [google.com,gmail.com,flipkart.com and amazon.com]. How do you program it ?

Iterate all the values and just append .com to all the values using string concat method.

package com.ngdeveloper;
import java.util.ArrayList;

public class ListsDotCom {
  public static void main(String[] args) {
    ListsDotCom ld = new ListsDotCom();
    ld.addDotCom();
  }
  public void addDotCom() {
    ArrayList < String > arLst = new ArrayList < String > ();
    arLst.add("google");
    arLst.add("gmail");
    arLst.add("flipkart");
    arLst.add("amazon");
    ArrayList<String> dotComLst = new ArrayList<String>();
    for (String temp: arLst) {
      temp = temp.concat(".com");
      dotComLst.add(temp);
    }
    System.out.println("list is" + dotComLst);
  }
}

Output:

list is[google.com, gmail.com, flipkart.com, amazon.com]

27. Write a program to count the value of the integer string.

eg: String s ="1234567" then output should be: 28

Program to count the integer string value:

package com.ngdeveloper;
public class AddsOper {
  public static void main(String[] args) {
    AddsOper ads = new AddsOper();
    ads.add();
  }
  public void add() {
    String s = "1234567";
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
      count = count + Character.getNumericValue(s.charAt(i));
      System.out.println("count is : " + count);
    }
  }
}

Output:

count is : 28

28.If String s1 = “JAVA”; and String s2 = s1; What will be the output of s1==s2 and s1.equals(s2) ?

s1==s2: TRUE

When String s1=”JAVA”; executes then JAVA string will be created in the string pool with s1 as reference.

When String s2=s1; executes then same already created “JAVA” reference will be returned to s2 since the same string “JAVA” already exist in the string pool.
So s1 and s2 points to the same reference, it became TRUE.
s1.equals(s2): TRUE

If you print s1.hashcode() and s2.hashcode(), both will print the same integer values, because both is having the “JAVA” value only. So s1.equals(s2) returns true only.

Remember: equals() won’t work only with hashcode, because hashcode can be same for two differnt objects also. But it will check both hashcode and objects equality. here both the hashcodes are same and value also JAVA, so it returned TRUE.

Sample program:

package com.ngdeveloper;

public class EqualsUnderstanding {
  public static void main(String[] args) {

    String s1 = "Java";

    String s2 = s1;

    // hashcode
    System.out.println(s1.hashCode());
    System.out.println(s2.hashCode());

    if (s1 == s2) {
      System.out.println("s1==s2 true");
    } else {
      System.out.println("s1==s2 false");
    }

    if (s1.equals(s2)) {
      System.out.println("s1.equals(s2) true");
    } else {
      System.out.println("s1.equals(s2) false");
    }
  }
}

Output:

2301506
2301506
s1==s2 true
s1.equals(s2) true

29. What is Legacy class/Legacy interface and list a few legacy classes and interfaces ?

Legacy Classes/Legacy Interfaces:

Collection framework were introduced in Java 1.2 version. Before collection comes, few classes/interfaces and it’s methods were used to store and retrieve the objects.
Those classes/interfaces are called legacy classes/legacy interfaces.
Legacy classes:
HashTable
Vector
Dictionary
Properties
Stack

Legacy Interfaces:
Enumeration

Note: All legacy class definitions can be found at java.util package and all are synchronized.

30. Can we remove the collection(set/arraylist) elements based on the index value using iterator/listiterator ?

No. We can not remove any elements based on the index value. Because remove() method does not take any index position arguments in both iterator() and listiterator() interfaces.

Also remove() will remove the elements whichever is returned by next()/previous() methods.

31. Scenario: Given input number should be added with its digits till it become single digit number.

Eg: 917 => Add [17] => Again Add[8]
if 18 => Add [9]
This you can do in lot of ways, below is the one way to achieve this result.
Program to add numbers till it reach single digit:

package com.ngdeveloper;
public class SingleDigit {
  public static void main(String[] args) {
    SingleDigit sd = new SingleDigit();
    sd.printSingleDigit();
  }

  public void printSingleDigit() {
    String s = "917";
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
      count = count + Character.getNumericValue(s.charAt(i));
    } // checking if number is equal or more than 10, if so returning the same adding process if (count >= 10) {
    String s1 = String.valueOf(count);
    count = 0;
    for (int i = 0; i < s1.length(); i++) {
      count = count + Character.getNumericValue(s1.charAt(i));
    }
    System.out.println("value is " + count);
  }
}
}

Output:

value is 8

32. Scenario: Think you have list of website names in the arraylist, there can be n number of duplicates also. Now I wanted to get the count of all the website names.

You are free to use any collection ? How do you program this ?

package com.ngdeveloper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
public class CountOfWebsites {
  public static void main(String[] args) {
    CountOfWebsites cw = new CountOfWebsites();
    cw.cntWebsites();
  }
  int count = 0;
  public void cntWebsites() {
    // list of websites - need to find the count for this arraylist values only
    ArrayList < String > wbstsHitByUsrsLst = new ArrayList < String > ();
    wbstsHitByUsrsLst.add("google.com");
    wbstsHitByUsrsLst.add("yahoo.com");
    wbstsHitByUsrsLst.add("flipkart.com");
    wbstsHitByUsrsLst.add("amazon.com");
    wbstsHitByUsrsLst.add("flipkart.com");
    wbstsHitByUsrsLst.add("google.com");
    wbstsHitByUsrsLst.add("google.com");
    wbstsHitByUsrsLst.add("google.com");
    wbstsHitByUsrsLst.add("flipkart.com");
    wbstsHitByUsrsLst.add("amazon.com");

    // hashmap created with site names and count
    HashMap < String, Integer > fxdWbstsMp = new HashMap < String, Integer > ();
    fxdWbstsMp.put("google.com", 0);
    fxdWbstsMp.put("yahoo.com", 0);
    fxdWbstsMp.put("flipkart.com", 0);
    fxdWbstsMp.put("amazon.com", 0);
    fxdWbstsMp.put("ebay.com", 0);
    Set < Entry < String, Integer >> hshSet = fxdWbstsMp.entrySet();

    // iterating and comparing both the collection and incrementing the counter in hashmap
    for (String tempObj1: wbstsHitByUsrsLst) {
      for (Entry < String, Integer > tempObj2: hshSet) {
        if (tempObj1.equalsIgnoreCase(tempObj2.getKey())) {
          count = tempObj2.getValue() + 1;
          fxdWbstsMp.put(tempObj2.getKey(), count);
        }
      }
    }

    // printing sitename with it's respective counts
    for (Entry < String, Integer > mainMp: fxdWbstsMp.entrySet()) {
      System.out.println(mainMp.getKey() + "===" + mainMp.getValue());
    }
  }
}

Output:

google.com===4
yahoo.com===1
ebay.com===0
amazon.com===2
flipkart.com===3

33. Write a program to count only the vowels in the given string.

if input is “Naveen” then output should be 3 [a,e,e].
Program to count the vowels of the string:

Example Program:

package com.ngdeveloper;
import java.util.ArrayList;

public class VowelsCount {
  public static void main(String[] args) {
    VowelsCount vc = new VowelsCount();
    vc.countOfVowels();
  }

  public void countOfVowels() {
    ArrayList < Character > arLst = new ArrayList < Character > ();
    arLst.add('a');
    arLst.add('e');
    arLst.add('i');
    arLst.add('o');
    arLst.add('u');
    ArrayList < String > vowelsLst = new ArrayList < String > ();
    String s = "Naveen";

    // converting string to charArray.
    char[] c = s.toCharArray();

    // comparing the chararray with the arraylist of vowels
    for (Character tempObj1: arLst) {
      for (Character tempObj2: c) {
        if (tempObj1.equals(tempObj2)) {
          vowelsLst.add(tempObj1.toString());
        }
      }
    }

    System.out.println("vowels list" + vowelsLst);
    System.out.println("vowels list size" + vowelsLst.size());
  }
}

Output:

vowels list[a, e, e]
vowels list size 3

34. Scenario: I got some exception, flow went to catch block. I have few codes after catch block. I don’t want to execute those codes if I get any exception.

Will this happen by default or we need to do/add anything from our side ?

In this below program, code after catch block also executes even when exception occured:

Example Program:

package com.ngdeveloper;
public class TryCatchSample {
  public static void main(String[] args) {
    TryCatchSample tryCatch = new TryCatchSample();
    tryCatch.testException();
  }
  public void testException() {
    String s = "ngdeveloper.com";
    try {
      int i = 10 / 0;
    } catch (ArithmeticException ae) {
      System.out.println("Arithmetic Exception Occured");
    }
    System.out.println(s);
  }
}

Output:

Arithmetic Exception Occured
ngdeveloper.com

After return added in the catch,

catch (ArithmeticException ae) {
  System.out.println("Arithmetic Exception Occured");
  return;
}

Output:

Arithmetic Exception Occured

Explanation:
In the above program even after the exception, program continued to execute and printed “Javadomain.in”.

Remember:

  • If try block has 100 line and exception occurred at line number 50 then remaining 50 lines will be skipped, because the flow went to catch block.
  • But after catch if anything given, then surely it will execute those statements also.
  • If you want to avoid executing the codes after catch block, we need to add “return;” in catch block last line.

35. Scenario: I have a arraylist with 3 elements(C,C++,Java) and I am executing this snippet, what will happen?

arLst.set(5,"PHP");

You will get IndexOutOfBoundsException. Because the size is just 3 and we are trying to access the index 5 in the set method.

What set() method will do ? Set method will replace the given index value with the given value.

Program with IndexOutOfBoundsException: 

package com.ngdeveloper;
import java.util.ArrayList;
public class OperationsOnList {
  public static void main(String[] args) {
    OperationsOnList opr = new OperationsOnList();
    opr.operations();
  }
  public void operations() {
    ArrayList < String > arLst = new ArrayList < String > ();
    arLst.add("C");
    arLst.add("C++");
    arLst.add("Java");
    System.out.println("values in list before updating" + arLst);
    arLst.set(5, "PHP");
  }
}

Exception occurred, because index size is 5 but total list size itself 3 only.

values in list before updating[C, C++, Java]
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 3
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.set(Unknown Source)
at in.javadomain.OperationsOnList.operations(OperationsOnList.java:14)
at com.ngdeveloper.OperationsOnList.main(OperationsOnList.java:6)

Program with correct index: Updates value from C++ to PHP

package com.ngdeveloper;
import java.util.ArrayList;
public class OperationsOnList {
  public static void main(String[] args) {
    OperationsOnList opr = new OperationsOnList();
    opr.operations();
  }
  public void operations() {
    ArrayList < String > arLst = new ArrayList < String > ();
    arLst.add("C");
    arLst.add("C++");
    arLst.add("Java");
    System.out.println("values in list before updating" + arLst);
    arLst.set(1, "PHP");
    System.out.println("values in list after updating" + arLst);
  }
}

Output:

values in list before updating[C, C++, Java]
values in list after updating[C, PHP, Java]

36. Scenario: Think you have two different interfaces A and B with the integer value of i = 10 and i=15 respectively. Now both the interfaces are implemented in the main class and trying to print the i value. Which interface value will be printed ?

It will throw ambiguous exception. Because in both the interfaces variable i exist, so it will get confusion like which interface value should print. So ambiguous compilation error will occur.

Remember: If you have i=10 in both the interfaces also will throw the same error only. It will not bother about the value assigned to it.

Program with Interface variable Ambiguity Example:

package stringTest;

public interface A {

  int i = 10;
}

package stringTest;

public interface B {

  int i = 15;
}

package stringTest;

public class Main implements A, B {

  public static void main(String[] args) {
    System.out.println(i);
    //The field i is ambiguous
  }

}

Output:

Compilation Error:
//The field i is ambiguous

37. Is this both different from each other and which one is correct ?

public class Main extends A implements B

(OR)

public class Main implements B extends A

public class Main extends A implements B: correct syntax when you are extending the class and also implementing the interface.

If you try to put like this,

public class Main implements B extends A: then you will be getting the compilation error.

38. Can we have a try block without catch and finally blocks ?

No. We can not have only try block. We must have either catch block/finally block/both followed by try block.
Only Try block: [Compilation error]

package com.ngdeveloper;
public class TryCatchFinally {
  public static void main(String[] args) {
    try {
      int i = 10;
    }
  }
}

// Throwing Compilation error.
Try with only Catch: [No compilation error]

package com.ngdeveloper;
public class TryCatchFinally {
  public static void main(String[] args) {
    try {
      int i = 10;
    } catch (Exception e) {

    }
  }
}

Try with only Finally: [No compilation error]

package com.ngdeveloper;
public class TryCatchFinally {
  public static void main(String[] args) {
    try {
      int i = 10;
    } finally {

    }
  }
}

Try with both Catch & Finally: [No compilation error]

package com.ngdeveloper;
public class TryCatchFinally {
  public static void main(String[] args) {
    try {
      int i = 10;
    } catch (Exception e) {

    } finally {

    }
  }
}

39. Is finally block can have try catch ?

Yes. Finally block can have try catch/try finally/try catch finally.
Finally block with try catch sample:

package com.ngdeveloper;
public class TryCatchFinally {
  public static void main(String[] args) {
    try {
      int i = 10;
    } finally {
      try {

      } catch (Exception e) {

      } finally {

      }
    }
  }
}

Note: Finally inside finally and try inside try is also allowed in java.

40. How to avoid/skip/stop executing finally block ?

finally block will be executed all the time. But it will not be executed if you terminate the program by,

System.exit(0);

Stop executing finally block Example:

package com.ngdeveloper;
public class TryCatchFinally {
  public static void main(String[] args) {
    try {
      int i = 0;
      System.out.println(10 / i);
    } catch (Exception e) {
      System.exit(0);
    } finally {
      System.out.println("Very gud!");
    }

  }
}

No Output

But If you just comment the System.exit(0). You will be getting the output as “Very gud!“;

41. How do you get a ASCII value/Unicode of a given number/alphabet in java ?

We can get the ASCII value/Unicode value using the String function “codePointAt”.
Java Program to get the AsCII Value/unicode value using codePointAt function:

Example Program:

package com.ngdeveloper;

public class TryCatchFinally {
  public static void main(String[] args) {
    String s = "2";
    String s1 = "A";
    String s2 = "a";
    System.out.println("ASCII value of 2 is :" + s.codePointAt(0));
    System.out.println("ASCII value of A is :" + s1.codePointAt(0));
    System.out.println("ASCII value of a is :" + s2.codePointAt(0));
  }
}

Output:

ASCII value of 2 is :50
ASCII value of A is :65
ASCII value of a is :97

42. What is the output of the below program ?

Example Program:

public class NullString {
  public static void main(String[] args) {
    String s1 = null;
    String s2 = null;
    if (s1 == s2) {
      System.out.println("true");
    } else {
      System.out.println("false");
    }

    if (s1.equals(s2)) {
      System.out.println("true");
    } else {
      System.out.println("false");
    }
  }
}

Output:

true
Exception in thread "main" java.lang.NullPointerException
at NullString.main(NullString.java:11)

43. Difference between StringBuilder and StringBuffer?

StringBuffer: 

  • StringBuffer is mutable, means instance of an object can be modified without creating new object.
  • StringBuffer is synchronized.
  • StringBuffer is thread safe.
  • StringBuffer is slow than StringBuilder.

StringBuilder:

  • StringBuilder is also mutable, means in StringBuilder also instance of an object can be modified without creating new object.
  • StringBuilder is not synchronized
  • StringBuilder is not thread safe.
  • StringBuilder is faster than StringBuffer, since it is not synchronized and not thread safe.

44. Difference between concat() and append() ?

concat():

  • String has concat method, remember string is immutable.
  • It adds a string to another string.
  • It will create the new object after concatenation done, since it is a immutable.

append():

  • StringBuilder and StringBuffer has append method, remember these two are mutable.
  • It appends a char or char sequence to a string.
  • It will not create a new object, since it is a mutable one.

45. Difference between + and concat() ?

Concat():

  • String must not be null, if it is null then it will throw null pointer exception.
  • Argument must be string for concatenation using concat().

+ Operator:

  • String can be null and it will not throw null pointer exception.
  • Any type of variable can be concatenated, it is not mandatory to be a string variable.

Example can be found here and sample for string concatenation in java.

46. Difference between Array vs ArrayList ?

Array:

  1. Size must be defined during initialization itself.
  2. Size can not be resized once initialized.
  3. Size of the array calculated using length.
  4. Both objects and primitives can be stored.

ArrayList:

  1. Size can be resized after initialized.
  2. It is not mandatory to specify the size during initialization.
  3. Size of the ArrayList calculated using size().
  4. Only objects (wrapper class objects) can be stored in ArrayList (not only arraylist in all collections). But anyhow we can able to store the primitive data types using Autoboxing (available after java 1.5).
  5. ArrayList dynamically increase the size, here we are going to initialize arraylist with size 5, but once the 6th element inserted then it will automatically increases its size.
  6. Size of the ArrayList can not be identified till the element added in the arraylist eventhough we specified it’s size.

47. What is Autoboxing and Unboxing ?

Autoboxing: Converting primitive data type to wrapper class objects.
Eg: int to Integer, double to Double, float to Float etc..,
Unboxing: Converting wrapper class objects to primitive data types.
Eg: Integer to int, Double to double, Float to float etc..,

Sample program can be found here

48. Difference between int[] vs Integer[] ?

Int[] :

Int array to store primitive data type (int) values. but now you can store Integer (wrapper class objects) as well because of Autoboxing feature in java (only after java 1.5).

Integer[]:

Integer Array to store Wrapper class objects (Integer), but now you can store int (primitve data types) as well because of Unboxing feature in java (only after java 1.5).

In simple words, we can tell like,

int[] => array of primitive values.
Integer[] => array of objects.

Find sample program here

49. Difference between int and Integer ?

1. It is not possible to assign null to int. But the same possible in Integer.

2. In collections we can able to use Integer for HashMap (key) or vector(Integer) or ArrayList(Integer), int cannot be used in collections.

3. If we want to use methods like toString(), doubleValue(), byteValue(),floatValue(), longValue(), shortValue() etc…, then we must have Integer(wrapper) not int (primitive).

Find sample program here

50. Is this below code snippet executes ?

Snippet 1:

final MobileObject mob = new MobileObject();
mob = new MobileObject();

No, because MobileObject mob is declared with final keyword. So it can not be reasssigned with any value.

Snippet 2:

final MobileObject mob = new MobileObject();
mob.setPrice(1000);

This snippet works, because we are not reassigning the object again, instead changing the property of the same object.

 51. When is the finalize() method called in java ?

It will be called by garbage collector,

  1. When no more references to the object.
  2. Overriding finalize() can be used to system resources disposal or to perform other clean up activities.Note: No guarantee that it will be called surely, it may not call throughout the execution cycle also.

52. What will happen if exception is thrown by the finalize method ?

If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.
Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.

53. What will be output of the below snippet ?

Example Program:

public class ToStringExample {
  public static void main(String[] args) {

    String s = "Javadomain";
    System.out.println("Only string : " + s);
    System.out.println("toString string : " + s.toString());

    ToStringExample tse = new ToStringExample();
    System.out.println("object : " + tse);
  }

  @Override
  public String toString() {
    return "Hello";
  }
}

Output:

Only string : Javadomain
toString string : Javadomain
object : Hello

 Explanation: By default if you print any object it will convert internally to string and prints the value. Default implementation of the string prints hashcode, so here overrided the same with the value “Hello”. So it prints “Hello” only for object sysout. For string s and s.toString(), it has already the value, so prints that value itself.

54. Will this block throws compilation exception ?

Example Snippet:

TreeSet<String> mySet = new TreeSet<String>();
mySet.add(null);

It will not throw any compilation exception, but when you print the set then you will get NPE exception. But the same won’t happen with hashset and linkedhashset. Since only treeset will not allow the “null”.

55. Can you guess the output of this snippet ?

Example Program:

public class NPE {

  public static void main(String[] args) {
    try {
      throw new NullPointerException();
    } catch (NullPointerException e) {
      System.out.println("NPE!");
    } catch (Exception e) {
      System.out.println("Exception!");
    }
  }
}

Output:

NPE!

56. When java has garbage collection, how out of memory error occurs ?

Garbage collection thread runs on less priority than the other running threads(including user custom threads). So if the high priority thread is running, then the garbage collection thread never runs, so we get the out of memory error.

57. Why do we need clone() method when we can create using new ?

Even both the way object creation is possible, clone() method makes it faster than the new keyword object creation method, because it just takes it from the memory and clone’s it.

Where as using new keyword, it has to be checked in the field level type testing before cloning it.

58. What are all the ways of creating the threads ?

Thread needs to be created this way,

  1. Implementing Runnable interface
  2. Extending Thread class

In both the ways, Run() method should be overridden.

59. What will happen if we call thread.run() directly instead of thread.start() ?

thread.run() method runs directly on the main/current thread instead of creating the new thread, where as thread.start creates a new thread and continuous its execution on the newly created thread.

60. What are Solid Principles in Java ?

Solid

Single Responsible: A Class should have limited or single responsibility. (then it’s good cohesion class as well).

Open/Closed Principle: A class should be written with open for extend and closed for modification.

Liskov Substitution Principle: A subclass should either inherits or leaves it’s parents attributes. But not allowed to perform any action completely opposite to it’s parents.

Interface Segregation Principle: As interface implemented classes has to implement all its methods, interface has to be segregated based on it’s functionalities to keep it small and helpful for all of it’s implementation classes.

Dependency inversion: Write code to depend abstraction rather than specifications.

61. How will you create a arraylist readonly ?

Arraylist can be created as readonly by passing the created list to unmodifiableList() method of collections class.

Same way Set/Map can also be created as readonly using the methods unmodifiableSet and unmodifiableMap available in the collections.

unmodifiableCollection() generic method can also be used for any type of colleciton to make it as readonly collection.

62. Explain Association/Aggregation and composition in detail.

Aggregation and composition are specialized form/subset of Association only.

enter image description here

Association: Each object has its own life-cycle, so one object life-cycle activities like create/deletions will not have any impact / create any issues on another objects, Means objects are completely independent.

Aggregation: It is a specialized form of association, object can be in parent-child hierarchy, but if the parent object destroyed, child object can still be alive.

Composition:It is a specialized form of aggregation. object will be in parent-child hierarchy, and if the parent object destroyed, then all its child object will also be destroyed.

Eg 1: Man has a heart, if man died then his heart also would have died.

Eg 2: House can contain multiple rooms – there is no independent life of room and any room can not belong to two different houses. If we delete the house – room will automatically be deleted.

Eg 3: Car and wheels.

63. List down the few design patterns implemented in the java core libraries ?

  • Proxy: PersistanceContext
  • Interpreter: PatternMatching/Regex/Format
  • Singleton: System/getRuntime()
  • Factory: Calendar
  • Builder: StringBuilder/StringBuffer

Detailed answers available in stackoverflow at GoF Design patterns in Java Core Lib

64. Can we create our own market interface in java ?

Yes, We can create our own marker interface and by using instanceof keyword we can check the instance and perform some operations occordingly. But as like in the inbuilt market interfaces JVM’s can’t do anything with our own created market interfaces.

65. What is Future interface in Java and What is the use of it ?

Future interface is available in java.util.concurrent package and it can be used for inter thread communication.

It has the below methods:

cancel()
isCancelled()
isDone()
get()

66. Write a small program with Java 8 Stream:

This below program just filters the value which has .com extension and moves that alone to different list using java 8 stream api.

Example Program:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Streams {

  public static void main(String[] args) {

    List<String> sitesList = new ArrayList<String>();
    sitesList.add("www.google.com");
    sitesList.add("www.facebook.com");
    sitesList.add("www.ngdeveloper.com");
    sitesList.add("www.youtube.com");
    List<String> onlyDotComSites = sitesList.stream().filter(siteNm -> siteNm.toString().contains(".com"))
      .collect(Collectors.toList());
    System.out.println(onlyDotComSites);
  }

}

Output: (We have still better way for this logic? Can you try that and share in the comment ?)

[www.google.com, www.facebook.com, www.youtube.com]

67. Example program with Java 8 Stream forEach with Consumer interface

This program uses consumer interface along with java 8 foreach, it just adds the www & .com to all the values present in the list which we are iterating using forEach.

Example Program:

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class Streams {
  public static void main(String[] args) {
    List<String> sitesList = new ArrayList<String>();
    sitesList.add("google");
    sitesList.add("facebook");
    sitesList.add("youtube");
    sitesList.forEach(new Consumer < String > () {
      public void accept(String siteNm) {
        System.out.println("Sitename is appended with www &amp; .com >>> " + "www." + siteNm + ".com");
      }
    });
  }
}

Output:

Sitename is appended with www & .com >>> www.google.com
Sitename is appended with www & .com >>> www.facebook.com
Sitename is appended with www & .com >>> www.youtube.com

68. How many wrapper classes exist in Java ?

We have 8 wrapper classes each one for one data types available.

Find the list of primitive data types -> and its equivalent wrapper classes available in java below:

(int -> Integer, float -> Float, char -> Character, boolean -> Boolean, double -> Double, long -> Long, byte -> Byte, short -> Short)

69. How many ways object can be created in java ?

Object can be created by many ways, few knows ways are:
1. Using new keyword
2. Class.forName() [but we need to know the classname and should make sure that class has public default constructor]
3. Clone creats the copy of an existing object.
4. Creating object using de-serialization [readOnly() method can return the object of the serialzied object].
5. String.class.newInstance() creats the new empty instance for string.

70. Will Object.clone() method calls the constructor ?

No, it just copies the object from the memory location, so it will not call the constructor if we try to create the object through clone() method.

71. Can we have main() method in interface ?

Yes, we can have main method in interface and it can be executed as well.

Example Program:

public interface StreamInterface {
  public static void main(String[] args) {
    System.out.println("Hello Interface!");
  }
}

Output:

Hello Interface!

The same is possible even in abstract class:

Example Program:

public abstract class StreamInterface {

  public static void main(String[] args) {
    System.out.println("Hello abstract class");
  }
}

Output:

Hello abstract class

72. Can you guess the output ?

package com.ngdeveloper;

public class Simple {

  static {
    System.out.println("3");
  }

  static {
    System.out.println("1");
  }

  static {
    System.out.println("2");
  }

  public static void main(String[] args) {
    System.out.println("4");
  }

}

Output:

3
1
2
4

Explanation:

Here, static block executes in which the order it is written. Here we get 312, the same order mentioned.

73. Can you guess the output ?

Program:

package com.ngdeveloper;

public class Simple {

  static {
    System.out.println("static 1");
  }

  {
    System.out.println("initialize block 1");
  }

  public static void main(String[] args) {
    System.out.println("main");
    Simple s = new Simple();
  }

  Simple() {
    System.out.println("constructor");
  }

  {
    System.out.println("initialize block 2");
  }

  static {
    System.out.println("static 2");
  }
}

Output:

static 1
static 2
main
initialize block 1
initialize block 2
constructor

Explanation:

  • static block executed first [static blocks executed in which the order it is written]
  • Then the main method executed
  • Then the initialize and constructor called because we tried to instantiate the class inside the main method

74. Can we instantiate / create the object inside the static block ?

75. Can we have static block inside the constructor ?

76. Can we have static /initialize blocks inside main method ?

One comment

Leave a Reply