Top Java Interview Questions For Freshers
Preparing for a Java interview as a fresher can be challenging, but our top 40 Java interview questions with answers can give you a competitive edge. These questions cover fundamental topics like OOP principles, Java syntax, data structures, and exception handling, providing a solid foundation for any beginner. By understanding these key areas, you can confidently demonstrate your knowledge and skills to potential employers, making you a standout candidate. So let’s start to prepare these questions to boost your confidence and impress your interviewer.
Q.1. What is Java?
Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is a general-purpose programming language that is concurrent, based on classes & objects, and designed to have as few implementation dependencies as possible. Initially designed for interactive television, it was too advanced for the digital cable television industry at the time.
Q.2. Explain the concept of the Java Virtual Machine (JVM). How does it work?
The Java Virtual Machine (JVM) is an abstract computing machine that enables a computer to run a Java program. Java code is compiled by the JVM into bytecode, which is then executed by the JVM. The JVM provides a platform-independent way of executing code, as it handles the specifics of the operating system and hardware.
Q.3. What is the difference between JDK, JRE, and JVM?
- JVM (Java Virtual Machine): The engine that provides the runtime environment to execute the Java bytecode. It does not exist physically.
- JRE (Java Runtime Environment): Comprises the JVM and the standard libraries and resources that support JVM to run Java applications.
- JDK (Java Development Kit): Includes the JRE and the compilers and tools (like JavaDoc, and Java Debugger) needed to develop Java applications.
Q.4. What do you understand by Java bytecode?
Java bytecode is the intermediate representation of Java code compiled by the Java compiler from Java source files. Bytecode is not machine instructions and therefore not tied to any specific hardware, making Java a platform-independent language. This bytecode is executed on the JVM.
Q.5. What are the main features of Java?
- Object-oriented: Everything is an object that can be easily extended according to object-oriented principles.
- Platform-independent: Java code runs on any machine that doesn’t need any special software to be installed, but the JVM needs to be present on the machine.
- Strongly typed: Every variable and expression type is known at compile time.
- Multithreaded: Supports multiple threads of execution, including a very sophisticated synchronization mechanism.
- Robust and secure: Provides many safeguards to ensure reliable code, and it has no explicit pointer and runs inside the virtual machine sandbox.
- High performance: With the use of Just-In-Time compilers, Java enables high performance.
Q.6. Can Java be used for web applications? If yes, how?
Yes, Java can be used for web applications through various technologies like Servlets, JSP (JavaServer Pages), and frameworks such as Spring and Hibernate, which facilitate the development of robust and scalable server-side applications. Java web applications run on servers, often accessed via browsers or APIs.
Q.7. Explain the concept of object-oriented programming as it relates to Java.
Object-oriented programming (OOP) in Java is based on using objects rather than actions. You organize your program as a collection of objects that embody both data and behavior. Java is purely object-oriented and supports OOP features including inheritance, encapsulation, polymorphism, and abstraction.
Q.8. What are access modifiers in Java?
Access modifiers in Java determine the accessibility or scope of a field, method, constructor, or class. There are four types of access modifiers:
- private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
- default: If no modifier is specified, the default access level is used. It is accessible only within the same package.
- protected: The protected access level provides visibility to the same package or subclasses.
- public: The public access level has no restrictions on visibility.
Q.9. What is an abstract class? How is it different from an interface?
An abstract class in Java is a class that cannot be instantiated and is always used as a base class. Abstract classes may contain abstract methods, which do not have implementations and must be implemented by subclasses. An interface is a reference type in Java, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields. The methods in interfaces are abstract by default.
Q.10. What is inheritance in Java?
Inheritance in Java is a mechanism wherein a new class is derived from an existing class. The derived class (subclass) inherits all the features from the base class (superclass) and can have additional features or override the base class methods.
Q.11. Explain method overloading and method overriding.
- Method Overloading occurs when two or more methods in the same class have the same name but different parameters (different type or number of parameters). Overloading is resolved at compile-time.
- Method Overriding occurs when a subclass has a method with the same name, return type, and parameters as a method in the parent class. It is used to give a specific implementation to a method that is already provided by its super class. Overriding is resolved at runtime.
Q.12. What is polymorphism in Java? Provide an example.
Polymorphism in Java is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. For example, if we have a parent class Animal and a derived class Dog, then a Dog object can be treated as both an animal and a dog:
Animal myDog = new Dog();
This demonstrates polymorphism where myDog can access all the methods in Animal and those in Dog that override the methods in Animal.
Q.13. What is encapsulation?
Encapsulation is a fundamental concept in object-oriented programming. It refers to the bundling of data (attributes) and methods that operate on the data into a single unit or class. It also restricts direct access to some of the object’s components, which can prevent the accidental modification of data. To achieve encapsulation in Java, declare the variables of a class as private and provide public setter and getter methods to modify and view the variables’ values.
Q.14. Explain the concept of constructors in Java.
Constructors in Java are special methods used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. Constructors do not have a return type, not even void, and its name must be exactly the same as the class name.
Q.15. What is the use of the ‘this’ keyword in Java?
The this keyword in Java is a reference variable that refers to the current object. It is used to:
- Differentiate between class attributes and parameters with the same name (commonly used in constructors and setters).
- Pass the current object as a parameter to another method.
- Invoke the current object’s method.
- Return the current class instance from the method.
Q.16. How do you handle exceptions in Java?
Exceptions in Java are handled using:
- try block: Code that might throw an exception is placed in this block.
- catch block: This block catches and handles the exception thrown by the try block.
- finally block: This block executes regardless of whether an exception was thrown or caught, and is typically used for clean-up activities.
- throw keyword: Used to explicitly throw an exception.
- throws keyword: Used in the method signature to indicate that this method might throw this type of exception.
Q.17. What are the different types of exceptions in Java?
Exceptions in Java are broadly classified into two types:
- Checked Exceptions: Exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.
- Unchecked Exceptions: These are the exceptions that are not checked at compile time. It includes runtime exceptions and errors.
Q.18. Explain the final keyword in Java.
The final keyword in Java is used to apply restrictions on class, method, and variable. A final class cannot be subclassed, a final method cannot be overridden, and a final variable cannot change from its assigned value.
Q.19. How is data encapsulation implemented in Java?
Data encapsulation in Java is implemented by declaring the variables of a class as private and providing public setter and getter methods to modify and view the variables’ values. This protects the integrity of the data by hiding it from external access and allowing controlled modifications.
Q.20. What are packages in Java?
Packages in Java are namespaces that organize a set of related classes and interfaces. By using packages, developers can easily modularize the code and optimize its reuse. Additionally, packages help avoid name conflicts between the classes by providing a way to categorize the classes that are being developed.
Q.21. What is garbage collection in Java?
Garbage collection in Java is the process by which Java programs perform automatic memory management. Java programs compile to bytecode that is run on the Java Virtual Machine (JVM). As programs run, the JVM automatically frees memory used by objects to which no active pointer exists, helping manage memory and reduce memory leaks.
Q.22. How can you prevent a class from being subclassed?
To prevent a class from being subclassed in Java, you can declare the class as final. A final class cannot be extended by any other class, thus effectively preventing inheritance. For example:
public final class MyFinalClass {
// class body
}
Q.23. What is multithreading in Java?
Multithreading in Java is a process of executing multiple threads simultaneously to maximize the utilization of CPU time. A thread is the smallest unit of processing that can be scheduled by an operating system. Multithreading leads to concurrent execution of two or more parts of a program to utilize the CPU time more efficiently.
Q.24. How do you implement synchronization in Java?
Synchronization in Java is used to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This can lead to significant errors. The synchronized keyword in Java provides a mechanism for locking the resource being accessed by a thread. Here’s an example:
public synchronized void syncMethod() {
// method body
}
Alternatively, synchronization blocks can also be used to synchronize a block of statements rather than an entire method.
public void someMethod() {
synchronized(this) {
// block of code
}
}
Q.25. What are the differences between processes and threads?
- Process: A process is a program in execution. A process has a self-contained execution environment including its own memory space. Multiple processes can run concurrently on a computer, and they do not share memory with each other.
- Thread: A thread is a lighter unit of process. Multiple threads can exist within the same process and share resources such as memory, while still executing independently. Threads are used for small tasks within a program.
Q.26. Explain the importance of the main() method in Java.
The main() method in Java is the entry point for any standalone Java application. The signature of this method is always:
public static void main(String[] args) {
// application logic
}
When a Java class is executed by the JVM, the main()
method is called, and the code within it is executed first.
Q.27. What is the default value of local variables?
Local variables in Java do not have a default value and must be initialized before use. If a local variable is declared but not initialized, the compiler will throw an error.
Q.28. What is the significance of static methods and static variables?
Static methods and static variables are associated with the class itself rather than with any object. Every instance of the class shares the same static variable, which can be accessed directly by the class name and doesn’t need any object. Static methods can access static data member and can change the value of it.
Q.29. What is the use of the super keyword?
The super keyword in Java is a reference variable which is used to refer to the immediate parent class object. It can be used to access superclass methods and constructors, and also to access a field of the parent class that has been hidden by a field in a subclass.
Q.30. Explain how to create a memory leak in Java.
Although Java manages memory through garbage collection, memory leaks can still occur if objects hold references unnecessarily, preventing the garbage collector from reclaiming the memory. For example:
public class MemoryLeakExample {
List<Object> leakyList = new ArrayList<>();
public void leak() {
Object obj = new Object();
// Adding to the list and never clearing it
leakyList.add(obj);
}
}
This code keeps adding objects to the list without ever clearing them, even if they are no longer needed, leading to a memory leak.
Q.31. What is the purpose of the System class?
The System class in Java provides several useful class fields and methods. It cannot be instantiated. Among its facilities are standard input, standard output, error output streams, access to externally defined properties and environment variables, a means of loading files and libraries, and a utility method for quickly copying a portion of an array.
Q.32. Explain the difference between == and equals() in Java.
In Java, == is a reference comparison, i.e., both objects point to the same memory location. Meanwhile, equals() evaluates to the comparison of values in the objects. If a class does not override the equals() method, then by default it uses == operator to compare two objects. For example, String class overrides the equals() method so that it checks only the contents of the strings, not their references.
Q.33. What are wrapper classes?
Wrapper classes provide a way to use primitive data types (int, boolean, etc.) as objects. The primitive data type needs to be wrapped as an object for synchronization, as object collections in utilities, such as Java Collections cannot work with primitive data types. Some examples of wrapper classes are Integer, Character, Boolean, and Long.
Q.34. What are the benefits of using generics in Java?
Generics provide type safety and flexibility to Java collections by allowing them to operate on objects of various types while providing compile-time type safety. This helps in detecting errors at compile time rather than at runtime and aids in eliminating the risk of ClassCastException.
Q.35. How do you convert a string to an integer in Java?
In Java, you can convert a string to an integer using the parseInt() method of the Integer class:
String number = "123";
int result = Integer.parseInt(number);
This will convert the string “123” to the integer 123.
Q.36. What is a Java Array and how is it different from an ArrayList?
A Java array is a fixed-size data structure which can store elements of the same type. An ArrayList, however, is part of the Java Collections Framework and can dynamically grow or shrink in size, offers more flexibility, and provides more powerful insertion and search mechanisms than arrays.
Q.37. What is a singleton class? Give an example.
A singleton class is a class that is designed to have only one instance in the whole application, with a global point of access to this instance. The classic implementation involves a private constructor and a field that holds the sole instance:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Q.38. Explain the concept of Java Annotations.
Java annotations are a form of metadata that provide data about a program but are not part of the program itself. Annotations have no direct effect on the operation of the code they annotate. They can be used for a variety of purposes, such as compile-time instructions for the Java compiler, compile-time and deployment-time processing, or runtime processing.
Q.39. What is the purpose of the finally block in exception handling?
The finally block in Java exception handling is the block that is always executed whether an exception is handled or not. Therefore, it is used for clean-up activities such as closing files, releasing resources, etc.
Q.40. Describe how you can make a Java class immutable.
To make a class immutable in Java:
- Declare the class as final so it can’t be extended.
- Make all fields private so that direct access is not allowed.
- Don’t provide setter methods for variables.
- Make all mutable fields final so that their value can be assigned only once.
- Initialize all fields via a constructor performing deep copy.
- Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.