51 frequently asked java interview questions and answers for freshers (0-2 Years Experience) - Part 5(Q#41 to Q#51)

Previous posts of frequently asked Java interview questions and answers for freshers are Q#1-Q#10Q#11-Q#20Q#21-Q#30,Q#31-Q#40. This is last post of this Interview question and answer series and cover from Q#41-Q#51.
41.Which of the two methods plays significant role in HashMap working ? / How equals() ad hashCode() play important role in hashMap working ?
Answer: equals() and hashCode() are the important methods which plays an important role in working for HashMap. Before moving ahead, it is good to recall the contract between equals() and hashCode() in Java: for the given objects Object1 and Object2,
  1. If Object1.equals(Object2) returns true, then hashCode of both object should be equal. 
  2. However, if Object1.haschCode() == Object2.hashCode() returns true, then it is not necessary that they will qualify equals() test too.
    i.e: HashCode of two different object may be same, but two equals objects must have same hashCode.
HashMap stores key/value pair along with next reference of Entry type in each Entry object.
put() operation:- when a new element is added to hashmap, hashCode() is calculated based on key and finds bucket number for storing Entry object. If collision occurs(already an Entry object is there in that bucket location) then hashmap maintains a linkedlist and stores reference of newly added element in previous Entry object.
get() operation:- If get() operation is executed for a key element, map again calculate hashCode and finds bucket number. If only one entry is there then value associated with that key is returned. If multiple entry is there - linkedList will be traversed and with equals() method appropriate key/value containing Entry node is identified and value is returned.Read Internal working of HashMap in detail.

42.How do you convert an list into array in Java ?
Answer: List can be converted into array using toArray() method.
List<String> list = new LinkedList<String>();
String[] str = list.toArray(new String[list.size()]);

43.What are collections algorithm in java? Give few examples.
Answer: collections framework has various algorithms defined as static methods within the Collections class that can be applied to collections(Set,List) and Map.Some of the very commonly used operations by algorithm are : find minimum/maximum, sort elements in collection, finding an element in the collection, copy elements from one list to another, creating synchronized collections, etc. Refer it for the holistic view of Collections algorithm and methods supported.

44. How HashMap is different from HashSet ?/ Difference between HashMap and Hashtable ?
Answer: HashMap implements Map interface and HashSet implements set interface. HashMap allows null value as key however, HashSet does not allow null values.HashSet internally backed-up by HashMap instance. It does not guarantees about order of insertion of elements.Read How does HashSet uses HashMap internally?
Difference between HashMap and Hashtable:
  1. HashMap is unsynchronized, however HashTable is synchronized.
  2. HashMap allows null as key, hashTable does not allow null as key.

45.What do you mean by type safety in Java and how does generics helps  to achieve it ?

46. Annotations in Java ?
Answer: An annotation is a form of syntactic metadata that can be added to Java source code - Classes, methods, variables, parameters and packages. Annotations can also be applied to use of types from Java 8 (Refer type annotations in Java 8).
Java has predefined annotations: @Override, @SuppressWarnings, @Deprecated , (@) indicates to the compiler that what follows it is an annotation.
@Deprecated - indicates that the marked element is deprecated and should no longer be used.
@Override -  informs the compiler that the element is meant to override an element declared in a superclass.
@SuppressWarnings-  tells the compiler to suppress specific warnings that it would otherwise generate.
Annotations that apply to other annotations are called meta-annotations.Some predefined meta annotations are:
@Target- marks another annotation to restrict what kind of Java elements the annotation can be applied.
@Retention - it specifies how the marked annotation is stored(Compile time- RetentionPolicy.CLASS / Run time - RetentionPolicy.RUNTIME).
Note: Before Java 8 , annotations were only restricted to declaration, however from Java 8 annotations can also be applied to any type use, such annotations are termed as type-annotations.For example,
@NonNull String str;  //this variable is never assigned to null, Valid only from Java 8.
Custom annotations :- We can create custom annotations using @interface, see following example. Read in details about custom annotations here..
//create a annotation type
@interface ClassPreamble {
   String author();
   String Date();
//Now we can use ClassPreamble as annotation
@ClassPreamble(author = "Nikhil", date = "12-12-2014")
class MyNewClassInProject{


47. What is difference between throw and throws keyword in Java and where do we use them ?
Answer: throws and throw keyword are used in context of exception handling. As explained in Question#33, throw keyword in used to relegate exception to higher context from a given scope/method. And throws keyword is used with method signature to inform caller about this - Hey caller!! I will throw <this type> of exception , so please it is your responsibility to handle it. 
It can be spotted from division method declared in Question#33 - throws NumberFormatException.

48. Can we have two main methods in Java ? Justify your reasoning.
Answer: Yes, we an have overloaded main method. However, main() method of Java has special syntactical meaning and it must not be interfered. Below is the sample program to illustrate meian method overloading.
public class MainOverloadedExample {

  public static void main(String[] args) {
        .println("Priviledged main method,execution starts from here");
    Integer[] intArray = 123445 };

  public static void main(Integer[] intArgs) {
    System.out.println("intArry first element is " + intArgs[0]);

  public static void main(Long[] intArgs) {
    System.out.println("It is with Long arguments");
  /*public static Integer main(String[] argsName) {
    System.out.println("It is with Long arguments");

  public static void main() {
    System.out.println("Called from priviledged main method");
=========Sample Output:======================
Priviledged main method,execution starts from here
Called from priviledged main method
intArry first element is 12
In Java, public static void main(String[] args) is privileged main method, so program execution starts from here and after that other overloaded methods are executed from there.We cannot declare two main method with parameter String[] "main(String[] argsName) ", even if  return type of both main is different (why? - Remember Return type of methods does not participate in determining overloading criteria. Refer-Question#30). If we uncomment the code lines in above program, program will not compile.

49.What is class Loader in Java ? Can you name some class loader used in Java.
Answer: Class loader is part of JRE(Java Runtime Environment) which load classes in JVM dynamically.There are three default class loader used in Java: 1.Bootstrap  2.Extension 3.System or Application class loader. All these class loaders loads class files from a predefined location.
Bootstrap Class loader: It is responsible for loading standard JDK class files from JRE\lib\rt.jar (java.lang.Object and other runtime class) and i18.jar used for internationalization.
Extension Class loader: It is responsible for loading all .jar files from "jre/lib/ext" or any other directory pointed by java.ext.dirs system property.
System class loader or Application Class loader: It is responsible for loading application specific classes from CLASSPATH environment variables(or Class-Path attribute of Manifest file inside JAR).Read: How class Loader works internally in Java?

50.Difference between comparator and comparable? Explain with example. 
Answer: Comparable and Comparator interfaces are used to sort Objects in Java. Comparable interface is known for providing natural ordering and Comparator interface is known for its flexibility - sorting by plugging instance of a class's implementing Comparator interface Read Difference between comparable and comparator in more detail.

51.How do you rate your self in Java?
It is one of the most difficult question, answer is with you and depends on your understanding of Java. Answer honestly with care , have to justify during interview. 

Previous: Part 4(Q31 to Q#40 ) - Interview Q&A


  1. Hello Nikhil,

    Very nice list of java questions and answers for freshers.
    Thanks...for sharing some interesting Java questions and answers .
    I am looking for such type of blog or Website on google, coincidentally I found your blog and found your blog very nice.

    Thanks once again

Previous Post Next Post