Java Interview Questions for Freshers

Top 45 Fresher Java Interview Questions

As a continuation in our series of Java Interview Questions, here we cover the top 30+ Java Interview Questions for Freshers that will help you start your career in Java.

Java was developed as an open-source and platform-independent programming language by Sun Microsystems in the year of 1995. From that, it has stayed relevant and showed no sign of decline in its popularity and for that reason, it is still one of the most popular programming languages.

Most of the developers choose it up as their first programming language because its syntax is simple and reasonably easy to learn. Candidates used to earn a Java certification as proof of their skills and knowledge.

Java could be learned in a very short span of time because it has English-like syntax with minimum use of special characters. It comes from a family language that is heavily influenced by C++, therefore, it provides vast opportunities when you go for these languages.

Java has become an important part of software development through which different applications are delivered for banks, governments, schools, colleges, media companies, and tech-giants. It has improved a lot in the past years, and to know about its history, one needs to first go through the Java version history.

Java’s current owner Oracle published a report which says that 97% (percent) of the enterprise desktops run Java. The enterprise adaption rate of Java is always been high and consistent which is also one of the reasons it is still relevant.

Also Read: Top Core Java Interview Questions

Java Interview Questions for Freshers

If you are planning to learn Core Java or any interview is scheduled in the coming days. As core java plays an important role in any Java interview, Java interview questions for freshers help you to prepare for Java-based interviews. In any Java-based interview, core Java is the favorite area for most interviewers and always considered to be the deciding factor of the interview.

In this article, we are trying to provide some of the important core java interview questions for freshers with answers which are to the point.

These questions cover important core java concepts that will really help you in your preparation. Here are the top trending 25+Java interview questions for freshers.

1. What are the key differences between C++ and Java?

Answer: C++ and Java both are object-oriented programming languages with some differences. The interviewer may ask the difference between the two and include this in the top Java interview questions for freshers to check your basic knowledge. The differences between C++ and Java are as follows –

C++ Java
1) C++ is platform dependent. 1) Java is platform-independent.
2) C++  writes structural programs without using classes and objects. 2) Java is a pure object-oriented language except for the primitive variables.
3) C++ doesn’t support documentation comments. 3) Java supports documentation comment (/**…*/) to create documentation for java code.
4) C++ fully supports pointers. 4) In Java, there is no concept of pointers.
5) C++ supports multiple inheritance. 5) Java doesn’t support multiple inheritance.

2.  Explain the JVM architecture?

Answer: Java Virtual Machine is the abstract machine or specification that provides a runtime environment to execute the bytecode. JVM supports Java and many other languages known as JVM languages, the program written in these languages is compiled into the bytecode and then executed by the JVM. contains key components which are classloader, memory area, execution engine etc.

a) Classloader

It is a subsystem of JVM which load class files. Whenever a Java program is run, it is loaded by the classloader.

b) Class Area

Class Area holds class-level data of each class file such as metadata, constant run pool, and static variables.

c) Heap

It is the runtime data which is used for allocating objects.

d) Stack

The stack is used for storing temporary variable. This component has a stack frame which is allocated one frame to each thread and when the execution of the thread is completed then that frame is also gets destroyed.

e) Registers

This component contains the address of JVM instruction which currently being executed.

f) Native Method Stack

All the native method stack used in the application are stored in this.

g) Execution Engine

It contains:

  • A virtual processor
  • An interpreter that executes the instructions after reading the bytecode.
  • JIT compiler, used for improving the performance due to the slow execution. It compiles the similar part of the bytecode at the same time which reduces the total time needed for compilation.

h) Java Native Interface

It provides an interface which is needed for communicating with another application developed in another language like C, C++, C# etc.

3. What is the use of Classloader in Java?

Answer: A Java program is made up of a different number of custom classes and pre-defined classes. When a program is executed, JVM is used to load all the content of that needed class and through the use of Classloader JVM, it finds that class.

There are three types of Classloaders:

  • System Class Loader

It loads all the classes from the classpath.

  • Extension ClassLoader

It loads all the classes from the extension directory.

  • Bootstrap Class Loader

It loads all the pre-defined java classes.

4. Which class is a superclass of all classes?

Answer: Java.lang.The object is the root class for all the java classes and we don’t need to extend it. Every other java classes fall back under the object. All the different non-primitive types including arrays are inherited directly or indirectly from this class.

5. What is the static keyword?

Answer: The static keyword is used with a class level variable to make it global so all the objects will be able to share the same variable. It can also be used with methods. A static method can access only static variables of the class and invoke only a static method of the class.

The interview generally asks this question in the Java interview questions for freshers. Even if you are a fresher, you should have a good knowledge of the keywords in Java.

6. What are finally and finalize in Java?

Answer: Finally block is used with a try-catch block to put the code that you always want to get executed even the execution is thrown by the try-catch block.  Finally is just used for releasing the resources which were created by the try block.

Finalize() is a special method in Object class that we can override in our classes. Finalize() is called by the Garbage collector to collect the garbage value when the object is getting it. This method is generally overridden to release the system resources when garbage value is collected from the object.

Also Read: Top Java interview questions for 5 years experience

7. What is Type casting in Java?

Answer: Casting in Java is one of the top topics from where you can get questions in your interview. When we assign a value of one data type to a different data type then these two data types might not be compatible with each other and needs conversion. If data types are compatible with each other like, in case of the conversion of int value to long then automatic conversion is done by Java and doesn’t require typecasting. But if data types are not compatible with each other then they need to be cast for conversion.


dataType variablename = (dataType) variableToConvert;

Also Read: Top 5 Java Frameworks

8. What is the inner and anonymous inner class?

Answer: In Java, we can define a class inside a class and they are called nested classes. Any nested class which is non-static are known as inner class. Inner classes are associated with objects of the class and they can access all the variables and methods of the outer class.

Any local inner class without any name is known as an anonymous inner class. It is defined and instantiated in a single statement. Anonymous inner class always extend a class or implement an interface. Since an anonymous inner class doesn’t have any name, it is not possible to create its constructor.

9. What is break and continue statement?

Answer: In a while or do-while loop, we use break for a statement to terminate the loop. We use a break statement in a switch statement to exit the switch case. We can also use break statement for terminating the nested loop.

The continue statement is used for skipping the current iteration of a for, while or do-while loop. We can use the break statement with a label to skip the current iteration of the outermost loop.

The most basic programming question, not only related to the Java. If you have some knowledge of programming languages, you should know the answer to this question as it is among frequently asked Java interview questions for freshers.

10. What is an interface?

Answer: Interfaces are the core part of Java programming language used a lot in JDK, java design patterns, and most of the frameworks and tools. The interface provides a way to achieve abstraction in Java and used to define the contract for the subclasses to implement.

The interface is a good starting point to define the type and create a top-level hierarchy in your code. In Java, a class can implement multiple interfaces, it’s better to use interfaces as a superclass in most of the cases.

11. What is aggregation in Java?

Answer: Aggregation is best defined as the entity reference where it represents the relationship between two classes where the aggregate class contains a reference to the class which it owns. Aggregation represents a has-a and whole/part relationship.

For example consider an aggregate class Employee stores information such as name, age, salary, and the Address class stores information such as city, state, and pin-code. Now, if the Employee class is defined to contain an Address object then it will be said that the Employee object has-a Address object. The Address object also makes up part-of Employee object – there is no employee without any address to live. Therefore, the Employee object owns the Address object.

12. What is the use of System class in Java?

Answer: This question is among the most common Java interview questions for freshers. Java System class is one of the core classes. One of the easiest ways to log information for debugging is System.out.print() method. System class is final so 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 System class are for array copy, get the current time, and reading environment variables.

13. What is an instanceof keyword?

Answer: We can use instanceof keyword in java to check whether an object belongs to a class or not. We should avoid much usage of it. Sample usage:

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);



14. What is an Iterator?

Answer: Iterator interface provides methods to iterate over any collection. We can get iterator instance from a collection using iterator() method. Iterator takes the place of Enumeration in the Java Collection Framework. The iterator allows the caller to remove elements from the underlying collection during the iteration. Java Collection iterator provides a generic way for transversal elements of a collection and implements Iterator Design Pattern.

15. What is the Java Collections Framework?

Answer: Collections are used in every programming language and when initial java was released it contained few classes for collections: Vector, Stack, Array, and Hashtable. But for larger scope and usage, Java 1.2 came up with Collection Framework that grouped all the collections interfaces, implementations, and algorithms.

Java Collection has come a long way with the usage of Generic and concurrent Collection classes for thread-safe operations. It has included blocking interfaces and their implementations in Java concurrent package.

Most Popular Java Interview Questions for Freshers:

In this section, we will cover the most popular Java interview questions for freshers which are commonly asked in all Java interviews. These popular Java interview questions for freshers will definitely help you in your preparation and will provide you with a better concept & learning.

16. What do you understand about Thread Priority?

Answer: Every thread when gets born is assigned with a priority value and usually higher priority gets precedence in execution but it also depends on the Thread Scheduler implementation which is OS dependent. We can assign the priority of thread but it doesn’t guarantee that higher priority will get executed before lower priority thread. Thread priority is an integer value varies from 1 to 10 where 1 is the lowest and 10 is the highest priority thread.

17. What is Thread Scheduler and Time Slicing?

Answer: Thread Scheduler is Operating System service which allocates the CPU time to the available runnable threads. Once a thread is created and it’s in the runnable phase then its execution depends on the implementation of the Thread Scheduler.

Time Slicing is a process of dividing available CPU time among the various runnable threads. Allocation of CPU time will depend on the thread priority or for how much time it is in the waiting state for getting the CPU time. Thread Scheduling cannot be controlled by Java, so it’s always better to control it by the application itself.

18. Which is more preferred – Synchronized method or Synchronized block?

Answer: The synchronized block is more preferred because it doesn’t lock the object, synchronized methods lock the object and if there are multiple synchronization blocks in the class, even though they are not related, it will stop the execution and put them in a wait state to get the lock on the object.

19. How to create daemon thread in Java?

Answer: Thread class setDaemon(true) is used for creating daemon thread in Java. We used to call this method before calling the start() method else it will give IllegalThreadStateException.

20. What is ThreadLocal?

Answer: ThreadLocal in Java is used for creating thread-local variables. We know that all threads of an object share its variables. So, if the variable is not threaded safe then we can use synchronization. But if we want to avoid synchronization then we can use ThreadLocal variables.

Every thread has its own ThreadLocal variable and they can use get() and set() methods to get the default value or change its local thread value. ThreadLocal instances are typically private static fields in classes that wish to associate the state with a thread.

21. Explain the Java Exception Hierarchy.

Answer: Java Exceptions are hierarchical and inheritance is used for categorizing the different types of exceptions. Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects – Error and Exceptions.

Errors are exceptional scenarios which are out of the scope of applications and it’s not possible to anticipate and recover from them, for example, hardware failure, JVM crash or out of memory error. Exceptions are further divided into checked and runtime exception.

Checked exceptions are exceptional scenarios that we can anticipate in a program and try to recover from it, for example, FileNotFoundException. We should catch this exception and provide a useful message to the user and log it properly for debugging purpose. The exception is the parent class of all the Checked exceptions.

Runtime exceptions are caused by bad programming, for example, trying to retrieve an element from the Array. At first, we should check the length of the array before trying to retrieve the element otherwise it might throw ArrayIndexOutOfBoundException at runtime. RuntimeException is the parent class of all runtime exceptions.

This is one of the most common Java interview questions for freshers. So, don’t miss and clear your concepts on Java exceptions.

22. What happens when an exception is thrown by the main method?

Answer: When an exception is thrown by the main() method, Java Runtime terminates the program and print the exception message and stack trace in system console.

23. How do you ensure that N thread can access N resources without getting into the Deadlock situation?

Answer: In the case when N thread can access N resources without getting into a deadlock situation, here the key point in order. If we acquire resources in particular order and releases resources in reverse order then we can prevent the deadlock situation.

24. How to get the database server details in Java program?

Answer: For this, we can use DatabaseMetaData object to get the database server details. When the database connection is created successfully, we can get the metadata object by calling getMetaData() method. There are also many methods in DatabaseMetaData that we can use to know the product name, it’s version and configuration details.

  1. DatabaseMetaData metadata = con.getMetaData();
  2. String dbProduct = metadata.getdatabaseProductName;

25. What is JDBC PreparedStatement?

Answer: JDBC PreparedStatement object represents a precompiled SQL statement. We can use its setter method to set the variables for the query. Since PreparedStatement is precompiled, it can then be used to efficiently execute this statement multiple times. PreparedStatement is a better choice than Statement because it automatically escapes the special characters and avoids SQL injection attacks.

👉 Free PDF Download for Java Interview Questions

Recent Updates

26. What are the various access specifiers in Java Class?

Answer: There are four access specifiers in Java: public, protected, default (no access specifier), and private.

Public: The fields, methods, and classes that are declared public can be accessed by any other class.

Protected: The fields, methods, and classes that are declared protected can only be accessed by classes in the same package or subclasses in other packages.

Default (no access specifier): The fields, methods, and classes that have no access specifier are accessible only to classes in the same package.

Private: The fields, methods, and classes that are declared private are only accessible within the declared class itself.

27. What is a Object in Java?

Answer: An object in Java is a data structure that represents a real-world entity. In Java, an object can be a physical object like a car, or it can be an abstract concept like a mathematical formula.

Each object has its own data and behavior. Data is the information that the object contains, while behavior is the object’s ability to perform certain actions.

Java objects are created using a class. A class is a template that defines the data and behavior of a particular type of object. Once a class has been defined, we can create objects of that class by using the new keyword.

28. What is the difference between a static and non-static method in Java?

Answer:  A static method is a method that can be called directly on a class, rather than on an instance of the class. Non-static methods, also known as instance methods, can only be called on an instance of a class.

29. What is the difference between a constructor and a method in Java?

Answer:  A constructor is a special method that is used to create and initialize an object of a class. A method is a block of code that can be called multiple times within a class.

30. What is polymorphism and how is it implemented in Java?

Answer:  Polymorphism is the ability of an object to take on multiple forms. It can be implemented in Java through method overriding and interface implementation.

31. Does the constructor return any value?

Answer: Yes, The constructor can implicitly return the current instance of the class and we cannot use explicit return type with the constructor.

32. What is an object-oriented paradigm?

Answer:It is a programming paradigm that is simply framed based upon the objects and it has data and methods defined in the class itself. It simply aims to integrate the benefits of modularity and reusability. Objects are simply referred to as instances of classes that interact with each other to design the applications and programs. 

33. What type of constructors are used in Java?

Answer: The java constructors were classified on the basis of the parameters passed and thus it has been categorized into two:

  • Default Constructor: This kind of constructor does not accept any value.And it is mainly used for initializing the instance variable with default values. It is also used for carrying out useful tasks based on the object creation. 
  • Parameterized Constructor: In this constructor, initialization of the instance variables done with given values. In other words, this kind of constructor can accept the arguments.

34. What is the usage of a default constructor?

Answer: The main use of the default constructor such as to assign the default value to the objects. The java compiler can create a default constructor in an implicit manner if the constructor does not hold any values in it.

35. Why does Java employ the Unicode System?

Answer: The Unicode system was introduced to address the issues with the earlier language standards. Java employs the Unicode system as Java requires  only 2 bytes for each character and Unicode provides a character default size of 2 bytes.

36. What is the difference between JDK, JRE, and JVM.

Feature JDK (Java Development Kit) JRE (Java Runtime Environment) JVM (Java Virtual Machine)
Purpose Development kit for creating Java applications Runtime environment for executing Java applications Runtime engine for executing Java bytecode
Components Includes development tools, libraries, and compiler Includes Java Virtual Machine (JVM), core libraries, etc. Interprets and executes Java bytecode
Usage Developers use JDK to write and compile Java code End-users install JRE to run Java applications Executes Java bytecode and manages runtime environment
Key Functions Development, compilation, debugging Running Java applications, providing core libraries Translates bytecode into machine-specific instructions
Example Tools javac (compiler), java (runtime), javadoc (documentation generator) java (runtime), javaw (for GUI applications), javap (disassembler) HotSpot JVM, OpenJ9 JVM, Zing JVM

37. What are the four principles of OOP?

The four principles of Object-Oriented Programming (OOP) are:

  1. Encapsulation: Encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit called a class. It allows for data hiding and abstraction, preventing direct access to the internal state of objects and exposing only necessary functionalities through defined interfaces.
  2. Inheritance: Inheritance is a mechanism where a new class (subclass or derived class) is created from an existing class (superclass or base class), inheriting its attributes and methods. It promotes code reusability, enabling the subclass to inherit and extend the behavior of the superclass while adding its own unique features.
  3. Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common superclass through method overriding and method overloading. It enables flexibility and extensibility in software design, allowing multiple implementations of methods with the same name but different behaviors based on the object’s type.
  4. Abstraction: Abstraction involves modeling real-world entities as classes or objects with simplified representations that focus on essential characteristics and behaviors while hiding unnecessary details. It simplifies complex systems by providing a high-level view and defining clear interfaces for interaction, facilitating modular design, and reducing complexity.

 38. What are access modifiers?

Access modifiers in object-oriented programming languages like Java, C++, and C# are keywords used to control the accessibility or visibility of classes, methods, and other members within a program. They specify the level of access that other classes or code components have to a particular class or member.

The common access modifiers include:

  1. Public: Members with the public access modifier are accessible from any other class or code component. They have the widest scope of accessibility.
  2. Private: Members with the private access modifier are accessible only within the same class where they are declared. They are not visible or accessible from outside the class.
  3. Protected: Members with the protected access modifier are accessible within the same class, subclasses (derived classes), and classes within the same package. They are not accessible from outside the package unless inherited by a subclass.
  4. Default (No Modifier): Members with no explicit access modifier (also known as package-private or default access) are accessible only within the same package. They are not accessible from outside the package.

39. What is exception handling?

Exception handling is a mechanism used in programming to deal with unexpected or exceptional conditions that occur during the execution of a program. These conditions, called exceptions, may arise due to errors in the program logic, invalid input data, hardware malfunctions, or other unforeseen circumstances.

40. What are the types of exceptions in Java?

In Java, exceptions are classified into two main categories:

  • Checked Exceptions:
      • Definition: Checked exceptions are exceptions that are checked at compile time by the compiler. They represent conditions that a well-behaved application should anticipate and recover from.
      • Examples: IOException, SQLException, ClassNotFoundException.
      • Usage: Checked exceptions must be either caught by a try-catch block or declared in the method signature using the throws keyword.
  • Unchecked Exceptions (Runtime Exceptions):
    • Definition: Unchecked exceptions are exceptions that are not checked at compile time. They typically represent programming errors or unexpected conditions that occur at runtime.
    • Examples: NullPointerException, ArrayIndexOutOfBoundsException, IllegalArgumentException.
    • Usage: Unchecked exceptions do not need to be explicitly caught or declared, but they can be caught if desired.

41. What is a binary search tree?

A binary search tree (BST) is a binary tree data structure where each node has at most two children, referred to as the left child and the right child. In a BST, the key (value) of each node is greater than all keys in its left subtree and less than all keys in its right subtree. This ordering property allows for efficient searching, insertion, and deletion operations.

42. What is a lambda expression in Java? 

A lambda expression in Java is a concise way to represent a block of code that can be passed around, like an object, and executed later. It provides a way to create anonymous functions, which can be used to implement functional interfaces, often replacing anonymous classes.

43. What is the difference between a while loop and a do-while loop in Java?

The main difference between a while loop and a do-while loop in Java lies in when the loop condition is evaluated:

  1. While Loop:
    • In a while loop, the loop condition is evaluated before the loop body is executed.
    • If the condition is false initially, the loop body will not be executed at all.
  2. Do-While Loop:
    • In a do-while loop, the loop body is executed at least once before the loop condition is evaluated.
    • Even if the condition is false initially, the loop body will be executed at least once before the condition is checked.

44. What is a thread in Java?

A thread in Java refers to the smallest unit of execution within a Java program. It represents a separate path of execution, allowing concurrent and asynchronous execution of code. Threads enable a Java program to perform multiple tasks simultaneously, making efficient use of available resources.

45. How do you implement bubble sort algorithms in Java?

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.This process is repeated until the list is sorted. Below is an implementation of the bubble sort algorithm in Java:

public class BubbleSort {

    public static void bubbleSort(int[] arr) {

        int n = arr.length;

        boolean swapped;

        for (int i = 0; i < n - 1; i++) {

            swapped = false;

            for (int j = 0; j < n - i - 1; j++) {

                if (arr[j] > arr[j + 1]) {

                    // Swap arr[j] and arr[j+1]

                    int temp = arr[j];

                    arr[j] = arr[j + 1];

                    arr[j + 1] = temp;

                    swapped = true;



            // If no two elements were swapped in the inner loop, then the array is already sorted

            if (!swapped) {





    public static void main(String[] args) {

        int[] arr = {64, 34, 25, 12, 22, 11, 90};

        System.out.println("Original array:");



        System.out.println("Sorted array:");




    public static void printArray(int[] arr) {

        for (int i = 0; i < arr.length; i++) {

            System.out.print(arr[i] + " ");






Original array:

64 34 25 12 22 11 90 

Sorted array:

11 12 22 25 34 64 90 

Final Words

So, here we have covered the top 35+ freshers Java interview questions. You can also find different java interview questions for freshers from the other sources. The key to getting success in the Java interview is going through as many questions as you can. The more questions you will go through, it will only increase your chance of clearing the interview.

Being certified also gives you an advantage to ace the interview. So, if you haven’t validated your Java expertise yet, we’ll recommend you start your preparation now for the Java certifications. Choose your certification and start the preparation with Whizlabs Oracle Java Certifications training courses.

Best of Luck for your interview!

About Aditi Malhotra

Aditi Malhotra is the Content Marketing Manager at Whizlabs. Having a Master in Journalism and Mass Communication, she helps businesses stop playing around with Content Marketing and start seeing tangible ROI. A writer by day and a reader by night, she is a fine blend of both reality and fantasy. Apart from her professional commitments, she is also endearing to publish a book authored by her very soon.

1 thought on “Top 45 Fresher Java Interview Questions”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top