Interview Questions

Java Interview Questions & Answers

1) What is Java?

Java is an object-oriented and platform independent language. It has the following features-

  • Simple
  • Secure
  • Architectural-neutral
  • Portable
  • Robust
  • Multi-threaded
  • Interpreted
  • High-Performance
  • Distributed
  • Dynamic

2) What is javac command?

To compile a Java source file you need to use the Java compiler which is called javac.
Syntax- javac [options] FileName.java

3) What is JIT compiler in Java?

JIT stands for Just In Time compiler. It is considered as a part of JVM. Its primary objective is to enhance the performance of JVM by compiling some code block into native machine language instructions.

4) Which elements live on the stack and heap?

Following are the elements that live on the stack-

  • Local variables
  • Local reference variables.
  • Method invocations.

Following are the elements that live on the heap-

  • Instance variables
  • Instance reference variables.
  • Objects.

5) Why Java is given 'write once run anywhere' slogan?

The reason of this slogan is that- Java compiler compiles the source code into bytecode, which is not executable code. Bytecode is somewhere in the middle of source code and executable code. This bytecode is platform independent and can be executed on any system.

6) Who developed Java programming language?

James Gosling developed Java programming language in 1992-1994. And he is know as "The Father of Java".

7) What is Java Bytecode?

Bytecode contains instructions in the form of machine language program for a Java processor.

8) How many operators are there in Java?

Java supports the following operators-

Operators Symbols
Arithmetic Operators +, -, *, /, %, ++, --
Relational Operator >, >=, <, <=, ==, !=
Logical Operators &, |, ^, ~, !, &&, ||
Assignment Operators =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>=

9) What is the difference between while and do-while loop in Java?

In while loop, the condition is checked at the beginning of the loop and if the condition evaluates to true then code inside the while loop is executed.
In do while loop, the condition is checked at the end of the loop. Even if the condition evaluates to fails, the code inside the loop is executed at least once.

10) What is top-level class in Java?

Class that is declared outside of any class is called top-level class.

11) What are access modifiers in Java?

Access modifiers control the access of the class members (instance variables, methods, and nested classes). Java supports four access modifiers which are described below-

Access Modifiers Explanation
public A class or class members that are declared public can be accessed by any code from any class. This modifier makes the member most accessible.
protected A member declared protected is accessed by all classes in the same package. You cannot declare a class protected. This modifier provides less accessibility than the public modifier.
default If you do not specify any access modifier while declaring a class or a class member, the default access is assumed. A class or a class member with default access can be accessed by any class in the same package. This modifier provides less accessibility than the protected modifier.
private This access modifier cannot be applied to a top-level class. It can be applied to the members of a top-level class which are instance variables, methods, and inner classes. This modifier makes a member least accessible.
For More Details...

12) Can we declare class inside a class?

Yes, it is valid to declare a class inside another class. This is referred to as nested classes. In this, a class is declared as a member of another class. There are four types of nested classes-

  1. Static member class
  2. Nonstatic member class
  3. Anonymous class
  4. Local class
For More Details...

13) Why main method is declared static?

To call static methods, an object of a class is not required. If we declare main() function non-static then JVM must first create object and then call main() method. This will create the problem of extra memory allocation.

14) What is constructor in Java?

The constructor is a special method that has the same name as that of class and has no return type. It is called whenever any object of a class is created.

Syntax
access-modifier className(parameters){
	//Code to be executed.
}
For More Details...

15) How many types of constructor are there in Java?

There are three types of constructor in Java-

  1. Default Constructor- This constructor takes no argument and is called when an object is created without any explicit initialization.
    Example- LinkedList ll = new LinkedList();
    The compiler provides default constructor when you do not write any constructor for a class. If you provide at least one constructor for the class, then the compiler does not provide any constructor.
  2. Parameterized Constructor- This constructor is called when an object is created and it is initialized with some values at the time of creation.
    Example- LinkedList l2 = new LinkedList(12);
  3. Copy Constructor- This constructor is called when an object is created and it is initialized with some other object of the same class at the time of creation.
    Example- LinkedList l3 = new LinkedList(l2);
For More Details...

16) What are the rules for calling a constructor?

There are two rules for calling a constructor-

  1. Outside the class- The constructor can only be called with the help of new operator that is when you create an object of the class. For example, new LinkedList() will call the default constructor of LinkedList class
  2. Inside the class- The constructor can only be invoked from within another constructor using this or super keyword and not from anywhere else.
For More Details...

17) How do you call a constructor from another constructor of the same class?

Using this() as a method name, you can call a constructor from another constructor. It must appear at the beginning of the constructor otherwise compile-time error will occur.

Example
class Point2D{
	private int x;
	private int y;
	public Point2D(){
		this(0,0);
	}
	public Point2D(int a){
		this(a,0);
	}
	public Point2D(int a, int b){
		x=a;
		y=b;
	}
	public Point2D(Point p){
		this(p.x, p.y);
	}
	public void show(){
		System.out.println();
	}
}
For More Details...

18) A constructor cannot be inherited. True or False?

True

19) Is it valid to declare constructor as final?

No, constructor cannot be declared as final.

20) What is the use of this keyword in Java?

this keyword basically refer to the current object. Following are the usage of this keyword-

  • It is used to access instance variables.
  • You can pass the current object to a function.
  • Return the current object from a function.
For More Details...

21) What is Method Overloading in Java?

When you have more than one functions with the same name but with the different number of arguments, type of arguments, or the order of arguments, then such concept is called method overloading. In method overloading, the return type of overloaded functions may be same or different.

void add(int a, int b)
void add(float a, float b) //valid as the type of arguments have changed.
void add(float a, int b) //valid as the type of arguments have changed.
void add(int a, float b) //valid as the order of arguments have changed.
float add(float a, int b, float c) //valid the number of arguments have changed.

All the above methods are valid overloaded functions

For More Details...

22) What is constructor overloading?

A class having multiple constructors is called constructor overloading.

For More Details...

23) What is Method Overriding in Java?

  • Using method overriding, a subclass can change the behavior of inherited methods to meet its specific needs. It allows a programmer to implement methods in a derived class that has the same signature as in the base class. Same signature means the same name, the same number of parameters, and their types appearing in the same order.
  • You are not allowed to override a method that has the final modifier.
  • The return type of overriding and overridden method must be same.
public class Animal{
	public void sound(){
		System.out.println("Animal makes sound");
	}
}
class Dog extends Animal{
	public void sound(){
		System.out.println("Dog barks");
	}
	public static void main(String args[]){
		Dog d = new Dog();
		d.sound();
	}
}
Output
Dog barks
For More Details...

24) What is the difference between Method Overriding and Overloading?

Method Overriding Method Overloading
In method overriding, the signature of overriding method must be same as that of overridden method. In other words, the number of arguments, their types, and the order must be same in both overriding and overridden methods. In method overloading, we have more than one functions with the same name but with different sets of argument types or the same set of argument types in different order.
The return type of both overriding and overridden method must be same. The return type of overloaded functions may be same or different.
It is an example of run-time polymorphism. It is an example of compile-time polymorphism.
You cannot make overriding method less public than the overridden method. Overloaded functions can have different access modifiers.
For More Details...

25) What is the use of super keyword in Java?

There are two usage of super keywords-

  • It is used to call the base class constructor.
  • Using super keyword, you can access an overridden function in the base class.
For More Details...

26) What is polymorphism?

Polymorphism is a Greek word which means "several forms". It is the most important feature of any object-oriented programming language.

For More Details...

27) What is run-time polymorphism?

  • It is also known as dynamic binding or late binding.
  • Here, different forms of a single entity are determined at the runtime.
  • Method Overriding is an example of run time polymorphism.
For More Details...

28) What is compile-time polymorphism?

  • It is also known as static binding or early binding.
  • Here, method behavior is resolved at the compile time.
  • Method Overloading is an example of compile time polymorphism.
For More Details...

29) What is static variable in Java?

  • A variable that is declared static is called static variable.
  • It is initialized when the class is loaded.
  • It can be accessed by an instance of the class or by using the class name.
For More Details...

30) What static method in Java?

  • Like a static variable, a static method belongs to the class and not to the specific instance of the class.
  • It cannot access nonstatic members of the class. In other words, it is allowed to access the static members of the class.
  • It can be invoked before any object is created. That is why main() method is declared static.
For More Details...

31) What is the difference between static method and instance method?

static method instance method
A method that is declared static is called static method. A method that is not declared without static keyword is called instance method.
static method can be called by class name or an instance of the class. Instance method can be only be called by object of the class.
It cannot be access non-static members of the class. Both static and non-static members can be access by instance methods.

32) What is static code block?

  • A static code block is used to execute the task before the class is initialized.
  • It does belong to any method, but only to the class.
Syntax
static{
	//code to be executed
}
For More Details...

33) What is variable-length argument method?

J2SE 5.0 introduced a new feature that allows us to define methods with a variable number of arguments so that we can call the same method with a variable number of parameters. This is called variable-length argument method. Following are the rules to define this method-

  • There must be only one variable-length parameter list.
  • If there are more than one parameters in a method, then the variable-length parameter must appear at last.
  • A variable-length parameter consists of a type followed by three dots and the name.
Syntax
access-modifier return-type methodName([parameters], type... name){
	//code to be executed.
}
Example
public int add(int... values){
	int sum=0;
	for(int v : values){
		sum+=v;
	}
	return v;
}
add(1,2);
add(1,2,3);
add(1,2,3,4);

34) What is inheritance?

Inheritance is a fundamental feature of object-oriented programming. It enables the programmer to write a class based on an already existing class. The already existing class is called the parent class, or superclass, and the new class is called the subclass, or derived class. The main advantages of inheritance are-

  • Code reusability
  • Code maintenance
  • Implementing Object Oriented Programming(OOP)
For More Details...

35) Does Java support multiple inheritances?

Java only supports single inheritance. While programming you may run into a situation where mulitple inheritance is required. In that case, use interface to overcome this problem.

36) How to declare constant in Java?

A constant is declared using final modifier. Example- final float pi = 3.14;

37) Can we prevent a method from overriding?

If a method is declared final, then you cannot override that method.

38) What do you mean by final class?

Final class means the class cannot be extended.

For More Details...

39) Which is the superclass of all the classes?

Object is the super class for all the classes.

40) Can we apply access modifiers to local variables and method parameters?

No, local variables and method cannot be defined by access modifier. An attempt to do so will prevent compilation error.

41) Are you allowed to write super() and this() both in a constructor?

You are not allowed to write super() and this(). Doing so will give compile time error.

42) What is an abstract class?

  • An abstract class is used to group common state (variables) and behaviour (methods) of its derived classes.
  • You are not allowed to create an instance of an abstract class.
  • By defining abstract methods, it forces its derived classes to define their implementation.
For More Details...

43) Is it necessary for an abstract class to have abstract methods?

A class can be defined as abstract class even if it does not have any abstract methods.

44) Can you create an object of an abstract class?

You cannot create an object of an abstract class. You can only use its variable to refer to objects of its derived class.

45) What happens when derived class does not implement all abstract methods?

If a derived does not implement abstract methods, then you must define it as an abstract derived class.

46) What is an interface?

  • An interface is a mechanism by which you can implement multiple inheritances.
  • A subclass can inherit one or more interface in addition to the super class.
  • An interface can define only abstract methods and constants.
For More Details...

47) Can you make interface methods more restrictive?

A derived class cannot apply access modifier other than public on the methods inherited from the interface.

48) Can an interface extend one or more interfaces?

With the help of extends keyword, an interface can extend one or more interfaces.

49) Explain the difference between interface and abstract class?

abstract Class Interface
An abstract class may or may not have abstract method. All the methods inside an interface are by default abstract.
An abstract class can contain constructor. You cannot define constructor in an interface.
In an abstract class, the data variable may or may not be defined constant. An interface can only have constants.
It supports single level inheritance. It supports multiple inheritance.

50) Are you allowed to declare more than one top-level classes as public?

At most one top-level class may be declared public.

51) How do you handle command line arguments in Java?

  • The array argument in the main() method indicates that you can pass command line arguments to it. You provide command line arguments when you run the class that contains the main() method.
  • The length of arguments array is not fixed. It becomes equal to the number of arguments that you pass.
  • The datatype of the parameter in the main() method must be a String array, and its name could be any valid variable name.

52) What are packages in Java?

  • Packages are the way to group related classes and interfaces. You store all the class file related to a package in a directory whose name matches the name of the package.
  • Using package statement, you define classes and interfaces in a package. Package statement must be the first statement in your class or interface.
For More Details...

53) Which package is imported automatically by the JVM?

java.lang package is imported automatically by the JVM.

54) What do you mean by static import?

Static import is the feature that allows us to import static variables of a class so that we can refer to them without using the class name. The syntax of this feature is- import.static.

For More Details...

55) What is an Exception?

An exception is an error that happens when an application is running. When an unexpected condition arises, the exception is thrown, and it changes the normal execution flow of the program. Java offers a very good system for exception handling.

56) What do you mean by exception handling?

In a program, if you perform an operation that causes an exception that is an exception is thrown, you can alway catch the exception and deal with it. This is called Exception Handling.

For More Details...

57) How many keywords are there in exception handling mechanism?

The Java exception-handling mechanism contains five keywords: try, catch, throw, throws, and finally.

58) Which is the base class of all the exceptions in Java?

Throwable class.

59) Is it necessary to write finally block?

No, if you want to execute some code regardless of whether or not there is matching catch block, you can put those code inside the finally block.

For More Details...

60) How many types of exception are there?

There are two categories of exception-

  1. Checked Exception-
    • These exceptions are the subclasses of the Exception class or one of its subclasses, excluding the RuntimeException.
    • Checked exceptions are checked by the compiler.
    • If there is no matching catch block for the checked exception and the method does not throw the exception using throws clause, the code will not compile.
    • Eg- ClassNotFoundException, URISyntaxException, etc.
  2. Unchecked Exception-
    • It is also known as Runtime Exception.
    • These exceptions are the subclasses of the RuntimeException class or one of its subclasses.
    • Checked exceptions are not checked by the compiler.
    • Eg- ClassCastException, ArrayIndexOutOfBoundsException, etc.
For More Details...