Java Interview Questions

1.) Why the main method is static in java?

JVM is not able to create objects, hence how JVM will call the main method. Declaring method as static means, it can be called by the class name itself without creating the object. This is the reason we create the main method as static.
If we do not declare the main method as static, JVM will give runtime exception Saying NoMainMethodFound.

2.) What happens if you remove static modifier from the main method?

The program will compile successfully but JVM will through Runtime exception – “NoSuchMethodError”.

3.) What is the scope of variables in Java in the following cases?

The public access modifier

the public modifier can be used for class, method, member variables, and constructors. This modifier is the least restrictive modifier. Public members are visible to any class in the java program, whether these classes are in the same package or another package.

The private access modifier

the private modifier can be used for class, method, member variables, and constructors. This modifier is the most restrictive modifier. Private attributes, methods cannot be accessed outside the class. Attributes, methods, constructor which are declared as private are strictly controlled. Which means they can not be accessed by anywhere outside the enclosing class.

A standard design strategy is to defining all fields of class as private and providing getters and setters methods for the fields to access them.

The protected Access modifier

the protected modifier can be used for class, method, member variables, and constructors. This modifier has less restriction than the private modifier. Attributes, methods, and constructor declared as protected in a superclass can only be accessed by the subclass of other packages. Protected field, method or constructor can be accessed within the same package, no matter they are subclass or not of the protected member’s class.

The default access modifier

When no access modifier is specified then it is assumed to default. In this case class field, method or constructor is accessible only by classes in the same package. In the case of Interface, the default modifier is not used for fields and methods.

4.) What is “this” keyword in java?

this is a keyword in java used to denote the current object whose method or is being invoked. this keyword can be used inside the method or constructor of the class. It can be used to refer to any member of the class from within the method or constructor.

this keyword with a field

5) What are the differences between C++ and Java?

  • C++ is platform-dependent but Java is platform-independent. This is one of the major feature of Java that A Java class can be compiled in a machine but can be run in any machine.
  • Java doesn't support multiple inheritances through class but C++ supports multiple inheritances. With the help of Interfaces, we can achieve Multiple inheritances in Java. Virtual is a keyword in C++ which is used to resolve ambiguity among classes during multiple inheritances. This is the main difference between Java and C++.
  • With the help of the try-catch block, we can handle the exception at runtime. In Java, there are no destructors, so exception handling is different in Java. In C++ we do not include try catch even if the function throws an exception.
  • Java doesn't support structures and unions but C++ supports structures and unions.
  • C++ supports operator overloading and method overloading both but Java doesn't support operator overloading. Java support method overloading only.
  • Like C++ Java does not have any concept of pointers because like C, C++ we have to manage the memory management by destructors. In Java, Automatic Garbage Collector works the same. This feature makes Java more secure because pointers point to the exact memory location that means we can lose the security as it is using them directly.
  • Java has built-in support for the thread as Thread is a class in Java and can be used to create and manage the life cycle of a thread. In C++ there is no built-in library, we have to be dependent on third-party libraries for thread support.
  • C++ supports goto statement but Java does not have goto statement. Although goto and const are the keywords in Java but using these keywords is not advised. There may be chances that it causes an unconditional loop.
  • this keyword is used to handling variable in a way that we can have a global variable of a name and we can have a local variable with the same name. a global variable can be accessed by this keyword. With this feature, the local variable will hide the instance variable. This is called variable hiding. Please have a look below program.

5.) Which class is the superclass for every class?

Object class.

6.) Can we overload the main() method?

The main method is just like any other method in Java. It can be overridden, it can be overloaded.
Overloading of the main method can be done in the same way, overload other methods.
JVM will call the main method which is in the syntax-

public static void main(args [] )

other than this method syntax, JVM will not call.

7.) What is object cloning?

The object cloning is a way to create an exact copy of the content of an object.

Java use clone() method to Object class to clone an object, which is also known as Shallow copy.

Reference Copy Shallow Copy

Accoount a1 = new Account(10);

Account a2 = a1;

Account a1 = new Account(10);

Account a2 = a1.clone();

A2.balance = 20;

Java.lang.cloneable interface must be implemented by the class whose object clone you want to create otherwise clone() method will raise cloneNotSupportedException.

Interface Cloneable is a marker interface and does not contain any method.

9.) Can we override private methods in Java?

No, private methods are not visible outside the class, hence no overriding can be possible.

10.) What is the Java IDE’s?

Eclipse and NetBeans are the IDE’s of JAVA.

11.) What do you mean by Constructor?

A constructor is just like a method but has many features and differences to the method, that the name of the method must be the same as the name of the class and it doesn't return any value. The constructor is used to initialize a newly created object and is called just after the memory is allocated for the object. It can be used to initialize the objects to desired values or default values at the time of object creation. It is not mandatory for the developer to write a constructor for a class. If we do not define any constructor in a class, compiler initializes the member variable to its default values.

1.) It has the name as the class name.
2.) It does not return any value, not even void.

public class Employee{
	Employee(){ // Constructor Declaration
		.... //Constructor body
	}
}

12.) What do you understand by Local variable and Instance variable?

Local variables are defined in the method and scope of the variables is only within the method. Outside the scope is no accessibility.

An instance variable is defined inside the class and outside the method and scope of the variables is throughout the class. It is part of the class rather than the object.

9.) What is a class?

Class is a basic building block of java, all Java codes are defined in a class. A Class has variables and methods and blocks. What an object will do, is defined inside the class.

public class InitializationBlocks
{
	static int balance;
	int initialLoad;
	static{
		balance=100000;
	}
	{
		initialLoad = 2000;
	}
}


14.) What is Object?

The object is a real-world entity and describes what a class can do and what are the features and functionalities are carried by the class.

InitializationBlocks blocks = new InitializationBlocks();

15.) What is Inheritance?

It is always recommended if we can reuse something that already exists rather than creating the same again. With the help of Inheritance, we can achieve this concept in Java. Java classes can be reused in many ways.

Inheritance is a mechanism wherein a new class is derived from an existing class. A class may inherit or reuse the properties and methods of other class.

A class derived from another class is called a subclass or child class where is the class from which a subclass is derived is called a superclass or parent class.

Java says a child has only one parent class where is a parent may have one or more child classes.
Inheritance is a compile-time mechanism and shows a static relationship between classes.
A superclass can have any number of subclasses.

16.) What is Encapsulation?

To gather all related methods and attributes in a single class is called Encapsulation. In other words, binding related data members and methods in a class is called Encapsulation. Encapsulation class is also called expert class because it binds only related attributes and methods.

Making an expert class is called encapsulation or you can say after encapsulation we will get an expert class.
The person can contain information relevant to people like name, address, and date of birth but cannot contain irrelevant information like balance or speed.

Account class is the expert of account services and contains relevant attributes and methods like fund transfer(), deposit(), withdrawal() and getBalance(). It cannot contain a piece of irrelevant information like date of birth and gear.

17.) What is Polymorphism?

Representing a single entity in many forms is called Polymorphism.

A single object can refer to the superclass or subclass depending on the reference type which is called polymorphism.

18.) What is method Overriding?

In a child-parent relationship of classes when a child class is not satisfied with the method implementation present in the parent class or when child class wants to give their own definition to the method, can rewrite the same method in child class. So declaring a method with the same signature, present in parent class into child class is called as method Overriding.

With the help of method Overriding we can achieve Polymorphism.

19.) What is Method Overloading?

Compile time polymorphism is achieved through method overloading in Java. In simple terms method overloading means there are several methods present inside the class having the same name but different types/order/number of parameters. Sometimes it is referred to as static binding. Because of Method overloading feature, we can have more than one constructor in a class.

Here is an example of overloading a method by a different order of arguments –

public class JavaExample {

	public JavaExample() {
		// constructor
	}

	public void add(int a, double b) {
		double result = a + b;
		System.out.println("add(int,double) method called!");
		System.out.println("after addition - " + result);
	}

	public void add(double a, int b) {
		double result = a + b;
		System.out.println("add(double, int) method called!");
		System.out.println("after addition - " + result);
	}

	public void add(String a, char b) {
		String result = a + b;
		System.out.println("add(String, char) method called!");
		System.out.println("after addition - " + result);
	}

	public void add(char a, String b) {
		String result = a + b;
		System.out.println("add(char, String) method called!");
		System.out.println("after addition - " + result);
	}

	public static void main(String[] args) {

		JavaExample ex = new JavaExample();
		ex.add(4, 5.5);
		ex.add(5.5, 4);
		ex.add("India ", 'Y');
		ex.add('Y', " India");
	}

}
Example Output

20.) What is Interface?

Multiple inheritances cannot be achieved in java because of Diamond problem. To overcome this problem Interface concept is introduced. We can extend a class and implements multiple interfaces at the same time in a class.
An Interface contains all abstract methods and defined by interface keyword. The interface is used to achieve complex abstraction in java.

public interface SocialWorker 
{
public void helpToOthers();
}
public interface RichMan 
{
public void earnMoney();
public void donation();
public void party();
}

21.) What is the Abstract class?

Abstract Classes are used when a parent class needs to provide default behavior along with abstract methods. It enforces child classes to implement specialized behavior of abstract methods. It can never be Instantiated.
An abstract class is declared by abstract keywords.

public abstract class Shape{
	// add some text here
}

An abstract class has the following properties:

1. It may or may not contain abstract methods.

2. It can be initiated.

3. Child classes are enforced to implemented abstract methods.

4. If child class does not implement abstract methods then the child will also be declared as abstract.

If a class is not an abstract class then it is called a concrete class. Concrete class does not have abstract methods.

22.) What is the difference between String, String Builder, and String Buffer?

String variables are immutable, that means once a value is assigned to them, it cannot be changed, if they try to, JVM will create a new object and it will be returned.

So when we need immutability, we go for Strings.

StringBuffer class is mutable and thread Safe. It uses Stack to store the value. If one tries to change the value of the StringBuffer object, It will replace the old value in the same instance.

All the methods are synchronized and can be used in a multithreaded environment.

StringBuilder class is immutable and not thread safe. So when Thread safety is not a concern and immutability is also not required, String Builder is the best option.

23.) Explain about public access modifiers?

The public access modifier

the public modifier can be used for class, method, member variables, and constructors. This modifier is the least restrictive modifier. Public members are visible to any class in the java program, whether these classes are in the same package or another package.

Look at the below Example:

package academic;

public class School {

	public String schoolName;
	public String schoolAddress;
	public int schoolStaffCount;

	public School() {
		super();
	}


	/**
	 * @return the schoolName
	 */
	public String getSchoolName() {
		return schoolName;
	}

	/**
	 * @param schoolName the schoolName to set
	 */
	public void setSchoolName(String schoolName) {
		this.schoolName = schoolName;
	}

	/**
	 * @return the schoolAddress
	 */
	public String getSchoolAddress() {
		return schoolAddress;
	}

	/**
	 * @param schoolAddress the schoolAddress to set
	 */
	public void setSchoolAddress(String schoolAddress) {
		this.schoolAddress = schoolAddress;
	}

	/**
	 * @return the schoolStaffCount
	 */
	public int getSchoolStaffCount() {
		return schoolStaffCount;
	}

	/**
	 * @param schoolStaffCount the schoolStaffCount to set
	 */
	public void setSchoolStaffCount(int schoolStaffCount) {
		this.schoolStaffCount = schoolStaffCount;
	}

}

Here we have created a School class where all the methods and variables and constructor are public. So it can be accessed from anywhere in a different package.

24.) Explain about private access modifiers?

the private modifier can be used for class, method, member variables, and constructors. This modifier is the most restrictive modifier. Private attributes, methods cannot be accessed outside the class. Attributes, methods, constructor which are declared as private are strictly controlled. Which means they can not be accessed by anywhere outside the enclosing class.

A standard design strategy is to defining all fields of class as private and providing getters and setters methods for the fields to access them.

25.) Explain about protected access modifiers?

the protected modifier can be used for class, method, member variables, and constructors. This modifier has less restriction than the private modifier. Attributes, methods, and constructor declared as protected in a superclass can only be accessed by the subclass of other packages. Protected field, method or constructor can be accessed within the same package, no matter they are subclass or not of the protected member’s class.

26.) Explain about default access modifiers?

When no access modifier is specified then it is assumed to default. In this case class field, method or constructor is accessible only by classes in the same package. In the case of Interface, the default modifier is not used for fields and methods.

27.) Who is known as the inventor of JAVA?

The first publically available version of Java (Java 1.0) was released in 1995 by James Gosling and Team. Later, Sun Microsystems was acquired by the Oracle Corporation in 2010. With the development of technology, new versions of Java have been released over a period of time.

28.) What is JVM?

When the compiler compiles the Java file into a .class file, that .class file works as input into the JVM, which Loads and executes the class file. The virtual machine is a software implementation of the physical machine. when we try to execute our .class file, JVM comes in picture. It takes the .class file and loads all the dependent libraries to provide a smooth execution environment.

29.) What do you mean by platform independence of Java?

Platform independence means that w can run the same Java Program in any Operating System.

For example, we can write a java program in Windows and run it in Mac OS.

30.) Why Java is not a pure Object Oriented language?

Java is not called as a pure Object Oriented Language because it supports primitive data types such as int, byte, short long. Java also has the wrapper classes to created such objects but still, Java is supporting to them which makes the language so easy in development.

31.) What is the importance of the main method in Java?

The main method is the entry point in all standalone Java Application.

The syntax of the main method –

public static void main (String args[])

JVM calls the main method whenever we run the standalone application and it should be called in a static way. We define the main method as public and static because the method should be called by the class name and also by outside anywhere.

32.) Can we overload the main method?

Yes, we can have multiple overloaded main methods in a class but JVM will call the main method which has the proper syntax of the main method.

public static void main (String args[])

33.) Can we have multiple public classes in a java source file?

A Java file cannot have more than one public class. We can have any number of classes in a Java Source file but can have only one public class.

34.) What is Java Package and which package is imported by default?

Grouping the classes in different – different types and managing each class in at least a group is called packaging. We create a package and then create the class inside the package.

So, whenever we need to use that class we just use import statement and import that class in our class.

35.) What is finally and finalize in java?

finally is a block, always associated with try catch block and execute always to perform clean-up activities.
finalize() is a method which is present in Object class and always been called by the garbage collector before releasing the unused object.

36.) Can we declare a class as static?

A top level class can not be declared as static but, an inner class can be declared as static.

If an inner class is declared as static, it is called static nested class.

The static inner class is just the same as any other top-level classes.

37.) What is the static import?

If we want to use a static method declared in another class and another package, we usually import the whole class in our class and then use the method by the class name.

We can do this same by importing only the static method in the class by using static import and we can call this method in the same way as that method is part of the calling class.

38. What is try with resources in Java?

A resource (Connection, JDBC connection or socket or File streams) which is opened in try catch block must be closed once a program is done using it. Before Java 7 we were using try block to open the connections and use finally block to close the connections which are opened.

Sometimes we may forget to close the connection and it increases the chances of memory leak.

Java 7 has the feature to close the connections automatically by using try with resources.

Benefits of try with resources in JAVA –

  • More readable code and easy to write.
  • Automatic resource management.
  • The number of lines of code is reduced.
  • No need of finally block just to close the resources.
  • We can open multiple resources in a try-with-resources statement separated by a semicolon.

39.) What is the multi-catch block in Java?

A try block can have multiple catch blocks where we can catch multiple exceptions and can write an independent code to handle each exception.

While writing multiple catch blocks We should take care about the hierarchy of classes as if parent class exception is called before child class then we will get compile time error.

40.) What is the static block?

We can declare a block as static, which is executed at the time of class loading in the memory by classLoader. It is normally use to initialize the variables of class.

41.) Can an interface implement or extend another interface?

Yes. An interface can extend any number of interfaces.

42.) What is Marker interface?

A marker interface is an empty interface without including body, i.e. no method and no variables declaration.

JVM gives support to marker interfaces. Such common used marker interfaces are –
Serializable and Cloneable.

43.) What are the Wrapper classes?

The primitive data types byte, short, int, long, float, double, char and boolean are not objects, they do not belong to any class.

Many data structures like Collection in JDK 1.4 on word accept only objects. In this case, there is a need to convert primitive data types into objects.

Wrapper classes allow primitive data types to convert into objects. As the name says, a wrapper class wraps around a primitive data type and gives it an object representational form.

They are one for primitive type Boolean, Byte, Character, Double, Float, Integer, Long and Short. Wrapper classes make the primitive type data to act as objects. Wrapper classes belong to Java.lang package.

Wrapper classes are immutable, means once they have been given a value that value cannot be changed.

int I = 5;
Integer obj = new Integer (i); // wrapping
int j = obj.intValue(); // unwrapping

double d = 5.5;
Double obj  = new Double (d); // wrapping
Double dd = obj.doubleValue();// unwrapping
int I = 5;
Integer obj = new Integer (i); // wrapping
int j = obj.intValue(); // unwrapping

double d = 5.5;
Double obj  = new Double (d); // wrapping
Double dd = obj.doubleValue();// unwrapping

44.) What is the use of upper keyword?

Super is a keyword and can be used to called parent implementations.

We can call parent constructor before calling child constructor with the help of the super keyword. The statement of calling parent constructor using super keyword must be the first statement in Child constructor.

Child(){
	super();
}

We can call the parent variable by super keyword

class Child{
		int k = 50;
		System.out.println(“Child k = ”+k)
		System.out.println(“Parent k = ”+super.k)
}

45.) Can we have tried without catch block?

Yes, we can have tried with finally block. The catch block is not necessary all the time.

46.) What is Garbage Collection?

Garbage collection is the process of identifying the objects which are unreachable and unusable and killing them to free up the memory.

We can also call the garbage collector to perform clean up activity in our application.
Runtime.getRuntime().gc() System.gc();

47.) What is instanceOf keyword?

the instanceOf operator only used for object reference variables. This operator is used to check if the present object is a type of that class/interface or not.

public class Demo{

	public static void main(String[] args) {
		
		String name = "S";
		if (name instanceof String) {
			System.out.println("This is String Object");
		}
	}
}
Example Output

48.) Java is Pass by Value or Pass by Reference?

Java is Pass by value, we can not access reference location in Java.

49.) Java Compiler is stored in JDK, JRE or JVM?

Java compiler converts Java source code into byte code. Javac is used to compile our Java program. JRE is a runtime entity and provides runtime entity only so, the compilation is no needed here. Only java command is useful in JRE.

Hence Compiler is part of JDK not JRE or JVM.

50.) What will be the output of the following the program?

public class Test {

	public static String toString() {
		System.out.println("Test toString called");
		return "";
	}

	public static void main(String args[]) {
		System.out.println(toString());
	}
}

Answer: The code will not be compiled as toString method is present in Object class which is parent class of all the classes. At the time of overriding, we cannot change the method signature as static. Because static is part of class hence This static method cannot hide the instance method from Object.

Share