1.What modifiers are allowed for methods in an interface?
Public: Interface methods are implicitly public, meaning they are accessible from anywhere.
Abstract: Interface methods are implicitly abstract, indicating that they do not have an implementation in the interface itself.
Default: Starting from Java 8, interfaces can have default methods, which provide a default implementation for the method. Default methods are declared using the default
keyword and can be overridden by implementing classes if needed.
Static: Interfaces can have static methods, which are defined using the static
keyword. Static methods in interfaces are not inherited and can be called directly using the interface name.
It’s important to note that in Java 17 and earlier versions, interface methods cannot have the private
, protected
, or final
modifiers. These modifiers are not allowed for interface methods until Java 18, which introduced the private
and protected
modifiers for interface methods.
2. What is a local, member, and a class variable?
Variables declared within a method are local. Variables declared within a class but outside of methods are member variables. Variables within a class that are static are called class variables.
A local variable is a variable declared inside a method, constructor, or a block of code, such as a loop or conditional statement. It is accessible only within its enclosing scope and is not visible outside of that scope. Local variables are used for temporary storage and hold data that is relevant only within a specific block of code. Local variables must be initialized before they can be used.
public void process() { int num = 10; // Local variable declaration and initialization // ... }
In the above example, num
is a local variable declared inside the process()
method. It is accessible only within the method and is not visible outside of it.
Member variables, also known as instance variables, are declared within a class but outside of any method. They are associated with instances (objects) of the class and each instance of the class has its own copy of these variables. Member variables have default values if not explicitly initialized. They are accessible within the entire class, including its methods and constructors.
public class User { private String name; // Member variable declaration public void setName(String value) { name = value; // Accessing member variable within a method } }
In the above example, name
is a member variable declared within the User
class. It is accessible in all methods and constructors of the class, and each instance of User
will have its own copy of this variable.
Class variables, also known as static variables, are declared within a class with the static
modifier. Unlike member variables, class variables are associated with the class itself rather than with instances of the class. There is only one copy of a class variable shared by all instances of the class. Class variables are initialized only once when the class is loaded into memory and retain their values throughout the program execution.
public class User { private static int time; // Class variable declaration public static void setTime(int value) { time = value; // Accessing class variable within a static method } }
In the above example, time
is a class variable declared within the User
class. It is shared among all instances of the class, and its value can be accessed and modified through static methods or by directly referencing the class name (User.time
).
It’s important to note that local variables are temporary and exist only within the scope of a method or block, member variables belong to instances of a class, and class variables are associated with the class itself and are shared among all instances of the class.
3. What are Serialization and Deserialization?
Serialization is the process of saving/writing the state of an object to a byte stream.
Deserialization is the process of restoring a serialized object.
4. Can you have an inner class within a method and what variables can you access?
It is possible to have an inner class within a method. These inner classes are called local inner classes or method-local inner classes. They are defined within a method or a block of code and have their own scope limited to that method or block. Local inner classes have access to variables declared within the method/block, as well as to the method’s/block’s parameters and any final or effectively final variables.
public class OuterClass { public void outerMethod() { int outerVariable = 10; class LocalInnerClass { public void innerMethod() { System.out.println("Accessing outer variable: " + outerVariable); } } LocalInnerClass innerObj = new LocalInnerClass(); innerObj.innerMethod(); } }
5. What is the clonable interface?
The clonable interface is a marker interface. The Cloneable
interface is a marker interface that indicates a class’s ability to be cloned using the clone()
method. It serves as a marker for objects that can support cloning, allowing you to create a copy of an object with the same state.
The Cloneable
interface does not contain any methods. It acts as a flag, notifying the clone()
method that the object can be cloned without throwing a CloneNotSupportedException
. If a class implements Cloneable
, it indicates that instances of that class can be cloned.
To make a class cloneable, you need to follow these steps:
public class MyClass implements Cloneable { // class members and methods @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
The clone()
method is declared in the Object
class and is protected, so you need to provide a public implementation in your class to make it accessible.
When cloning an object, you call the clone()
method on an instance of the class, which creates and returns a shallow copy of the object. It is important to note that the clone()
method performs a shallow copy by default, meaning that only the object’s references are copied, not the referenced objects themselves.
In a shallow copy, only the references of the fields are copied from the original object to the cloned object. Both the original and cloned objects will point to the same referenced objects in memory. In other words, changes made to the referenced objects in one object will be reflected in the other object as well.
If you need a deep copy (i.e., copies of the referenced objects as well), you need to implement a custom cloning mechanism within the clone()
method. To deep copy an object you ensure that all the referenced objects in the class also implement the Cloneable
interface and override their clone()
methods.
6. What is the difference between Integer and int?
Integer is a wrapper class for the primitive int. Integer can be used for generic like List<Integer> list. It cannot be List<int> list.
int is the primitive.
7. What is an inner class and an anonymous class?
An inner class is any class defined in another class even an inner class within a method.
An anonymous class is a class defined inside a method. This class does not have a name. It is instantiated and declared in the same place. It can’t have explicit constructors.
An anonymous class is a specific type of inner class that does not have a name. It is declared and instantiated in a single expression, usually at the point of use. Anonymous classes are commonly used to implement interfaces, extend classes, or define event handlers.
Here’s an example of an anonymous class implementing an interface:
interface MyInterface { void doSomething(); } public class MyClass { public void performAction() { MyInterface myInterface = new MyInterface() { public void doSomething() { System.out.println("Doing something..."); } }; myInterface.doSomething(); } }
8. What modifiers can a top-class have?
public, abstract, and final.
9. What is the difference between a superclass and a subclass?
A superclass is a class that is inherited.
A subclass is a class that does the inheriting.
10. What is the difference between overloading and overriding?
Overloading is a relationship between different methods within a class.
Overloading methods have the same name with different method signatures.
Overloading:
public class Calculator { public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; } }
Overriding is a relationship between a superclass and a subclass.
Overriding methods must have the same method signatures.
Overriding:
public class Animal { public void makeSound() { System.out.println("Animal makes a sound."); } } public class Dog extends Animal { @Override public void makeSound() { System.out.println("Dog barks."); } }
11. What is final, finalize(), and finally?
final: a final class can’t be extended. a final method can’t be overridden. a final variable can be changed from its initial value.
finalize(): this method is called just be an object is garbage collected.
finally: a finally block a block which is part of a try or try and catch block. This block runs regardless of an exception is thrown or not.
12. What are the different types of access modifiers in Java?
public: can be accessed from everywhere.
private: can be accessed outside of the class in which private is used.
protected: can be accessed from the same package or subclasses from different packages.
Default modifier: can be accessed only from the same package.
13. What do static methods mean?
Static methods can be called using just the class name. Static methods belong to class not an object of the class. You don’t have to create an object to access static methods.
14. What does it mean that a method or a field is static?
Static variables and methods are instantiated only once per class. If you change the value of a static variable, it will change for all instances of that class.
15. What is the common usage of serialization?
Serialization in Java refers to the process of converting an object into a byte stream, which can be saved to a file, sent over a network, or stored in a database. Deserialization is the reverse process, where the byte stream is converted back into an object.
When an object(and its state) is to be saved somewhere and be retrieved for later use then serialization comes into the picture. When you cache an object using a cache manager(Redis) the object must be serialized.
Caching: Serialization can be used for caching objects in memory or on disk. By serializing objects, they can be stored in a cache and quickly retrieved when needed. This helps improve performance by reducing the need to recreate objects from scratch.
Network Communication: Serialization enables objects to be transmitted across a network or between distributed systems. By serializing an object and sending it over the network, the receiving end can deserialize it to obtain the original object. This is commonly used in client-server architectures, remote procedure calls (RPC), distributed computing, and messaging systems.
Persistence: Serialization allows objects to be stored persistently in files or databases. By serializing an object, its state can be saved, and later, the object can be deserialized to recreate the exact state. This is useful for saving and loading application data, configuration settings, user preferences, and more.
import java.io.*; public class SerializationExample { public static void main(String[] args) { // Create an object to serialize Person person = new Person("John Doe", 30); // Serialize the object to a file serializeObject(person, "person.ser"); // Deserialize the object from the file Person deserializedPerson = deserializeObject("person.ser"); // Print the deserialized object System.out.println("Deserialized Person: " + deserializedPerson); } public static void serializeObject(Object obj, String fileName) { try { // Create a FileOutputStream to write object data to a file FileOutputStream fileOut = new FileOutputStream(fileName); // Create an ObjectOutputStream to serialize the object ObjectOutputStream objectOut = new ObjectOutputStream(fileOut); // Write the object to the ObjectOutputStream objectOut.writeObject(obj); // Close the streams objectOut.close(); fileOut.close(); System.out.println("Object serialized and saved to " + fileName); } catch (IOException e) { e.printStackTrace(); } } public static <T> T deserializeObject(String fileName) { T obj = null; try { // Create a FileInputStream to read object data from a file FileInputStream fileIn = new FileInputStream(fileName); // Create an ObjectInputStream to deserialize the object ObjectInputStream objectIn = new ObjectInputStream(fileIn); // Read the object from the ObjectInputStream obj = (T) objectIn.readObject(); // Close the streams objectIn.close(); fileIn.close(); System.out.println("Object deserialized from " + fileName); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } return obj; } } class Person implements Serializable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Person{name='" + name + "', age=" + age + "}"; } }
16. What is java String Pool?
The string pool is a memory area in the Java heap where String literals are stored. The string pool is a way of conserving memory by reusing existing String objects instead of creating new ones with the same content. Whenever a new string object is created, String pool first checks whether the object is already present in the pool or not. If it is present, then the same reference is returned to the variable else new object will be created in the String pool and the respective reference will be returned.
17. What are the differences between this() and super()?
this() | super() |
1. this() represents the current instance of a class | 1. super() represents the current instance of a parent/base class |
2. Used to call the default constructor of the same class | 2. Used to call the default constructor of the parent/base class |
3. Used to access methods of the current class | 3. Used to access methods of the base class |
4. Used for pointing the current class instance | 4. Used for pointing the superclass instance |
5. Must be the first line of a block | 5. Must be the first line of a block |
18. What are the differences between String, String Builder, and String Buffer?
Factor | String | String Builder | String Buffer |
Storage Area | Constant String Pool | Heap Area | Heap Area |
Mutability | Immutable | Mutable | Mutable |
Thread Safety | Yes | No | Yes |
Performance | Fast | Fast | Slow |
19. What is constructor chaining?
Constructor chaining is the process of calling a constructor from another constructor. This is done using this() keyword.
It’s the process of calling one constructor from another constructor within the same class or between parent and child classes. It allows constructors to invoke other constructors to perform common initialization tasks or to provide different options for object creation.
Within the Same Class:
this()
keyword, a constructor can call another constructor in the same class.this()
must be the first statement in the constructor body.public class MyClass { private int value; public MyClass() { this(0); // Calls the parameterized constructor with value 0 } public MyClass(int value) { this.value = value; } }
Between Parent and Child Classes:
super()
keyword.super()
call must be the first statement in the subclass constructor.public class Animal { protected String name; public Animal(String name) { this.name = name; } } public class Dog extends Animal { private String breed; public Dog(String name, String breed) { super(name); // Calls the constructor of the superclass (Animal) this.breed = breed; } }
Constructor chaining allows for code reuse and helps maintain a clean and modular design by centralizing common initialization logic in one place. It enables constructors to be flexible and provide different ways to construct objects based on the available parameters.
20. Why do we need constructor chaining?
Constructor chaining is useful when we want to perform multiple tasks in a single constructor rather than creating code for each task in a single constructor. We create a separate constructor for each task and make it a chain that makes the program more readable.
21. Why is String immutable?
In Java, string objects are immutable in nature which simply means once the String object is created its state cannot be modified. Whenever you try to update the value of that string, Java creates a new string object instead of updating the values of that particular string. Java String objects are immutable as String objects are generally cached in the String pool. Since String literals are usually shared between multiple clients, action from one client might affect the rest. It enhances security, caching, synchronization, and performance of the application.
22. What are the differences between Array and ArrayList?
Array | ArrayList |
---|---|
Cannot contain values of different data types | It can contain values of different data types. |
Size must be defined at the time of declaration | Size can be dynamically changed |
Need to specify the index in order to add data | No need to specify the index |
Arrays are not type parameterized | ArrayList are type |
Arrays can contain primitive data types as well as objects | ArrayList can contain only objects, no primitive data types are allowed |
23. What is pass by value?
You are passing the values copied. Java is passed by value when you pass primitive data types and passed by reference when you pass custom object data types.
24. What is pass by reference?
You are passing the memory address of the variables you are passing.
25. What is an interface?
An interface is similar to a class but it is an abstract class completely. An interface has abstract methods that its subclasses have to implement. When we talk about an interface we are talking about its capabilities. We are not even talking about how these capabilities are formed, just what they are.
26. 30 commonly asked Java interview questions
Question: Explain the difference between JDK, JRE, and JVM. Answer:
Question: What is the difference between a class and an object in Java? Answer: A class is a blueprint or template that defines the structure and behavior of objects, while an object is an instance of a class.
Question: What is the difference between the ==
operator and the equals()
method in Java? Answer: The ==
operator is used to compare the references of two objects, while the equals()
method is used to compare the content or value of two objects. The equals()
method should be overridden in classes to define custom equality.
Question: What is the difference between checked and unchecked exceptions in Java? Answer: Checked exceptions are checked at compile-time and must be handled explicitly using try-catch blocks or declared in the method signature using the throws
keyword. Unchecked exceptions, also known as runtime exceptions, do not require explicit handling or declaration.
Question: What are access modifiers in Java? Explain their significance. Answer: Access modifiers control the visibility and accessibility of classes, methods, and variables. They include public
, protected
, private
, and default (no modifier). Access modifiers ensure proper encapsulation and provide control over the accessibility of code.
Question: What is the static
keyword in Java used for? Answer: The static
keyword is used to define class-level members that are shared among all instances of a class. static
methods and variables can be accessed without creating an instance of the class.
Question: What is the purpose of the final
keyword in Java? Answer: The final
keyword is used to restrict the behavior of classes, methods, and variables. A final class cannot be subclassed, a final method cannot be overridden, and a final variable cannot be reassigned once initialized.
Question: What is the difference between method overloading and method overriding? Answer: Method overloading is the process of defining multiple methods with the same name but different parameters within the same class. Method overriding occurs when a subclass provides a different implementation of a method that is already defined in its superclass.
Question: Explain the concept of inheritance in Java. Answer: Inheritance allows a class to inherit the properties (fields and methods) of another class, known as the superclass or parent class. It promotes code reuse and allows for the creation of specialized classes from a general superclass.
Question: What is the this
keyword in Java used for? Answer: The this
keyword refers to the current instance of a class. It is often used to differentiate between instance variables and method parameters or to invoke constructors within a class.
Question: What is the purpose ofContinuing from the previous response, here are more Java interview questions along with their answers:
Question: What are abstract classes and interfaces in Java? Answer: Abstract classes are classes that cannot be instantiated but can be used as base classes for subclasses. They can have abstract methods (without implementation) and concrete methods. Interfaces, on the other hand, define a contract of methods that a class must implement. They cannot contain implementation details.
Question: What is method overriding in Java? Answer: Method overriding occurs when a subclass provides a different implementation of a method that is already defined in its superclass. The overridden method in the subclass must have the same signature (name, return type, and parameters) as the method in the superclass.
Question: What is the difference between checked and unchecked exceptions in Java? Answer: Checked exceptions are checked at compile-time and must be handled explicitly using try-catch blocks or declared in the method signature using the throws
keyword. Unchecked exceptions, also known as runtime exceptions, do not require explicit handling or declaration.
Question: What is the purpose of the StringBuilder
class in Java? Answer: The StringBuilder
class is used to create and manipulate mutable strings. It provides methods for appending, inserting, and modifying strings efficiently.
Question: Explain the concept of autoboxing and unboxing in Java. Answer: Autoboxing is the automatic conversion of primitive types to their corresponding wrapper classes, while unboxing is the automatic conversion of wrapper classes back to primitive types. This conversion is done by the compiler.
Question: What is the difference between String
, StringBuilder
, and StringBuffer
in Java? Answer:
String
is an immutable class, meaning its value cannot be changed once created. It is suitable for situations where the value needs to remain constant.StringBuilder
and StringBuffer
are mutable classes that can be used to manipulate strings. StringBuilder
is not thread-safe, while StringBuffer
is thread-safe due to its synchronized methods.Question: What is the purpose of the Collections
class in Java? Answer: The Collections
class provides utility methods for working with collections (lists, sets, etc.) in Java. It includes methods for sorting, searching, and modifying collections.
Question: What is the purpose of the equals()
method in Java? Answer: The equals()
method is used to compare the equality of two objects. It is typically overridden to provide a custom implementation for object comparison based on specific criteria.
Question: Explain the concept of serialization in Java. Answer: Serialization is the process of converting an object into a byte stream to be stored in memory, sent over a network, or persisted to a file. Deserialization is the reverse process of reconstructing the object from the byte stream.
Question: What is the purpose of the try-catch-finally
block in Java? Answer: The try-catch-finally
block is used for exception handling. The try
block contains the code that may throw an exception, the catch
block handles the exception, and the finally
block is executed regardless of whether an exception occurs or not.
Question: What is the difference between ArrayList
and LinkedList
in Java? Answer:
ArrayList
is implemented as a dynamic array, providing fast random access and iteration. It is suitable for scenarios where frequent element access and modification are required.LinkedList
is implemented as a doubly-linked list, providing fast insertion and deletion at both ends. It is suitable for scenarios where frequent insertions and deletions are required.Question:Continuing from the previous response, here are more Java interview questions along with their answers:
Question: What is the difference between the throw
and throws
keywords in Java? Answer:
throw
keyword is used to explicitly throw an exception within a method or block of code.throws
keyword is used in a method signature to indicate that the method may throw one or more exceptions. It is used for checked exceptions.Question: What is the difference between HashMap
and HashTable
in Java? Answer:
HashMap
is not synchronized and allows null values and keys, while HashTable
is synchronized and does not allow null values or keys.HashMap
is generally preferred over HashTable
for better performance unless thread-safety is required.Question: What is the purpose of the finalize()
method in Java? Answer: The finalize()
method is a method of the Object
class that is called by the garbage collector before reclaiming an object’s memory. It can be overridden to perform cleanup tasks before the object is garbage collected.
Question: What is the difference between shallow copy and deep copy? Answer:
Question: What is the purpose of the static
initializer block in Java? Answer: The static
initializer block is a block of code that is executed only once when the class is loaded into memory. It is used to initialize static variables or perform one-time setup tasks for the class.
Question: What is the purpose of the System.gc()
method in Java? Answer: The System.gc()
method is used to suggest to the JVM that it should run the garbage collector to free up memory. However, it does not guarantee immediate garbage collection.