Java Interview QuestionsNo Comments

Object Oriented Programming

1. What is a Class?

A class is a Template. A class defines state and behavior that an object can exhibit.
 

2. What is an Object?

An instance of a class. We can create multiple objects of the same class.
 

3. What is state of an Object? 

Values assigned to instance variables of an object. State of an object might change with time.
 

4. What is behavior of an Object?

Methods supported by an object.
 

5. Explain toString method?

toString method is used to print the content of an Object. If the toString method is not overridden in a class, the default toString method from Object class is invoked. This would print some hashcode as shown in the example below. However, if toString method is overridden, the content returned by the toString method is printed.
Consider the class given below:

class Animal {

    public Animal(String name, String type) {
        this.name = name;
        this.type = type;
    }

    String name;
    String type;

}

Run this piece of code:

Animal animal = new Animal("Tommy", "Dog"); 
System.out.println(animal);//Animal@f7e6a96 

Output does NOT show the content of animal (what name? and what type?). To show the content of the animal object, we can override the default implementation of toString method provided by Object class.

Adding toString to Animal class

class Animal {
    public Animal(String name, String type) {
        this.name = name;
        this.type = type;
    }

    String name;
    String type;

    public String toString() {
        return "Animal	[name=" + name + ",	type=" + type + "]";
    }

}

Run this piece of code:

Animal animal = new Animal("Tommy","Dog"); 
System.out.println(animal);//Animal [name=Tommy, type=Dog] 

Output now shows the content of the animal object.

 

6. What is the use of equals method in Java?

Equals method is used when we compare two objects. Default implementation of equals method is defined in Object class. The implementation is similar to == operator. Two object references are equal only if they are pointing to the same object.
We need to override equals method, if we would want to compare the contents of an object.
Consider the example Client class provided below.

class Client {
    private int id;

    public Client(int id) {
        this.id = id;
    }
}

== comparison operator checks if the object references are pointing to the same object. It does NOT look at the content of the object.

Client client1 = new Client(25);
Client client2 = new Client(25);
Client client3 = client1;

//client1 and client2 are pointing to different client objects. 
System.out.println(client1 == client2);  //false

//client3 and client1 refer to the same client objects. 
System.out.println(client1 == client3);  //true 
 
//similar output to == 
System.out.println(client1.equals(client2));  //false 
System.out.println(client1.equals(client3));  //true

We can override the equals method in the Client class to check the content of the objects. Consider the example below: The implementation of equals method checks if the id’s of both objects are equal. If so, it returns true. Note that this is a basic implementation of equals and more needs to be done to make it foolproof.

class Client {
    private int id;

    public Client(int id) {
        this.id = id;
    }

    @Override 
    public boolean equals(Object obj) {
        Client other = (Client) obj;
        if (id != other.id) 
           return false;
        return true;
    }
}

Consider running the code below:

Client client1 = new Client(25); 
Client client2 = new Client(25); 
Client client3 = client1; 
 
//both id's are 25 
System.out.println(client1.equals(client2));  //true 
 
//both id's are 25 
System.out.println(client1.equals(client3));  //true

Above code compares the values (id’s) of the objects.

 

6. What is the use of equals method in Java?

Any equals implementation should satisfy these properties:
1. Reflexive. For any reference value x, x.equals(x) returns true.
2. Symmetric. For any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
3. Transitive. For any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) must return true.
4. Consistent. For any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, if no information used in equals is modified. 5. For any non-null reference value x, x.equals(null) should return false.

Our earlier implementation of equals method will not satisfy condition 5. It would throw an exception if an object of different class (other than Client) is used for comparison.

Let’s now provide an implementation of equals which satisfy these properties:

//Client class 
@Override
public boolean equals(Object obj) {
    if (this == obj) 
        return true;
    if (obj == null) 
        return false;
    if (getClass() != obj.getClass())
        return false;
    Client other = (Client) obj;
    if (id != other.id) 
        return false;
    return true;
}

 

7. What is the hashCode method used for in Java?

HashCode’s are used in hashing to decide which group (or bucket) an object should be placed into. A group of object’s might share the same hashcode.

The implementation of hash code decides effectiveness of Hashing. A good hashing function evenly distributes object’s into different groups (or buckets).

A good hashCode method should have the following properties

• If obj1.equals(obj2) is true, then obj1.hashCode() should be equal to obj2.hashCode()

• obj.hashCode() should return the same value when run multiple times, if values of obj used in equals() have not changed.

• If obj1.equals(obj2) is false, it is NOT required that obj1.hashCode() is not equal to obj2.hashCode(). Two unequal objects MIGHT have the same hashCode.

A sample hashcode implementation of Client class which meets above constraints is given below:

//Client class
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + id;
    return result;
}

 

8. What is Method Overloading?

A method having the same name as another method (in same class or a sub class) but having different parameters is called an Overloaded Method.
Example 1
doIt method is overloaded in the below example:

class Foo {
    public void doIt(int number) {}
    public void doIt(String string) {}
}

Example 2
Overloading can also be done from a sub class.

class Bar extends Foo {
    public void doIt(float number) {}
}

Day to day example of Overloading:-
• Constructors

o public HashMap(int initialCapacity, float loadFactor)

o public HashMap() { o public HashMap(int initialCapacity)

• Methods

o public boolean addAll(Collection c)

o public boolean addAll(int index, Collection c)

 

9. What is Method Overriding?

Creating a Sub Class Method with same signature as that of a method in SuperClass is called Method Overriding.
Let’s define an Animal class with a method shout.

	
public class Animal {
    public String bark() {
        return "Don't	Know!";
    }
}

Let’s create a sub class of Animal – Cat – overriding the existing shout method in Animal.

class Cat extends Animal {
    public String bark() {
        return "Meow Meow";
    }
}

bark method in Cat class is overriding the bark method in Animal class.

Day to day example of Overriding:-
HashMap public int size() overrides AbstractMap public int size()

 

10. Can super class reference variable can hold an object of sub class?

Yes. Look at the example below:

Actor reference variables actor1, actor2 hold the reference of objects of sub classes of Animal, Comedian and Hero.

Since object is super class of all classes, an Object reference variable can also hold an instance of any class.
Object object = new Hero();

public class Actor {
    public void act() {
        System.out.println("Act");
    };
}

//IS-A	relationship.	Hero	is-a	Actor	
public class Hero extends Actor {
    public void fight() {
        System.out.println("fight");
    };
}

//IS-A	relationship.	Comedian	is-a	Actor	
public class Comedian extends Actor {
    public void performComedy() {
        System.out.println("Comedy");
    };
}

Actor actor1 = new Comedian();
Actor actor2 = new Hero();

 

11. Is Multiple Inheritance allowed in Java?

Multiple Inheritance results in a number of complexities. Java does not support Multiple Inheritance.

class Dog extends Animal, Pet { //COMPILER	ERROR	
}

However, we can create an Inheritance Chain

class Pet extends Animal {}

class Dog extends Pet {}

 

12. What is an Interface?

• An interface defines a contract for responsibilities (methods) of a class.

• An interface is a contract: the guy writing the interface says, “hey, I accept things looking that way”

• Interface represents common actions between Multiple Classes.

• Example in Java api : Map interface, Collection interface.

 

13. How do you define an Interface?

An interface is declared by using the keyword interface. Look at the example below: Flyable is an interface.

//public abstract are not necessary	
public abstract interface Flyable {
    //public abstract are not necessary					
    public abstract void fly();
}

 

14. Tricky things about an Interface

Variables in an interface are always public, static, final. Variables in an interface cannot be declared private.

interface ExampleInterface1 {
    // By default - public static final. No other modifier allowed
    // value1, value2, value3, value4 all are - public static final					
    int value1 = 10;
    public int value2 = 15;
    public static int value3 = 20;
    public static final int value4 = 25; 
    // private int value5 = 10;  //COMPILER ERROR!	
}

Interface methods are by default public and abstract. Before Java 8, A concrete method (fully defined method) cannot be created in an interface. Consider the example below:

interface ExampleInterface1 {
    // By default - public abstract. No other modifier allowed      
    void method1(); // method1 is public and abstract      
    // private void method6();  // COMPILER ERROR!            
    // Below method, would have given COMPILER ERROR! in Java 7 
    // But its allowed from Java 8 onwards.      
    default void method5() {
        System.out.println("Method5");
    }
}

 

15. Can you extend an interface?

An interface can extend another interface. Consider the example below:

interface SubInterface1 extends ExampleInterface1 {
    void method3();
}

Class implementing SubInterface1 should implement both methods – method3 and method1(from ExampleInterface1)
An interface cannot extend a class.

 

16. Can a class extend multiple interfaces?

A class can implement multiple interfaces. It should implement all the method declared in all Interfaces being implemented.
An example of a class in the JDK that implements several interfaces is HashMap, which implements the interfaces Serializable, Cloneable, and Map. By reading this list of interfaces, you can infer that an instance of HashMap (regardless of the developer or company who implemented the class) can be cloned, is serializable (which means that it can be converted into a byte stream; see the section Serializable Objects), and has the functionality of a map.

interface ExampleInterface2 {
    void method2();
}

class SampleImpl implements ExampleInterface1, ExampleInterface2 {
    /*	
    A class should implement all the methods in an interface.
    If either of method1 or method2 is commented, it would	
    result in compilation error.							
    */
    public void method2() {
        System.out.println("Sample	Implementation	for	Method2");
    }

    public void method1() {
        System.out.println("Sample	Implementation	for	Method1");
    }
}

 

17. What is an Abstract Class?

An abstract class is a class that cannot be instantiated, but must be inherited from. An abstract class may be fully implemented, but is more usually partially implemented or not implemented at all, thereby encapsulating common functionality for inherited classes.

public abstract class AbstractClassExample {
    public static void main(String[] args) {
        //An abstract class cannot be instantiated									
        //Below	line gives compilation error if uncommented	
        //AbstractClassExample ex = new	AbstractClassExample();					
    }
}

 

18. When do you use an Abstract Class?

If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class.

• An example of an abstract class in the JDK is AbstractMap, which is part of the Collections Framework. Its subclasses (which include HashMap, TreeMap, and ConcurrentHashMap) share many methods (including get, put, isEmpty, containsKey, and containsValue) that AbstractMap defines.

o example abstract method : public abstract Set> entrySet();

• Another Example – Spring AbstractController

In code below “AbstractClassExample ex = new AbstractClassExample();” gives a compilation error because AbstractClassExample is declared with keyword abstract.
Day to day example in Java : HashMap & TreeMap extend AbstractMap.

 

19. How do you define an abstract method?

An Abstract method does not contain body. An abstract method does not have any implementation. The implementation of an abstract method should be provided in an over-riding method in a sub class.

//Abstract Class can contain 0 or more abstract methods
//Abstract method does not have a body					
abstract void abstractMethod1();
abstract void abstractMethod2();

Abstract method can be declared only in Abstract Class. In the example above, abstractMethod() gives a compiler error because NormalClass is not abstract.

class NormalClass {
    abstract void abstractMethod(); //COMPILER	ERROR
}

 

20. Compare Abstract Class vs Interface?

Real Difference – Apple vs Orange

Syntactical Differences

• Methods and members of an abstract class can have any visibility. All methods of an interface must be public.

• A concrete child class of an Abstract Class must define all the abstract methods. An Abstract child class can have abstract methods. An interface extending another interface need not provide default implementation for methods inherited from the parent interface.

• A child class can only extend a single class. An interface can extend multiple interfaces. A class can implement multiple interfaces.

• A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define all interface methods as public

 

21. What is a Constructor?

Constructor is invoked whenever we create an instance(object) of a Class. We cannot create an object without a constructor.

Constructor has the same name as the class and no return type. It can accept any number of parameters.

class Animal {
    String name;

    //This is called a one argument constructor.
    public Animal(String name) {
        this.name = name;
    }

    public static void main(String[] args) { 
        //Since we provided a constructor, compiler does not 
        //provide a default constructor.								
        //Animal animal = new Animal();  //COMPILER ERROR!	

        //The only way we can create Animal1 object is by using								
        Animal animal = new Animal("Tommy");
    }
}

 

22. What is a Default Constructor?

Default Constructor is the constructor that is provided by the compiler. It has no arguments. In the example below, there are no Constructors defined in the Animal class. Compiler provides us with a default constructor, which helps us create an instance of animal class.

public class Animal {
    String name;

    public static void main(String[] args) { 
        // Compiler provides this class with a default no-argument constructor.
        // This allows us to create an instance of Animal class.						
        Animal animal = new Animal();
    }
}

 

23. How do you call a Super Class Constructor from a Constructor?

A constructor can call the constructor of a super class using the super() method call. Only constraint is that it should always be the first statement.

public Animal() {
    super();
    this.name = "Default Name";
}

 

24. What is the use of this()?

Another constructor in the same class can be invoked from a constructor, using this({parameters}) method call.

public Animal() {
    this("Default Name");
}

public Animal(String name) {
    this.name = name;
}

 

25. Can a constructor be called directly from a method?

A constructor cannot be explicitly called from any method except another constructor.

class Animal {
    String name;

    public Animal() {}

    public method() {
        Animal();  //Compiler error				
    }
}