Question-1
What is a final keyword?
The final keyword is used with Class to make sure no other class can extend it. For example, the String class is final and we can’t extend it.
We can use the final keyword with methods to make sure child classes can’t override it.
Java’s final keyword can be used with variables to make sure that it can be assigned only once. However the state of the variable can be changed, for example, we can assign a final variable to an object only once but the object variables can change later on.
Java interface variables are by default final and static.
Question-2
What is a static keyword?
Static keyword can be used with class-level variables to make it global i.e all the objects will share the same variable.
static keyword can be used with methods also. A static method can access only static variables of class and invoke only static methods of the class.
Question-3
What is finally and finalize in java?
The finally block is used with try-catch to put the code that you want to get executed always, even if an exception is thrown by the try-catch block. finally block is mostly used to release resources created in the try block.
finalize() is a special method in Object class that we can override in our classes. This method gets called by the garbage collector when the object is getting garbage collected. This method is usually overridden to release system resources when the object is garbage collected.
Question-4
Can we declare a class as static?
We can’t declare a top-level class as static however an inner class can be declared as static. If the inner class is declared as static, it’s called a static nested class.
The static nested class is the same as any other top-level class and is nested for only packaging convenience.
Question-5
What is static import?
If we have to use any static variable or method from another class, usually we import the class and then use the method/variable with the class name.
import java.lang.Math;
//inside class
double test = Math.PI * 5;
We can do the same thing by importing the static method or variable only and then use it in the class as if it belongs to it.
import static java.lang.Math.PI;
//no need to refer class now
double test = PI * 5;
The use of static import can cause confusion, so it’s better to avoid it. Overuse of static import can make your program unreadable and unmaintainable.
Question-6
What is try-with-resources in java?
Ans - One of the Java 7 features is the try-with-resources statement for automatic resource management. Before Java 7, there was no auto resource management and we should explicitly close the resource. Usually, it was done in the finally block of a try-catch statement. This approach used to cause memory leaks when we forgot to close the resource.
From Java 7, we can create resources inside try block and use it. Java takes care of closing it as soon as the try-catch block gets finished.
Question-7
What is a multi-catch block in java?
Ans - Java 7 one of the improvements was a multi-catch block where we can catch multiple exceptions in a single catch block. This makes our code shorter and cleaner when every catch block has a similar code.
If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, the exception parameter (ex) is final, so you can’t change it.
Question-8
What is a static block?
Ans - Java static block is the group of statements that gets executed when the class is loaded into memory by Java ClassLoader. It is used to initialize static variables of the class. Mostly it’s used to create static resources when class is loaded.
Question-9
What is an interface?
Ans - Interfaces are core concepts of java programming language and used a lot not only in JDK but also in java design patterns, most of the frameworks and tools. Interfaces provide a way to achieve abstraction in java and used to define the contract for the subclasses to implement.
Interfaces are good for starting point to define Type and create top-level hierarchy in our code. Since a java class can implement multiple interfaces, it’s better to use interfaces as super class in most cases.
Question-10
What is an abstract class?
Abstract classes are used in java to create a class with some default method implementation for subclasses. An abstract class can have an abstract method without the body and it can have methods with implementation also.
abstract keyword is used to create an abstract class. Abstract classes can’t be instantiated and mostly used to provide a base for sub-classes to extend and implement the abstract methods and override or use the implemented methods in abstract class.
Question-11
What is the difference between abstract class and interface?
Abstract keyword is used to create abstract class whereas interface is the keyword for interfaces.
Abstract classes can have method implementations whereas interfaces can’t.
A class can extend only one abstract class but it can implement multiple interfaces.
We can run an abstract class if it has a main() method whereas we can’t run an interface.
Question-12
Can an interface implement or extend another interface?
Interfaces don’t implement another interface, they extend it. Since interfaces can’t have method implementations, there is no issue of the diamond problem. That’s why we have multiple inheritances in interfaces i.e an interface can extend multiple interfaces.
From Java 8 onwards, interfaces can have default method implementations. So to handle the diamond problem when a common default method is present in multiple interfaces, it’s mandatory to provide an implementation of the method in the class implementing them.
Question-13
What is the Marker interface?
A marker interface is an empty interface without any method but used to force some functionality in implementing classes by Java. Some of the well-known marker interfaces are Serializable and Cloneable.
Question-14
What are Wrapper classes?
Java wrapper classes are the Object representation of eight primitive types in java. All the wrapper classes in java are immutable and final. Java 5 autoboxing and unboxing allow easy conversion between primitive types and their corresponding wrapper classes.
Question-15
What is Enum in Java?
Enum was introduced in Java 1.5 as a new type whose fields consist of a fixed set of constants. For example, in Java, we can create Direction as an enum with fixed fields as EAST, WEST, NORTH, SOUTH.
Enum is the keyword to create an enum type and similar to the class. Enum constants are implicitly static and final.
Question-16
What are Java Annotations?
Java Annotations provide information about the code and they have no direct effect on the code they annotate. Annotations are introduced in Java 5. Annotation is metadata about the program embedded in the program itself. It can be parsed by the annotation parsing tool or by the compiler. We can also specify annotation availability to either compile-time only or till runtime. Java Built-in annotations are @Override, @Deprecated, and @SuppressWarnings.
Question-17
What is Java Reflection API? Why it’s so important to have?
Java Reflection API provides the ability to inspect and modify the runtime behavior of java application. We can inspect a java class, interface, enum and get their methods and field details. Reflection API is an advanced topic and we should avoid it in normal programming. Reflection API usage can break the design pattern such as the Singleton pattern by invoking the private constructor i.e violating the rules of access modifiers.
Even though we don’t use Reflection API in normal programming, it’s very important to have. We can’t have any frameworks such as Spring, Hibernate, or servers such as Tomcat, JBoss without Reflection API. They invoke the appropriate methods and instantiate classes through reflection API and use it a lot for other processing.
Question-18
What is a composition in java?
Composition is the design technique to implement has-a relationship in classes. We can use Object composition for code reuse.
Java composition is achieved by using instance variables that refer to other objects. The benefit of using composition is that we can control the visibility of other objects to client classes and reuse only what we need.
Question-19
What is the benefit of Composition over Inheritance?
One of the best practices of Java programming is to “favor composition over inheritance”. Some of the possible reasons are:
Any change in the superclass might affect the subclass even though we might not be using the superclass methods. For example, if we have a method test() in the subclass and suddenly somebody introduces a method test() in the superclass, we will get compilation errors in the subclass. The composition will never face this issue because we are using only what methods we need.
Inheritance exposes all the superclass methods and variables to the client and if we have no control in designing superclass, it can lead to security holes. Composition allows us to provide restricted access to the methods and hence more secure.
We can get runtime binding in composition where inheritance binds the classes at compile time. So composition provides flexibility in the invocation of methods.
Question-20
How to sort a collection of custom Objects in Java?
We need to implement a Comparable interface to support the sorting of custom objects in a collection. The Comparable interface has the compareTo(T obj) method which is used by sorting methods and by providing this method implementation, we can provide a default way to sort custom objects collection.
However, if you want to sort based on different criteria, such as sorting an Employee collection based on salary or age, then we can create Comparator instances and pass it as sorting methodology.
Question-21
What is an inner class in java?
We can define a class inside a class and they are called nested classes. Any non-static nested class is known as an inner class. Inner classes are associated with the object of the class and they can access all the variables and methods of the outer class. Since inner classes are associated with the instance, we can’t have any static variables in them.
We can have a local inner class or an anonymous inner class inside a class.
Question-22
What is an anonymous inner class?
A local inner class without a name is known as an anonymous inner class. An anonymous class is defined and instantiated in a single statement. Anonymous inner class always extend a class or implement an interface.
Since an anonymous class has no name, it is not possible to define a constructor for an anonymous class. Anonymous inner classes are accessible only at the point where it is defined.
Question-23
What is Classloader in Java?
Java Classloader is the program that loads byte code program into memory when we want to access any class. We can create our own classloader by extending ClassLoader class and overriding the loadClass(String name) method.
Question-24
What are different types of classloaders?
There are three types of built-in ClassLoaders in Java:
Bootstrap ClassLoader – It loads JDK internal classes, typically loads rt.jar and other core classes.
Extensions Class Loader – It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
System Class Loader – It loads classes from the current classpath that can be set while invoking a program using -cp or -classpath command-line options.
Question-25
What is a ternary operator in java?
Java ternary operator is the only conditional operator that takes three operands. It’s a one-liner replacement for the if-then-else statement and used a lot in java programming. We can use ternary operator if-else conditions or even switch conditions using nested ternary operators.
Question-26
What does super keyword do?
The super keyword can be used to access the superclass method when you have overridden the method in the child class.
We can use the super keyword to invoke superclass constructors in the child class constructor but in this case, it should be the first statement in the constructor method.
package com.java.access;
public class SuperClass {
public SuperClass(){
}
public SuperClass(int i){}
public void test(){
System.out.println("super class test method");
}
}
The use of super keyword can be seen in the below child class implementation.
package com.java.access;
public class ChildClass extends SuperClass {
public ChildClass(String str){
//access super class constructor with super keyword
super();
//access child class method
test();
//use super to access superclass method
super.test();
}
@Override
public void test(){
System.out.println("child class test method");
}
}
Question-27
What is the break and continue statement?
We can use a break statement to terminate for, while, or do-while loop. We can use a break statement in the switch statement to exit the switch case. You can see the example of break statement at java break. We can use a break with the label to terminate the nested loops.
The continue statement skips the current iteration of a for, while, or do-while loop. We can use the continue statement with the label to skip the current iteration of the outermost loop.
Question-28
What is this keyword?
This keyword provides the reference to the current object and it’s mostly used to make sure that object variables are used, not the local variables having the same name.
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
We can also use this keyword to invoke other constructors from a constructor.
public Rectangle() {
this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
Question-29
What is the default constructor?
No argument constructor of a class is known as the default constructor. When we don’t define any constructor for the class, the java compiler automatically creates the default no-args constructor for the class. If there are other constructors defined, then the compiler won’t create a default constructor for us.
Question-30
Can we have try without catch block?
Yes, we can have a try-finally statement and hence avoiding catch block.
Question-31
What is Garbage Collection?
Garbage Collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. In Java, the process of deallocating memory is handled automatically by the garbage collector.
We can run the garbage collector with code Runtime.getRuntime().gc() or use utility method System.gc(). For a detailed analysis of Heap Memory and Garbage Collection.
Question-32
What are Serialization and Deserialization?
Ans - We can convert a Java object to a Stream that is called Serialization. Once an object is converted to Stream, it can be saved to file or send over the network or used in socket connections.
The object should implement a Serializable interface and we can use java.io.ObjectOutputStream to write objects to file or to any OutputStream object.
Question-33
How to run a JAR file through a command prompt?
We can run a jar file using the java command but it requires Main-Class entry in the jar manifest file. Main-Class is the entry point of the jar and used by java command to execute the class.
Question-34
What is the use of System class?
Java System Class is one of the core classes. One of the easiest ways to log information for debugging is the System.out.print() method.
System class is final so that we can’t subclass and override its behavior through inheritance. System class doesn’t provide any public constructors, so we can’t instantiate this class and that’s why all of its methods are static.
Some of the utility methods of the System class are for array copy, get the current time, reading environment variables.
Question-35
What is an instance of a keyword?
We can use the instanceof keyword to check if an object belongs to a class or not. We should avoid its usage as much as possible. Sample usage is:
public static void main(String args[]){
Object str = new String("ABC");
if(str instanceof String){
System.out.println("String value:"+str);
}
if(str instanceof Integer){
System.out.println("Integer value:"+str);
}
}
Since str is of type String at runtime, first if statement evaluates to the true and second one to false.
Question-36
Can we use String with the switch case?
One of the Java 7 features was the improvement of the switch case of allowing Strings. So if you are using Java 7 or higher version, you can use String in switch-case statements.
Question-37
Java is Pass by Value or Pass by Reference?
This is a very confusing question, we know that object variables contain the reference to the Objects in heap space. When we invoke any method, a copy of these variables is passed and gets stored in the stack memory of the method. We can test any language whether it’s pass by reference or pass by value through a simple generic swap method.
Question-40
What is the difference between Heap and Stack Memory?
The major difference between Heap and Stack memory are as follows:
Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
Memory management in the stack is done in a LIFO manner whereas it’s more complex in Heap memory because it’s used globally.
Question-41
Java Compiler is stored in JDK, JRE, or JVM?
The task of the java compiler is to convert the java program into bytecode, we have a javac executable for that. So it must be stored in JDK, we don’t need it in JRE and JVM is just the specs.
Question-42
What will be the output of the following programs?
Static method in class
package com.java.util;
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 won’t compile because we can’t have an Object class method with a static keyword. Note that the Object class has the toString() method. You will get a compile-time error as “This static method cannot hide the instance method from Object”. The reason is that the static method belongs to the class and since every class base is an Object, we can’t have the same method in the instance as well as in class. You won’t get this error if you change the method name from toString() to something else that is not present in superclass Object.
static method invocation
package com.java.util;
public class Test {
public static String foo(){
System.out.println("Test foo called");
return "";
}
public static void main(String args[]){
Test obj = null;
System.out.println(obj.foo());
}
}
Well this is a strange situation. We all have seen NullPointerException when we invoke a method on the object that is NULL. But here this program will work and prints “Test foo called”.
The reason for this is the java compiler code optimization. When the java code is compiled to produced byte code, it figures out that foo() is a static method and should be called using class. So it changes the method call obj.foo() to Test.foo() and hence no NullPointerException.
I must admit that it’s a very tricky question and if you are interviewing someone, this will blow his mind off.
I will keep on adding more questions to the list, if you think I missed any important ones, please let me know through comments.