by BehindJava

Core java interview questions and answers

Home » java » Core java interview questions and answers

In this tutorial we are going to have quick look on all the important Core java interview questions and answers.

What do you mean by Platform independence of java?

You can write and compile program in one Operating system and run in other operating system.

For example: You can compile program in Windows and can run it in Unix.

What is difference between JVM, JRE and JDK ?

  • JVM : JVM stands for Java Virtual Machine. It is virtual machine which actually runs the byte code.
  • JRE : JRE stands for Java Runtime Environment. It provides runtime environment for java code. It has JVM , libraries such as rt.jar and other files.
  • JDK : JDK stands for Java development kit. It is superset of JRE, it has JRE + compilation and debugging tools(javac and java).

What are memory areas allocated in JVM?

Memory areas allocated in JVM are:

  • Heap area
  • Method area
  • JVM language stacks
  • Program counter (PC) register
  • Native method stacks

What are some core concepts of OOPS in Java ?

Core concepts of OOPs are :

  • Encapsulation
  • Polymorphism
  • Abstraction
  • Inheritance

What is Abstraction?

Abstraction is achieved using interface and abstract class in Java.

Abstraction is a concept of exposing only essential details and hiding implementation details. It is one of the essential OOPs concept apart from encapsulation, inheritance and polymorphism. Abstraction retains only information which is most relevant for the specific purpose.

What is encapsulation?

Encapsulation in java is the process of binding related data(variables) and functionality(methods) into a single unit called class. Encapsulation can be achieved by using access modifier such as public, private, protected or default, so your class will be safe from unauthorized access by others and will be simple to maintain.

We can create fully encapsulated class by

  • Making variables private
  • Providing getters and setters methods for the accessing the variables.

What is Polymorphism in java?

Polymorphism means one name many forms. In Java, polymorphism can be achieved by method overloading and method overriding.

There are two types of polymorphism in java.

  • Compile time polymorphism.
  • Run time polymorphism.

    What is inheritance in java?

    Inheritance allows to inherit properties and methods of parent class, so you can reuse all methods and properties.

What is constructor in java?

Constructor can be considered a special code which is used to initiaze objects. It has two main points

  • Class and Constuctor name should match
  • Constructor should not have any return type else it will be same as method.

Can we declare constructor as final?

No, Constructor can not be declared as final. If you do so, you will get compile time error.

What is immutable object in java?

Immutable object is object whose state can not be changed once created. You can take String object as example for immutable object.

Why String is declared final or immutable in java?

There are various reasons to make String immutable.

  • String pool
  • Thread Safe
  • Security
  • Class Loading
  • Cache hash value

What are access modifier available in java?

It Specifies accessibility of variables, methods , constructor of class. There are four access modifier in java

  • Private : Accessible only to the class.
  • Default : Accessible in the package.
  • Protected : Accessible in the packages and its subclasses.
  • Public : Accessible everywhere

What is difference between Abstract class and interface?

You can refer difference between Abstract class and interface for more details.

Can one interface implement another interface in java?

No, One interface can not implement another interface. It can extend it using extends keyword.

What is marker interface?

Marker interfaces are interfaces which have no method but it is used to indicate JVM to behave specially when any class implement these interfaces.

For example : If you implement cloneable interface and then call .clone method of object, it will clone your object. If you do not implement cloneable interface, it will throw cloneNotSupported exception.

What is method overloading and method overriding in java?

Method overloading : Method overloading is concept that allows a class to have same method name but diferent method arguments. Method overloading is also known as compile time polymorphism.

Method overriding : If child class contain same method as parent class with same method signature. This is called method overriding. Method overriding is also known as dynamic polymorphism.

Can you override static methods in Java?

No, you can not override static methods in Java. You can create same method in child class but it won’t be dynamic polymorphism. It will be method hiding. Static methods belong at class level not at object level hence you can not override static method.

Can you override private methods in Java?

No, you can not override private methods in Java. Private methods are not visible to subclass, hence you can not override private method but you can hide it.

Difference between path and classpath in java?

Parameter Path classpath
Locate It allows operating system to locate executable such as javac, java It allows classloader to locate all .class file used by program
Overriding You can not override path variable with java setting You can override classpath by using -cp with java,javac or class-path in manifest file.
Inclusion You need to include bin folder of jdk (For example jdk1.7.1/bin) You need to include all the classes which is required by program
Used by Operating system java classloaders

What is difference between StringBuffer and StringBuilder in java?

Parameter StringBuffer StringBuilder
Thread-safe StringBuffer is thread safe. Two threads can not call methods of StringBuffer simultaneously. StringBuilder is not thread safe, so two threads can call methods of StringBuilder simultaneously.
Performance It is less performance efficient as it is thread-safe It is more performance efficient as it is not thread-safe.

What are methods you should override when you put an object as key in HashMap?

You need to implement hashcode() and equals() method if you put key as object in HashMap.

Key points to remember:

  1. If you are overriding equals method then you should override hashcode() also.
  2. If two objects are equal then they must have same hashcode.
  3. If two objects have same hashcode then they may or may not be equal
  4. Always use same attributes to generate equals and hashcode as in our case we have used name.

Can you explain internal working of HashMap in java?

There is an Entry[] array called table which has size 16. This table stores Entry class’s object. HashMap class has a inner class called Entry.This Entry have key value as instance variable.

Let’s see the structure of entry class Entry Structure.

static class Entry implements Map.Entry
{
        final K key;
        V value;
        Entry next;
        final int hash;
        ...//More code goes here
}

Whenever we try to put any key value pair in Hashmap, Entry class object is instantiated for key value and that object will be stored in above-mentioned Entry. Now you must be wondering, where will above created Entry object gets stored(exact position in table). The answer is, hash code is calculated for a key by calling Hashcode() method. This hashcode is used to calculate the index for above Entry[] table.

Why java uses another hash function internally to calculate hash value apart from hashcode method which you have implemented?

It is due to avoid large number of collisions due to bad hashcode method written by developers.

What if you don’t override hashcode method while putting custom objects as key in HashMap?

As we did not implement hashcode method, each object will have different hashcode(memory address) by default, so even if we have implemented equals method correctly, it won’t work as expected.

Can you explain internal working of HashSet in java?

HashSet internally uses HashMap to store elements in HashSet. It uses PRESENT as dummy object as value in that HashMap. HashSet uses HashMap to check duplicates in the HashSet.

What are differences between HashMap and HashSet in java?

Parameter HashMap HashSet
Interface This is core difference among them.HashMap implements Map interface HashSet implement Set interface
Method for storing data It stores data in a form of key->value pair.So it uses put(key,value) method for storing data It uses add(value) method for storing data
Duplicates HashMap allows duplicate value but not duplicate keys HashSet does not allow duplicate values.
Performance It is faster than hashset as values are stored with unique keys It is slower than HashMap
HashCode Calculation In hash map hashcode value is calculated using key object In this,hashcode is calculated on the basis of value object. Hashcode can be same for two value object so we have to implement equals() method.If equals() method return false then two objects are different.

Can you explain internal working of ConcurrentHashMap in java?

ConcurrentHashMap uses concept of Segments to store elements. Each Segment logically contains a HashMap. ConcurrentHashMap does not lock whole object , it just lock part of it i.e. Segment. Structure of Segment:

 /**
     * Segments are specialized versions of hash tables.  This
     * subclasses from ReentrantLock opportunistically, just to
     * simplify some locking and avoid separate construction.
     */
static final class Segment extends ReentrantLock implements Serializable {
 /**
      * The per-segment table.
*/
        transient volatile HashEntry[] table;
// other methods and variables
}

It stores a key value pair in a class called HashEntry which is similar to Entry class in HashMap.

static final class HashEntry {
 
  final K key;         
  final int hash;         
 volatile V value;         
 final HashEntry next; 
}

You can refer internal working of ConcurrentHashMap in java for more details.

Do we have lock while getting value from ConcurrentHashMap?

There is no lock while getting values from ConcurrentHashMap.Segments are only for write operation.In case of read operation, it allows full concurrency and provides most recently updated value using volatile variables.

How do you sort Collection of custom objects in java?

We need to implement the comparable interface to custom object class(Let’s say Country) and then implement compareTo(Object o) method which will be used for sorting. It will provides default way of sorting custom objects.

If we want to sort custom object (Lets say country) on different attributes such as name, population etc.We can implement Comparator interface and can be used for sorting. For more details, you can go through below topics.

  • Comparable in java
  • Comparator in java

What is Enum in java?

Java Enum is special data type which represents list of constants values. It is a special type of java class. It can contain constant, methods and constructors etc. You can refer Enum in java for more details.

How do you create custom exception in java?

You just need to extend Exception class to create custom exception. If you want to create Unchecked exception, then you need extend Runtime Exception.

You can refer to create custom exception in Java.

What is difference between Checked Exception and Unchecked Exception?

Checked Exception: Checked exceptions are those exceptions which are checked at compile. If you do not handle them , you will get compilation error. For example: IOException.

Unchecked Exception : Unchecked exceptions are those exceptions which are not checked at compile time. Java won’t complain if you do not handle the exception. For example: NullPointerException, ArrayIndexOutOfBoundsException