Video

Latest

Java Interview Questions





Here are some commonly asked interview questions :

    Java 7

  1. What is the most suitable option to use an Interface or an Abstract Class? Why?
  2. How to make a class immutable?
  3. What type of polymorphism are there in java?
  4. What are the different use of final, finally and finalize?
  5. What is the difference between Hash and Equals in java?
  6. What is polymorphism? Explain with an example of Upcasting and Downcasting?
  7. What is abstract class? How it is different from interface?
  8. Can inheritance works with interface? Give an example.
  9. Difference between Deep copy vs Shallow copy?
  10. What type of inheritance is there in java?
  11. What is the difference between Exception and Error in Java?
  12. Can we make one abstract class final? If so why? If not so why ?

    Java 8

  1. When to use Stream?
  2. What is functional interface?
  3. What type of functional interface are there?
  4. What is optional class?
  5. What is intermediate and terminal methods?

Answers

Java 7
1. What is the most suitable option to use an Interface or an Abstract Class? Why?

An interface can be used to define a contract behavior and it can also act as a contract between two systems to interact while an abstract class is mainly used to define default behavior for subclasses, it means that all child classes should have performed the same functionality. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing a common functionality to unrelated classes.

2. How to make a class immutable?

Immutable class in java means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable. We can create our own immutable class as well. Prior to going ahead do go through characteristics of immutability in order to have a good understanding while implementing the same. 

Following are the requirements: 

1. The class must be declared as final so that child classes can’t be created. 

2. Data members in the class must be declared private so that direct access is not allowed. 

3. Data members in the class must be declared as final so that we can’t change the value of it after object creation. 

4. A parameterized constructor should initialize all the fields performing a deep copy so that data members can’t be modified with an object reference. 

5. Deep Copy of objects should be performed in the getter methods to return a copy rather than returning the actual object reference)

3. What type of polymorphism are there in java?

Polymorphism in Java is the ability of an object to take many forms. To simply put, polymorphism in java allows us to perform the same action in many different ways. 

There are two types of polymorphism in java: 

1) Static Polymorphism also known as compile time polymorphism Polymorphism that is resolved during compiler time is known as static polymorphism. Method overloading is an example of compile time polymorphism. Method Overloading: This allows us to have more than one method having the same name, if the parameters of methods are different in number, sequence and data types of parameters. 

 2) Dynamic Polymorphism also known as runtime polymorphism It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a process in which a call to an overridden method is resolved at runtime, thats why it is called runtime polymorphism.

4. What are the different use of final, finally and finalize?

final with Variables : The value of variable cannot be changed once initialized. 

final with Class : The class cannot be subclassed. Whenever we declare any class as final, it means that we can’t extend that class or that class can’t be extended or we can’t make subclass of that class. 

final with Method : The method cannot be overridden by a subclass. Whenever we declare any method as final, then it means that we can’t override that method. 

 finally keyword: Just as final is a reserved keyword, so in same way finally is also a reserved keyword in java i.e, we can’t use it as an identifier. The finally keyword is used in association with a try/catch block and guarantees that a section of code will be executed, even if an exception is thrown. The finally block will be executed after the try and catch blocks, but before control transfers back to its origin 

 finalize method: It is a method that the Garbage Collector always calls just before the deletion/destroying the object which is eligible for Garbage Collection, so as to perform clean-up activity. Clean-up activity means closing the resources associated with that object like Database Connection, Network Connection or we can say resource de-allocation. Remember it is not a reserved keyword. Once the finalize method completes immediately Garbage Collector destroy that object. finalize method is present in Object class and its syntax is: protected void finalize throws Throwable{} Since Object class contains the finalize method hence finalize method is available for every java class since Object is the superclass of all java classes. Since it is available for every java class hence Garbage Collector can call finalize method on any java object Now, the finalize method which is present in the Object class, has an empty implementation, in our class clean-up activities are there, then we have to override this method to define our own clean-up activities.

5. What is the difference between Hash and Equals in java?

The difference in equals and hashCode in Java is that the equals is used to compare two objects while the hashCode is used in hashing to decide which group an object should be categorized into.


6. What is polymorphism? Explain with an example of Upcasting and Downcasting?

Typecasting is one of the most important concepts which basically deals with the conversion of one data type to another datatype implicitly or explicitly. In this article, the concept of typecasting for objects is discussed. Just like the data types, the objects can also be typecasted. However, in objects, there are only two types of objects, i.e. parent object and child object. Therefore, typecasting of objects basically means that one type of object (i.e.) child or parent to another. There are two types of typecasting. 

 They are: 

 Upcasting: Upcasting is the typecasting of a child object to a parent object. Upcasting can be done implicitly. Upcasting gives us the flexibility to access the parent class members but it is not possible to access all the child class members using this feature. Instead of all the members, we can access some specified members of the child class. For instance, we can access the overridden methods. 

 Downcasting: Similarly, downcasting means the typecasting of a parent object to a child object. Downcasting cannot be implicit.

7. What is abstract class? How it is different from interface?

As we know that abstraction refers to hiding the internal implementation of the feature and only showing the functionality to the users. i.e. what it works (showing), how it works (hiding). Both abstract class and interface are used for abstraction, henceforth Interface and Abstract Class are required prerequisites 

 Type of methods: Interface can have only abstract methods. An abstract class can have abstract and non-abstract methods. From Java 8, it can have default and static methods also. 

Final Variables: Variables declared in a Java interface are by default final. An abstract class may contain non-final variables. 

Type of variables: Abstract class can have final, non-final, static and non-static variables. The interface has only static and final variables. 

Implementation: Abstract class can provide the implementation of the interface. Interface can’t provide the implementation of an abstract class. 

Inheritance vs Abstraction: A Java interface can be implemented using the keyword “implements” and an abstract class can be extended using the keyword “extends”. 

Multiple implementations: An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces. 

Accessibility of Data Members: Members of a Java interface are public by default. A Java abstract class can have class members like private, protected, etc.

8. Can inheritance works with interface? Give an example.

An interface contains variables and methods like a class but the methods in an interface are abstract by default unlike a class. Multiple inheritance by interface occurs if a class implements multiple interfaces or also if an interface itself extends multiple interfaces.

A program that demonstrates multiple inheritance by interface in Java is given as follows:

Example

 Live Demo

interface AnimalEat {
   void eat();
}
interface AnimalTravel {
   void travel();
}
class Animal implements AnimalEat, AnimalTravel {
   public void eat() {
      System.out.println("Animal is eating");
   }
   public void travel() {
      System.out.println("Animal is travelling");
   }
}
public class Demo {
   public static void main(String args[]) {
      Animal a = new Animal();
      a.eat();
      a.travel();
   }
}

Output

Animal is eating
Animal is travelling

Now let us understand the above program.

The interface AnimalEat and AnimalTravel have one abstract method each i.e. eat() and travel(). The class Animal implements the interfaces AnimalEat and AnimalTravel. A code snippet which demonstrates this is as follows:

interface AnimalEat {
   void eat();
}
interface AnimalTravel {
   void travel();
}
class Animal implements AnimalEat, AnimalTravel {
   public void eat() {
      System.out.println("Animal is eating");
   }
   public void travel() {
      System.out.println("Animal is travelling");
   }
}

In the method main() in class Demo, an object a of class Animal is created. Then the methods eat() and travel() are called. A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String args[]) {
      Animal a = new Animal();
      a.eat();
      a.travel();
   }
}
9. Difference between Deep copy vs Shallow copy?

In this section, we will discuss the key difference between shallow copy and deep copy in Java. Let's understand the shallow and deep copy.

Shallow Copy

When we do a copy of some entity to create two or more than two entities such that changes in one entity are reflected in the other entities as well, then we can say we have done a shallow copy. In shallow copy, new memory allocation never happens for the other entities, and the only reference is copied to the other entities. The following example demonstrates the same.

FileName: ShallowCopyExample.java

  1. class ABC  
  2. {  
  3. // instance variable of the class ABC  
  4. int x = 30;  
  5. }  
  6. public class ShallowCopyExample   
  7. {     
  8. // main method  
  9. public static void main(String argvs[])   
  10. {  
  11. // creating an object of the class ABC  
  12. ABC obj1 = new ABC();  
  13.   
  14. // it will copy the reference, not value  
  15. ABC obj2 = obj1;  
  16.   
  17. // updating the value to 6   
  18. // using the reference variable obj2  
  19. obj2.x = 6;  
  20.   
  21. // printing the value of x using reference variable obj1   
  22. System.out.println("The value of x is: " + obj1.x);  
  23. }  
  24. }   

Output:

The value of x is: 6

Explanation: In the above example, we are updating the value of x using the reference variable obj2 and displaying the value of x using the reference variable obj1. In the output, we see the updated value 6 and not the original value 30. It is because obj1 and obj2 are referring to the same memory location. Therefore, whatever update we do use the reference variable obj2, the same changes will be reflected using the reference variable obj1.

Deep Copy

When we do a copy of some entity to create two or more than two entities such that changes in one entity are not reflected in the other entities, then we can say we have done a deep copy. In the deep copy, a new memory allocation happens for the other entities, and reference is not copied to the other entities. Each entity has its own independent reference. The following example demonstrates the same.

FileName: DeepCopyExample.java

  1. class ABC  
  2. {  
  3. // instance variable of the class ABC  
  4. int x = 30;  
  5. }  
  6. public class DeepCopyExample   
  7. {     
  8. // main method  
  9. public static void main(String argvs[])   
  10. {  
  11. // creating an object of the class ABC  
  12. ABC obj1 = new ABC();  
  13.   
  14. // it will copy the reference, not value  
  15. ABC obj2 = new ABC();  
  16.   
  17. // updating the value to 6   
  18. // using the reference variable obj2  
  19. obj2.x = 6;  
  20.   
  21. // printing the value of x using reference variable obj1   
  22. System.out.println("The value of x is: " + obj1.x);  
  23. }  
  24. }   

Output:

The value of x is: 30

Explanation: In the above example, we are updating the value of x using the reference variable obj2 and displaying the value of x using the reference variable obj1. In the output, we see the original value 30, not the updated value 6. It is because obj1 and obj2 are referring to different memory locations. Therefore, whatever update we do use the reference variable obj2, the same is not reflected using the reference variable obj1.

Differences Between Shallow Copy and Deep Copy

After learning about shallow and deep copy, let's see the differences between shallow and deep copy.

Shallow CopyDeep Copy
It is fast as no new memory is allocated.It is slow as new memory is allocated.
Changes in one entity is reflected in other entity.Changes in one entity are not reflected in changes in another identity.
The default version of the clone() method supports shallow copy.In order to make the clone() method support the deep copy, one has to override the clone() method.
A shallow copy is less expensive.Deep copy is highly expensive.
Cloned object and the original object are not disjoint.Cloned object and the original object are disjoint.
10. What type of inheritance is there in java?

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

Terms used in Inheritance

  • Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
  • Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
  • Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
  • Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance

  1. class Subclass-name extends Superclass-name  
  2. {  
  3.    //methods and fields  
  4. }  

The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.


Java Inheritance Example

Inheritance in Java

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.

  1. class Employee{  
  2.  float salary=40000;  
  3. }  
  4. class Programmer extends Employee{  
  5.  int bonus=10000;  
  6.  public static void main(String args[]){  
  7.    Programmer p=new Programmer();  
  8.    System.out.println("Programmer salary is:"+p.salary);  
  9.    System.out.println("Bonus of Programmer is:"+p.bonus);  
  10. }  
  11. }  

Test it Now

 Programmer salary is:40000.0
 Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.


Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.

Types of inheritance in Java

Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Multiple inheritance in Java


Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

  1. class Animal{  
  2. void eat(){System.out.println("eating...");}  
  3. }  
  4. class Dog extends Animal{  
  5. void bark(){System.out.println("barking...");}  
  6. }  
  7. class TestInheritance{  
  8. public static void main(String args[]){  
  9. Dog d=new Dog();  
  10. d.bark();  
  11. d.eat();  
  12. }}  

Output:

barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

  1. class Animal{  
  2. void eat(){System.out.println("eating...");}  
  3. }  
  4. class Dog extends Animal{  
  5. void bark(){System.out.println("barking...");}  
  6. }  
  7. class BabyDog extends Dog{  
  8. void weep(){System.out.println("weeping...");}  
  9. }  
  10. class TestInheritance2{  
  11. public static void main(String args[]){  
  12. BabyDog d=new BabyDog();  
  13. d.weep();  
  14. d.bark();  
  15. d.eat();  
  16. }}  

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

File: TestInheritance3.java

  1. class Animal{  
  2. void eat(){System.out.println("eating...");}  
  3. }  
  4. class Dog extends Animal{  
  5. void bark(){System.out.println("barking...");}  
  6. }  
  7. class Cat extends Animal{  
  8. void meow(){System.out.println("meowing...");}  
  9. }  
  10. class TestInheritance3{  
  11. public static void main(String args[]){  
  12. Cat c=new Cat();  
  13. c.meow();  
  14. c.eat();  
  15. //c.bark();//C.T.Error  
  16. }}  

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error.

  1. class A{  
  2. void msg(){System.out.println("Hello");}  
  3. }  
  4. class B{  
  5. void msg(){System.out.println("Welcome");}  
  6. }  
  7. class C extends A,B{//suppose if it were  
  8.    
  9.  public static void main(String args[]){  
  10.    C obj=new C();  
  11.    obj.msg();//Now which msg() method would be invoked?  
  12. }  
  13. }  

Test it Now

 Compile Time Error
11. What is the difference between Exception and Error in Java?

The general meaning of exception is a deliberate act of omission while the meaning of error is an action that is inaccurate or incorrect. In Java, Exception, and Error both are subclasses of the Java Throwable class that belongs to java.lang package. But there exist some significant differences between them. So, in this section, we are going to discuss the key differences between exception and error.

Exception Vs Error in Java

Before moving ahead in this section let's have a look at the hierarchy of the Java Throwable class.

Exception Vs Error in Java

Exception

The term exception is shorthand for the phrase exception event. It is an event that occurs during the execution of the program and interrupts the normal flow of program instructions. These are the errors that occur at compile time and run time. It occurs in the code written by the developers. It can be recovered by using the try-catch block and throws keyword. There are two types of exceptions i.e. checked and unchecked.

There are some important points that should be kept in mind while dealing with the exception:

  • When an error is detected, an exception is thrown.
  • Any exception that is thrown must be caught by the exception handler.
  • If the programmer has forgotten to provide an exception handler, the exception will be caught by the catch-all exception handler provided by the system.
  • Exception may be rethrown if exception handler is failure to handle it.

Advantages of Exceptions

  • It separates error handling code from regular code.
  • It has the ability to propagate error reporting up the call stack of methods.
  • The grouping or categorizing of exceptions is a natural outcome of the class hierarchy.

Let's understand the exception through a Java program.

Example of Exception

ExceptionExample.java

  1. import java.util.Scanner;  
  2. public class ExcptionExample  
  3. {  
  4. public static void main(String args[])   
  5. {  
  6. Scanner sc = new Scanner(System.in);  
  7. System.out.print("Enter a number: ");  
  8. int number = sc.nextInt();  
  9. System.out.println("You have entered: "+number);  
  10. }  
  11. }  

Let's run the above program and enter a float value deliberately to generate an exception.

Exception Vs Error in Java

It shows the InputMismatchExaception. Because the program accepts an integer value. We observe that the next statement is skipped and the program is terminated.

Error

Errors are problems that mainly occur due to the lack of system resources. It cannot be caught or handled. It indicates a serious problem. It occurs at run time. These are always unchecked. An example of errors is OutOfMemoryError, LinkageError, AssertionError, etc. are the subclasses of the Error class.

Let's understand the error through a Java program.

Example of Error

ErrorExample.java

  1. public class ErrorExample   
  2. {  
  3. public static void main(String args[])  
  4. {  
  5. //method calling  
  6. recursiveDemo(10);  
  7. }  
  8. public static void recursiveDemo(int i)  
  9. {  
  10. while(i!=0)  
  11. {  
  12. //increments the variable i by 1  
  13. i=i+1;  
  14. //recursive called method  
  15. recursiveDemo(i);  
  16. }  
  17. }  
  18. }  

Output:

Exception Vs Error in Java

We observe that on running the program, we get the StackOverflowError, not an exception.

Sr. No.KeyErrorException
1
Type 
Classified as an unchecked type 
Classified as checked and unchecked 
2
Package 
It belongs to java.lang.error 
It belongs to java.lang.Exception 
3
Recoverable/ Irrecoverable
It is irrecoverable
It is recoverable

 It can't be occur at compile time 
It can occur at run time compile time both 
5
Example
OutOfMemoryError ,IOError 
NullPointerException , SqlException 

Example of Error

public class ErrorExample {
   public static void main(String[] args){
      recursiveMethod(10)
   }
   public static void recursiveMethod(int i){
      while(i!=0){
         i=i+1;
         recursiveMethod(i);
      }
   }
}

Output

Exception in thread "main" java.lang.StackOverflowError
   at ErrorExample.ErrorExample(Main.java:42)

Example of Exception

public class ExceptionExample {
   public static void main(String[] args){
      int x = 100;
      int y = 0;
      int z = x / y;
   }
}

Output

java.lang.ArithmeticException: / by zero
   at ExceptionExample.main(ExceptionExample.java:7)

Let's discuss the key differences between exception and error.

12. Can we make one abstract class final? If so why? If not so why ?

Before reading this topic I will recommend you to read the abstract class in Java. Now we have good knowledge of the abstract class. But there are some concepts which are hidden from us. Let’s discuss one of them. Many programmers have a question, can an abstract class be final in java?
No, An abstract class can’t be final because the final and abstract are opposite terms in JAVA.
Reason: An abstract class must be inherited by any derived class because a derived class is responsible to provide the implementation of abstract methods of an abstract class. But on another hand, if a class is a final class, then it can’t be extended(inherited). So both concepts are opposite to each other.

Can abstract class be final in java
abstract final class Department
{
String collegeName = "KUK";
public void collegeName()
{
System.out.println("Name of college = "+ collegeName);
}
//abstract methods
public abstract void deptName();
public abstract void noOfTeachers();
}
class MainClass extends Department
{
public static void main(String arg[])
{
MainClass obj = new MainClass();
}
@Override
public void deptName() {
// TODO Auto-generated method stub
}
@Override
public void noOfTeachers() {
// TODO Auto-generated method stub
}
}

Output: This will show exception at compilation time.

As you can see in the above example, We are trying to use two opposite keywords (abstract and final) for a single class. In this case, the compiler showing an error compile-time, because Java doesn’t permit it.

Because if compiler works according to the final keyword then the Department class must not be extended by any other class. But the abstract keyword is the vice-versa. It means according to abstract keyword the Department must be extended by some other class. To remove this ambiguity of compiler, Java doesn’t permit it.


(Java 8 answers will be uploaded soon)

No comments