Java Interview Question Answer for Fresher

Can we create private constructor in java?

Yes, We can declare a constructor private by using the private access specifier. If a constructor is declared with private access specifier, we are not able to create an object of the class.
we can use this private constructor in Singleton Design Pattern.

How to iterate a HashMap?

There are many ways to iterate a HashMap.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class IterateMapExample {

    public static void main(String args[]){
        Map empMap = new HashMap();
        empMap.put(1,"Raju");
        empMap.put(2,"Anita");
        empMap.put(3,"Satish");

        //#1 Using KeySet
        for(Map.Entry entrySet : empMap.entrySet()){
            System.out.println("key==" +entrySet.getKey() + ", value=="+entrySet.getValue());
        }

        //#2 Using KeySet For loop
        for(Integer id : empMap.keySet()){
            System.out.println("key==" +id + ", value=="+empMap.get(id));
        }

        //#3 Using Iterator
        Iterator> itr = empMap.entrySet().iterator();
        while(itr.hasNext()){
            Map.Entry entry = itr.next();
            System.out.println("key==" +entry.getKey() + ", value=="+entry.getValue());
        }

        //#4 Using foreach
        empMap.forEach((k,v) -> System.out.println("key==" +k + ", value=="+v));
    }
}

What is cloning in Java and How can we clone a object in java? What is clone method in java?

Cloning is the process to create exact copy of an object. The clone() method of Object class is used to clone an object.

  1. Cloneable interface must be implemented to clone the object.
  2. Need to handle CloneNotSupportedException in cach block or throws.

Exception Hierarchy in Java

Exception Hierarchy in Java

How many types of Exception?

There are two types of exception.

  1. Checked Exception.
  2. Unchecked Exception.

Difference between Checked and Unchecked Exceptions?

There are two types of exception.

  1. Checked Exception

  2. Those exception are checked on compile time. If some code throws a checked exception, then the method must either handle the exception or it must specify the exception using the throws keyword.

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    public class CheckedExceptionExample {
        public static void main(String[] args) throws IOException {
    
            FileReader file = new FileReader("C:\\folder1\\sample.txt");
            BufferedReader br = new BufferedReader(file);
    
            while(br.readLine()!=null) {
                System.out.println(br.readLine());
            }
            br.close();
        }
    }
    
    

  3. Unchecked Exception

  4. Those exception are not checked on compile time that is called Unchecked Exception. Exceptions under Error and RuntimeException classes are unchecked exceptions.

    1. ArrayIndexOutOfBoundsException is an Unchecked Exception.
    2. NullPointerException is an Unchecked Exception
    3. ArithmeticException is an Unchecked Exception
    public class UncheckedException {
        public static void main(String args[]){
            int[] intArray = new int[]{ 1,2,3,4,5,6 };
            System.out.println(intArray[10]);
        }
    }
    Output:
        Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 6
        at com.inventory.sample.UncheckedException.main(UncheckedException.java:6)
    

Difference between JDK, JRE, and JVM?

Java Architecture

JDK

JDK stands Java Development Kit. JDK provides the environment to develop, execute or run the Java program. JRE is a part of JDK and JVM is a part of JRE.

JRE

JRE stands Java Runtime Environment. JRE is a part of JDK, it provides an environment to run the java program or application onto machine. JRE does not provides development tools, its provides the functionality to run the program/application only.

JVM

JVM stands Java Virtual Machine and it is a part of JRE(Java Runtime Environment). JVM is a run-time engine to run Java applications. JVM calls the main method present in a Java code. It provides a runtime environment for driving Java applications or code. JVM is an abstract machine that converts the Java bytecode into machine language. It is called a virtual machine because it doesn't physically exist.

How class loader works in Java?

Whenever we create a ".java" file, first we need to compile it with javac "class name" command to compile the file.

The below process will be executed when we compile the file.

  1. Compile the file of ".java" to ".class"
  2. Bytecode converion will be done when we compile the ".java" file.

The next step is to run the ".class" file.

  1. Need to execute the run command to run the ".class file, example (run "file name").
  2. Whenever we execute run command, the class loader loads the class file verify the bytecodes and distributes the class related data in the JVM memory areas, such as objects goes to the heap memory, method area, stack area etc.
  3. Next part is Interpreter - JVM converts bytecode to machine language specific for the platform independent. JVM also support (JIT) just-in-time compiler.

What is Java Memory Management?

Some of the areas are created by the JVM and some of the areas are created by the threads that are used in a program. When thread start creates the dat and destroy when thread exits but the memory area created by JVM is destroyed only when the JVM exits.

Java Memory Areas

  1. Heap Area
  2. Method Area
  3. JVM Stack
  4. Native JVM Stack
  5. PC Registration

What is Heap Area?

Java Memory Areas

  1. Java stores the objects in the Heap memory.
  2. The Heap area creates during the virtual machine startup.
  3. Whenever a new object is created, object is assigned a space in the Heap.

What is Method Area?

Method area is a part of the heap memory which is shared among all the threads. The method area is allocated for class structure, superclass name, interface name, and constructors.

What is JVM Stack?

  1. Stack Area generates when a thread creates.
  2. Stack area is used to store the partial results and data which will be needed while returning the value of the method.
  3. A new Stack frame is created When a method invoke. It destroys the stack frame when the method process completes.
  4. Each frame contains own Local Variable Array (LVA).

What is Native method Stacks?

The Native method Stack is also known as C stack. A Native method Stack is created when a thread is created.

What is Garbage Collector?

The Garbage collector finds the unused objects and deletes them to free up memory. When Java programs run on the JVM, objects are created on the heap, after execution, some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up memory.

How to call Garbage Collector manually?

We can execute System.gc().

What is Stack Overflow Error?

When ever stack memeory is out of space space that time we get the Stack Overflow Error. It may occur due to not handling the termination condition or infinite recursion.

Example of Stack Overflow Error

public class StackOverflowErrorExample {
    public static void main(String args[]){
        StackOverflowErrorExample.getAdditionValue(5);
    }

    public static Integer getAdditionValue(Integer i){
        i=i+5;
        getAdditionValue(i);
        return i;
    }
}
Output:
    Exception in thread "main" java.lang.StackOverflowError
	at com.sample.StackOverflowErrorExample.getAdditionValue( StackOverflowErrorExample.java:10 )

How to increase stack size in java?

The default Java thread stack size 320kb but we can increase the size with the stack size with the one -Xss option from below list.
Go to the tomcal directory and open tomcat\bin\setenv.bat, choose one from the below list and write in the setenv.bat.

  1. java -Xss1048576
  2. -Xss1m
  3. java -XX:ThreadStackSize=1024

What is OutOfMemoryError in java?

OutOfMemoryError is a runtime error in Java. It occurs due to insufficient space in the Java heap memory.

How to increase heap size in java?

Go to the tomcal directory and open tomcat\bin\setenv.bat, add -Xms64m -Xmx256m.

  1. -Xmx to set the initial heap size in Java.
  2. -Xms to set the maximum heap size

-XX:PermGen

What is PermGen Space?

PermGen stands for Permanent Generation. Java 8 and above has no PermGen space. From Java 8 PermGen was replaced by a new memory area called Metaspace. It is also a type of heap space. JVM uses PermGen to keep track of loaded class metadata which are not changed frequently.

  1. -XX:PermGen - For setting the initial size of the Permanent Generation memory.
  2. -XX:MaxPermGen - For setting the maximum size of Perm Gen.

What is Metaspace?

MetaSpace is introduceed in Java 8 to replace the PermGen space. The MetaSpace is used to hold class metadata and the size dynamically resize based on the application’s demands.

  1. JMX (Java Management Extensions) is used to see the utilization of Metaspace.
  2. -XX:Meta SpaceSize &XX: MaxMeta SpaceSize is used to customization the size of Metaspace.

How Metaspace Works?

When new class is loaded, the JVM identified the class defination and extracts metadata about the class, including as its name, parent class, interfaces implemented, fields and methods. Subsequently, JVM allocates memory in the MetaSpace for the class’s metadata.

JVM tracks the MetaSpace’s size as well as the amount of memory utilised by each class’s information. If the MetaSpace exceeds the allocated space, JVM checks which metadata is no longer is use and start the process of Garbage Collection to clear up space.

If a class is no longer is used or the JVM shuts down, the metadata in the MetaSpace will clean up immediately.

How to check Metaspace memory size in Java program?

import java.lang.management.MemoryUsage;
public class MetaSpaceExample {
    public static void main(String args[]) {
        MemoryUsage memory = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();

        long usedMetaspace = memory.getUsed();
        long maxMetaspace = memory.getMax();

        System.out.println( "usedMetaspace="+usedMetaspace );
        System.out.println( "maxMetaspace="+maxMetaspace );

    }
}

How to see Metaspace memory sizes?

java -XX:+PrintFlagsFinal -version | grep MetaspaceSize

How to increase Metaspace memory size?

-XX:MetaspaceSize=100M

What is difference between Comparable and Comparator Interface in Java?

Comparable

  1. The Comparable compares itself with another object.
  2. The class itself must implements the java.lang.Comparable interface to compare its instances.
  3. Need to override the compareTo() method in the class itself.

Comparator

  1. The Comparator provides multiple sorting sequences.
  2. You can sort the collection on the basis of multiple elements such as id, name, age and city etc..
  3. Comparator doesn't affect the original class. The actual class is not modified.
  4. Comparator has compare() method to sort elements.

Example of Comparable in Java?

public class ComparableExample implements Comparable<ComparableExample>{
 private Integer id;
 private String name;
 private String email;
 private Integer age;


 @Override
 //Override compareTo method
 public int compareTo(ComparableExample obj) {
    if(age==obj.age)
        return 0;
    else if(age>obj.age)
        return 1;
    else
        return -1;
  }
 }  

Example of Comparator in Java?

import java.util.Comparator;
public class Employee {
    private Integer id;
    private String name;
    private String email;
    private Integer age;
    
    public Employee(Integer id, String name, String email, Integer age) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.age = age;
    }
    
    public Integer getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public String getEmail() {
        return email;
    }
    public Integer getAge() {
        return age;
    }
}
//Seperate class need to create
class DemoComtarorExample implements Comparator<Employee> {
    @Override
    //Override the compare method
    public int compare(Employee obj1, Employee obj2) {
        if(obj1.getAge() == obj2.getAge())
            return 0;
        else if(obj1.getAge() > obj2.getAge())
            return 1;
        else
            return -1;
    }
} 

What is Array in Java?

An array is a container object that holds a fixed number of values of a single type.

public static void main(String[] args) throws IOException {
    Integer[] array = new Integer[3];
    array[0]=3;
    array[1]=4;
    array[2]=5;
    or
    Integer[] array1 = {3,4,5};
}