java interview questions

Java Interview Questions and Answers

April 6th, 2026
13374
60:00 Minutes

If you are preparing for a Java interview, you are probably asking yourself a lot of questions right now. What topics should you focus on? Are interviewers going to ask more about core Java or frameworks? And most importantly, how do you stand out among so many candidates? I have seen this confusion in many learners, and honestly, it is completely normal.

Java interviews are not just about writing code or recalling syntax. Employers want to see how well you understand concepts like object-oriented programming, memory management, collections and exception handling. They are equally interested in how you think, how you solve problems, and how clearly you can explain your approach. That is where most candidates either shine or struggle.

This is exactly why this Java interview preparation guide is designed for you. In this article, we will go through the most commonly asked Java interview questions, starting from basic concepts and moving toward advanced topics.

Explore our most asked Java Interview Questions and answers curated by top industry experts to help you crack your next Java developer interview.

Basic Java Interview Questions for Freshers

The core questions are such that beginners and experienced ones should know about them alike. These Java interview questions for freshers are however, a bit different. These are basic knowledge-based questions without including many skill-related topics.

1. What is a Java Virtual Machine?

JVM is a Java interpreter. It loads, verifies, and consequently executes the bytecode created in this language. It is platform-dependent wherein its software is different for different operating systems.

2. Explain garbage collection. What is its main objective?

Garbage collection here avoids memory leaks that may lead to crashing and instability of the program. Programmers can focus better on the app development process with garbage collection rather than managing memory resources. All the unreferenced objects get removed from the memory heap, and make its memory more efficient.

Master Java Programming with Java Training

Boost your coding skills and gain hands-on knowledge in Java.

Explore Now

3. Why is this a platform-independent language?

The purpose of this programming language was not to be dependent on any software or hardware. This is only possible since the compiler compiles the code and then converts it to platform-independent bytecode. Multiple systems can easily run this bytecode. The only condition here to run that bytecode is that the machine must have a runtime environment (JRE) installed.

4. How are Java and C++ different?

Here are some key points of difference between these two -

  • C++ is a compiled language only. Java programming language is compiled and interpreted.
  • C++ programs only run on a compiled machine while in another language the programs are machine-independent.
  • Users can use pointers in the program in C++, whereas the other uses pointers internally.
  • Only C++ supports multiple inheritance concepts.

5. Why are pointers not used in Java?

Pointers are not used here to make it easy for beginner programmers. Freshers might not be able to use pointers because of their complexity. Java programming language prefers code simplicity which is not provided by pointers. Pointers may lead to errors or even compromise security since they can directly access memory. They also make the garbage collection process slow and prone to errors.

6. What do access modifiers mean in Java?

Access modifiers are special keywords that control the scope and visibility of a method, variable, constructor or class in an application. They are important for object-oriented programming for enforcing encapsulation. There are four main types -

  • Public - These are accessible everywhere.
  • Protected - These are accessible only within the package as well as the subclasses.
  • Private - These are accessible only within the class.
  • Default - These are accessible within the package.

7. What is understood by local variables and instance variables?

Local variables are present within a function, constructor or block with accessibility only within them. Its usability is limited to the block scope. Other class methods do not get any update about the local variable even when it gets declared inside a method.

Example

public class Athlete {

    public void athlete() {

        String athleteName;
        double athleteSpeed;
        int athleteAge;

    }
}

Instance variables are accessible through all the methods in a class. They reside inside the class but outside the methods. These describe an object's properties and stay bound to it at all costs. All class objects have a copy of the variables. Any modification done to a variable only impacts that instance. All other class instances stay unaffected.

Example

public class Athlete {

    public String athleteName;
    public double athleteSpeed;
    public int athleteAge;

}

8. Explain data encapsulation.

Data Encapsulation is an OOP (object-oriented programming) concept. A single unit hides the data attributes and their behaviors. Developers can follow modularity when developing software. This is done by making sure that every object stays independent of other objects through their own attributes, functionalities and methods. It serves the purpose of data hiding by securing an object's private properties.

9. How can exceptions be handled in Java?

Try-catch blocks gracefully handle exceptions. The code that may throw an exception is written in the try block. The catch block specifies the reaction of the code if the exception occurs. A final block is usable for cleanup operations in case the try-catch blocks have to deal with external resources (like database connections, file managers, etc).

Example

import java.io.FileReader;
import java.io.IOException;

public class ExceptionHandlingExample {

    public static void main(String[] args) {

        FileReader reader = null;

        try {
            reader = new FileReader("nonexistent.txt");

            // Code that might throw an exception
            int character = reader.read();
            System.out.println((char) character);

        } catch (IOException e) {

            // Handling the specific exception
            System.out.println("An error occurred while reading the file: " 
                                + e.getMessage());

        } finally {

            // Cleanup code that always executes
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    System.out.println("Error closing file: " 
                                        + e.getMessage());
                }
            }
        }
    }
}

10. Explain the class constructor's purpose in the Java programming language.

Constructors are methods used for initializing instances of a class. They share their name with the class and their need arises as a new object gets created through the new keyword.

11. Explain the concept of constructor overloading in this language.

The process of constructor overloading creates many different constructors in the class. These consist of the same name but with a distinction in the constructor parameters. The compiler distinguishes the different types of constructors according to the number of parameters as well as their corresponding types.

12. Give an explanation for Java Data Types.

Java Data Types

Java is mainly segregated into two data types. These are primitive and non-primitive (or reference) types.

  • Primitive Data Types - These are int, char, float, boolean, etc.
  • Non-primitive Data Types - These include objects, interfaces and Arrays.

Related Article- Write Your First Java Program - Hello World

Java Interview Questions and Answers for Intermediates

Someone with mid-level experience will also have to prepare according to their current skill set and knowledge base. These Java intermediate interview questions cover such professionals. These intermediate-level experts must have a good grasp of the fundamentals and also be a few steps above it.

13. How are the Runnable and Callable interfaces different from one another in Java concurrency?

Both Runnable and Callable interfaces define tasks that are executable by threads. The first one neither returns a result nor can it throw checked exceptions. This makes it simpler to use for most basic tasks. Callable can return a result as well as throw checked exceptions. It is usually used along with ExecutorService for asynchronous task execution.

Runnable can be thought of as a worker silently doing their job but not reporting back with any information except ultimate success or failure. Callable can be considered a more professional worker who puts together an extended report on task results. This result outlines any problems it encountered during task execution.

14. What is Memory storage available with JVM?

Memory Storage JVM

The memory storages available with JVM are -

  • Class (Method) Area - These store class-level data of all the classes. It includes the runtime constant pool, method data and field.
  • Heap - Here the objects are created or stored. It allocates memory for objects during run time.
  • Stack - It stores data as well as partial results that are needed when performing dynamic linking and returning value for the method.
  • Program Counter Register - It stores JVM's address instruction that is being executed currently.
  • Native Method Stack - It stores all the native methods that are used in the application.

15. Describe the Singleton pattern. Make it clearer with an example of implementing the Singleton pattern.

The Singleton pattern is behind making sure that the class only has a single instance. It manages global states or resources with ease. Scenarios involving centralized control (like database connections or logging) also use this pattern.

Example

public class Singleton {

    private static volatile Singleton instance;

    // Private constructor to prevent instantiation
    private Singleton() {
    }

    public static Singleton getInstance() {

        if (instance == null) {

            synchronized (Singleton.class) {

                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }

        return instance;
    }
}

16. How can a highly scalable, distributed caching system be designed using Java?

A highly scalable and distributed caching system uses technologies like Apache Ignite or Hazelcast. The main considerations to keep in mind are -

  • Partitioning strategy for data distribution.
  • Consistency model.
  • Replication for fault tolerance.
  • Communication protocols and network topology.
  • Eviction policies.
  • Integration with existing systems.

17. Is it possible for the 'finally' block to not be executed? List the case if yes.

Yes, it is a possibility that the 'finally' block might not get executed. The two cases in which this might happen are -

  • In case System.exit() is used in the above statement.
  • In the case of fatal errors like Memory access errors, Stack overflow, etc.

18. Why is Java's main method static?

Java Interview Questions Main Method

The main method in this programming language is always static. This is because static members are methods belonging to the classes rather than individual objects. The main method has to be static for every available object to be acceptable by JVM. JVM uses the class name itself for calling the main method rather than by creating the object.

19. Why use reflection in Java?

Reflection gives information about the class of the object. It is a method of executing a class by using the object. It shows the inspection ability of a program on other code. We can modify it during the runtime. For instance, we have an unknown object type and a method fooBar() to call on the object.

This method cannot be implemented until we get the object type. This is achieved by reflection through which code scans the object and identifies its type. Then it will call the fooBar() method when required.

20. What do you understand about the IS-A relationship in OOPs Java?

IS-A relationship is an element of object oriented programming language. The relationship between the derived class and its base class is known as the IS-A relationship. It means the derived class has inherited some properties of the base class.

21. Can we turn the main() thread into a daemon thread?

Changing the main() threads into a daemon thread is not possible. There is no way to achieve this task.

22. Explain exception propagation in a code.

It is a long process. The extension instantly searches the matching catch block once it occurs. Then it executes the block once it is located. If it can not locate the block then it will go into the caller method.

The caller method tries to match the catch block. This propagation keeps happening until it finds the block. The program gets terminated if no match is found.

23. What is a class variable (static variable)?

Class variables are used for managing shared information and state in a class. We can define these variables with a static keyword. These only exist once and are sharable among all instances of a class. We can access static variables with the class name or an instance of the class.

24. What do you understand about MVC?

Java Interview Questions- MVC

MVC (Model View Controller) is an architectural pattern for building enterprise applications. This pattern can split an app into three types of logical components including model, view and controller. It completely separates the model component (business-specific logic) and the view component (presentation layer). The model components consist of data and its logic. The View component displays model objects in the user interface.

Related Article- Golang vs Java: What Should You Choose?

Java Interview Questions for Experienced Professionals

Senior developers might want to switch their jobs too. These Java interview questions for experienced professionals are highly useful for such aspirants. There is no age (or skill level) to stop learning. Sitting for an interview can be an intimidating process for anyone. This is why it is always a great idea to be completely ready for the round.

25. Explain lock-free programming in Java. Outline its advantages and challenges.

Thread safety is achieved in multi-threaded environments by using lock-free programming. This is done by using compare-and-swap (CAS) mechanisms and atomic operations.

Some advantages of this programming paradigm are -

  • Better scalability
  • No deadlocks
  • Better performance.
  • It also comes with certain challenges like -
  • Complicated implementation
  • Potential for ABA (Atomic-Borrow-Assign) problems
  • More memory usage

Example

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicCounterExample {

    public static void main(String[] args) {

        AtomicInteger counter = new AtomicInteger(0);

        // Thread-safe, lock-free increment
        counter.incrementAndGet();

        System.out.println("Counter value: " + counter.get());
    }
}

JMM sets the rules for the way in which Java programs interact with computer memory. This is especially useful in multi-threaded environments. The happens-before relationship works as a main part of this model.

Happens-before keeps the memory operations of one thread correctly in order with the operations in another thread. This is very important for writing correct concurrent code.

Example

public class SharedData {

    private volatile boolean flag = false;
    private int data = 0;

    public void writeData() {
        data = 42;
        flag = true;
    }

    public void readData() {
        if (flag) {
            // Guaranteed to see data = 42
            System.out.println(data);
        }
    }
}

27. What is the Java Memory Model? How does it relate to multi-threading?

Java Memory Model

The Java Memory Model is an acronym as JMM. It includes all the rules for stating the manner in which Java programs interact with computer memory, particularly in multi-threaded environments. One of the rules it states is about making all the threads see the changes made to shared data. Another rule claims that certain operations are indivisible (atomicity). These rules work for safe data sharing between threads as well as proper synchronization.

28. How is a thread-safe singleton implemented in Java?

There are many different approaches for implementing a thread-safe singleton in this programming language. Each of these approaches comes with its own set of trade-offs in terms of lazy loading, serialization behavior and thread-safety. The enum approach is usually tagged as the best one. This is because it is concise, inherently thread-safe and gives free serialization. The top four are -

  • Enum singleton.
  • Eager initialization.
  • Initialization-on-demand holder idiom.
  • Lazy initialization with double-checked locking.

29. How is a custom annotation processor designed and implemented in Java?

A custom annotation processor can be created through the implementation of the javax.annotation.processing.Processor interface. Some main steps to consider here are -

  • Defining the annotation.
  • Implement the processor logic.
  • Register the processor through the ServiceLoader mechanism.

30. What are Java agents? How can they be used for app monitoring and profiling?

Java agents are highly special utilities that have the potential to watch as well as change the way a Java program runs. They do not even need to change the original code to get this going. They can also be thought of as invisible assistants. They can do the following tasks amongst others -

  • See the happenings inside a program.
  • Make tweaks to the program's working.
  • Collect information regarding the actions of the program.
  • Track the time different parts of the program take.
  • Watch and access the way in which the program uses memory.
  • See if any part of the program is getting stuck.

31. Explain the concept of reactive programming in Java. How is it different from traditional imperative programming?

Reactive programming in relation to Java refers to a declarative programming paradigm. It is highly focused on data streams to propagate change. It is implemented most often through libraries like Project Reactor or RxJava.

It is quite different from imperative programming. This is because it emphasizes the flow of data and response to events instead of sequential execution of commands. This often leads to more responsive and scalable systems, particularly for I/O-bound applications.

32. Describe Java's Garbage Collection process. How can GC be tuned for a high-throughput and low-latency application?

Garbage Collection or GC is an automatic cleaning system. This system finds and then removes unused objects to make space in the memory. These adjustments can be made to this underlying mechanism for apps that must quickly handle lots of data without delays.

Use newer GC types (like G1GC or ZGC). They take shorter pauses between faster cleanups.

Make changes to the amount of memory Java can use.

Control the quantity of 'cleaner' threads it uses.

Example

java -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -Xmx4g YourApp

Functional interfaces can be explained in a much better way through an analogy. It could be thought of as a straightforward job description having only a single task. A chef who only needs to cook a meal is a good instance.

Lambda expressions can be understood better as quick and instant hires for these simple and uncomplicated jobs. This eliminates the need to go through the lengthy and complicated hiring process and frame up an employee contract and everything. It just tells someone the way to cook the meal and it gets done.

Example


public class LambdaExample {

    interface Chef {
        String cookMeal(String ingredient);
    }

    public static void main(String[] args) {

        // Traditional way (Anonymous Inner Class)
        Chef traditionalChef = new Chef() {
            @Override
            public String cookMeal(String ingredient) {
                return "Cooked " + ingredient;
            }
        };

        // Lambda way (Functional Interface implementation)
        Chef lambdaChef = ingredient -> "Cooked " + ingredient;

        System.out.println(lambdaChef.cookMeal("chicken"));
    }
}

34. Explain the purpose of default methods in interfaces that are introduced in Java 8.

Default methods that have been introduced in Java 8 offer default implementation of the method that's correct for it. It does so without breaking any existing code. In the past, adding a method to an existing interface would have meant having to implement it in every class using it. It was thus a massive pain point for many developers, particularly in gigantic codebases.

Example


public class DefaultMethodExample {

    interface Vehicle {

        void start();

        default void honk() {
            System.out.println("Beep beep!");
        }
    }

    static class Car implements Vehicle {

        @Override
        public void start() {
            System.out.println("Car is starting...");
        }
    }

    public static void main(String[] args) {

        Vehicle car = new Car();

        car.start();   // Abstract method implementation
        car.honk();    // Default method from interface
    }
}

35. Explain both concepts named - method overriding and method overloading. What is their relation with polymorphism?

Method overriding and method overloading are both forms of polymorphism in this programming language.

Method overriding takes place when a subclass gives a distinctive implementation for a method that is defined in its superclass. This superclass is the runtime polymorphism.

Example of Method Overriding


public class MethodOverridingExample {

    static class Animal {

        void makeSound() {
            System.out.println("Some sound");
        }
    }

    static class Dog extends Animal {

        @Override
        void makeSound() {
            System.out.println("Woof");
        }
    }

    public static void main(String[] args) {

        Animal animal = new Animal();
        Animal dog = new Dog();   // Polymorphism

        animal.makeSound();  // Output: Some sound
        dog.makeSound();     // Output: Woof
    }
}

Method overloading happens when different methods in the same class share a name but have different parameters.

Example of Method Overloading


public class MethodOverloadingExample {

    static class Calculator {

        int add(int a, int b) {
            return a + b;
        }

        double add(double a, double b) {
            return a + b;
        }
    }

    public static void main(String[] args) {

        Calculator calculator = new Calculator();

        System.out.println("Integer Addition: " + calculator.add(5, 10));
        System.out.println("Double Addition: " + calculator.add(5.5, 2.3));
    }
}

36. Point at the purpose of the synchronized keyword in Java. Outline its limitations as well.

The synchronized keyword is a potential asset when used correctly. It controls the access to a method or block of code in multithreaded environments. This will further make sure that only a single thread is able to execute the synchronized code at once.

Example


public class BankAccount {

    private int balance = 0;

    public synchronized void updateBalance(int amount) {
        balance += amount;
    }

    public int getBalance() {
        return balance;
    }

    public static void main(String[] args) throws InterruptedException {

        BankAccount account = new BankAccount();

        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                account.updateBalance(1);
            }
        };

        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("Final Balance: " + account.getBalance());
    }
}

Using this keyword comes with its own set of limitations. Overusing this keyword can cause performance issues. This is mostly because of thread contention, wherein the threads compete for resources. It may lead to deadlocks if it is not used carefully.

Read Also- 60 Best Spring Boot Interview Questions and Answers

Java Coding Interview Questions

Java is a programming language and thus, it is important to go through these top Java coding interview questions. Every developer should be ready for a practical or semi-practical round when they prepare for a face-to-face interview.

37. How are JRE, JDK and JVM different from each other?

JDK or Java Development Kit is a combination of different tools required for application development. JRE or Java Runtime Environment gives the environment where these apps run. JVM or Java Virtual Machine executes the bytecode.

38. Throw light on the concept of try-with-resources in language. In what way does it make resource management better?

Try-with-resources is basically a language construct that was introduced in Java 7. It automatically closes resources by implementing AutoCloseable. It also simplifies resource management while preventing resource leaks.

Example


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TryWithResourcesExample {

    public static void main(String[] args) {

        try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {

            // Use the resource
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

        } catch (IOException e) {

            // Handle exceptions
            System.out.println("Error reading file: " + e.getMessage());
        }

        // br is automatically closed here
    }
}

39. When is the super keyword used?

The super keyword accesses hidden fields as well as overridden methods/attributes of the parent class. This keyword is applicable in the following cases -

  • For accessing a parent class' data members when the member names of both the class and its child subclasses are the same.
  • For calling the parent class' default and parameterized constructor inside the child class.
  • For accessing parent class methods in the case the child classes override them.

Example demonstrating all 3 cases.


class Parent {

    protected int num = 1;

    Parent() {
        System.out.println("Parent class default constructor.");
    }

    Parent(String x) {
        System.out.println("Parent class parameterised constructor.");
    }

    public void foo() {
        System.out.println("Parent class foo!");
    }
}

class Child extends Parent {

    private int num = 2;

    Child() {

        // super() must always be the first statement in constructor
        // Either:
        // super();  // Calls default parent constructor

        super("Call Parent");  // Calls parameterised parent constructor

        System.out.println("Child class default Constructor");
    }

    void printNum() {
        System.out.println(num);         // Child's num
        System.out.println(super.num);  // Parent's num
    }

    @Override
    public void foo() {
        System.out.println("Child class foo!");
        super.foo();  // Calls parent class method
    }
}

public class DemoClass {

    public static void main(String[] args) {

        Child demoObject = new Child();
        demoObject.foo();

        /*
         Output:
         Parent class parameterised constructor.
         Child class default Constructor
         Child class foo!
         Parent class foo!
        */
    }
}

40. Here is a Java program. Access it to identify the output and state the reason.


public class IgmGuru {

    public static void main(String[] args) {

        final int i;

        i = 20;

        int j = i + 20;

        // This line will cause a compilation error
        i = j + 30;

        System.out.println(i + " " + j);
    }
}

This code is going to generate a compile-time error at Line 7. It will say - [error: variable i might already have been initialized]. This is simply because variable 'i' is the final variable. Final variables can only be initialized once which was already done on line 5.

41. How are Comparable and Comparator interfaces different from each other? When is each of these used?

Both Comparable and Comparator are for sorting objects. These two however serve different purposes. A Comparable is implemented in the class itself to define its natural ordering. It is mostly used when there is a clear, default way for comparing objects of that class.

Example


public class Person implements Comparable {

    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public int compareTo(Person other) {
        return this.name.compareTo(other.name);
    }
}

Comparator is a distinct class for defining custom orderings. It is preferred when many different ways for sorting objects are needed or the original class cannot be modified.

Example


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorExample {

    static class Person {

        private String name;
        private int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public int getAge() {
            return age;
        }

        public String getName() {
            return name;
        }
    }

    public static void main(String[] args) {

        List personList = new ArrayList<>();

        personList.add(new Person("John", 30));
        personList.add(new Person("Alice", 25));
        personList.add(new Person("Bob", 35));

        // Comparator using lambda expression
        Comparator ageComparator =
                (p1, p2) -> Integer.compare(p1.getAge(), p2.getAge());

        Collections.sort(personList, ageComparator);

        for (Person p : personList) {
            System.out.println(p.getName() + " - " + p.getAge());
        }
    }
}

42. What is the Observer pattern? How can it be implemented by using Java's built-in classes?

The observer pattern is to make sure that the objects are automatically notified when any object changes. It is impeccable for loose coupling in systems like event handling or GUIs. Now PropertyChangeListener is used in Java rather than the deprecated Observable. A WeatherStation class, for instance, uses PropertyChangeSupport. This automatically updates the observer in case of temperature changes.

Example


import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

public class ObserverPatternExample {

    static class WeatherStation {

        private int temperature;
        private final PropertyChangeSupport support =
                new PropertyChangeSupport(this);

        public void addObserver(PropertyChangeListener listener) {
            support.addPropertyChangeListener(listener);
        }

        public void setTemperature(int newTemperature) {
            int oldTemperature = this.temperature;
            this.temperature = newTemperature;

            support.firePropertyChange(
                    "temperature",
                    oldTemperature,
                    newTemperature
            );
        }
    }

    public static void main(String[] args) {

        WeatherStation station = new WeatherStation();

        station.addObserver(evt ->
                System.out.println("New temp: " + evt.getNewValue())
        );

        station.setTemperature(25);
    }
}

43. What is the purpose of the volatile keyword? What is its relation with the happens-before relationship?

The volatile keyword immediately makes all the changes made to a variable visible to other threads. It establishes a happens-before relationship. This means that all writes to a volatile variable are guaranteed visible to all subsequent reads having the same variable by any thread.

Example


public class FlagExample {

    private volatile boolean flag = false;

    public void setFlag() {
        flag = true;
    }

    public void checkFlag() {

        while (!flag) {
            // Busy-wait until flag becomes true
        }

        System.out.println("Flag was set!");
    }

    public static void main(String[] args) {

        FlagExample example = new FlagExample();

        Thread readerThread = new Thread(example::checkFlag);
        Thread writerThread = new Thread(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            example.setFlag();
        });

        readerThread.start();
        writerThread.start();
    }
}

44. How are && and & operators different from one another?

&& in Java is the logical AND operator that has short-circuit evaluation. & here is the bitwise AND operator that also doubles as a logical AND but still always evaluates both sides.

Example


public class LogicalOperatorExample {

    public static void main(String[] args) {

        int a = 5;
        int b = 10;
        boolean result;

        // Short-circuit AND (&&)
        result = (a > 10) && (b++ > 5);
        System.out.println("After && evaluation:");
        System.out.println("a = " + a + ", b = " + b + ", result = " + result);

        // Reset values
        a = 5;
        b = 10;

        // Non-short-circuit AND (&)
        result = (a > 10) & (b++ > 5);
        System.out.println("After & evaluation:");
        System.out.println("a = " + a + ", b = " + b + ", result = " + result);
    }
}

Output


a = 5, b = 10, result = false
a = 5, b = 11, result = false

45. How can a string be converted into an integer in this programming language?

The Integer class brings forth a parseInt() method for converting strings (with numeric value) into integers.


public class StringToIntegerExample {

    public static void main(String[] args) {

        String str = "123";

        int num = Integer.parseInt(str);

        System.out.println("Converted number: " + num);
    }
}

46. Explain the purpose of the final keyword when it is used with a variable.

The final keyword here is a modifier that is applicable to methods, classes and variables. This keyword makes it immutable or constant when it is used with a variable. PI is announced as a final variable in the below class -


public class CircleCalculator {

    private static final double PI = 3.14159;

    public double calculateArea(double radius) {
        return PI * radius * radius;
    }

    public static void main(String[] args) {

        CircleCalculator calculator = new CircleCalculator();

        double area = calculator.calculateArea(5);

        System.out.println("Area of circle: " + area);
    }
}

47. How can one iterate through a collection in Java?

A collection in Java refers to an object that amalgamates different elements into a single unit and makes it a part of the Java Collections Framework. This also stores, manipulates, communicates and retrieves aggregate data. An iterator, a for-each loop or a traditional for loop can be used for iterating through a collection.

Example showing the use of these loops.


import java.util.Arrays;
import java.util.List;

public class LoopExample {

    public static void main(String[] args) {

        // Example using for-each loop
        List fruits = Arrays.asList("Apple", "Banana", "Orange");

        for (String fruit : fruits) {
            System.out.println(fruit);
        }

        System.out.println("----");

        // Example using regular for loop
        for (int i = 0; i < fruits.size(); i++) {
            System.out.println(fruits.get(i));
        }
    }
}

48. How can you check if a number is prime as a developer?

I will check with a program as given below -


public class PrimeCheck {

    public static void main(String[] args) {

        int num = 29;
        boolean isPrime = true;

        for (int i = 2; i <= num / 2; i++) {

            if (num % i == 0) {
                isPrime = false;
                break;
            }
        }

        if (isPrime)
            System.out.println(num + " is a prime number.");
        else
            System.out.println(num + " is not a prime number.");
    }
}

49. Build a function to sort an array with the bubble sort algorithm.

Answer -


import java.util.Arrays;

public class BubbleSort {

    public static void main(String[] args) {

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

        bubbleSort(arr);

        System.out.println("Sorted array: " + Arrays.toString(arr));
    }

    public static void bubbleSort(int[] arr) {

        int n = arr.length;

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

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

50. Write a program to reverse a string.

Answer -


public class ReverseString {

    public static void main(String[] args) {

        String str = "Java";

        String reversed = new StringBuilder(str)
                                .reverse()
                                .toString();

        System.out.println("Reversed string: " + reversed);
    }
}

51. Build a program to find balanced parentheses from an expression.

Answer -


import java.util.Stack;

public class BalancedParentheses {

    public static void main(String[] args) {

        String expression = "{[()]}";

        boolean isBalanced = checkBalanced(expression);

        System.out.println("Is the expression balanced? " + isBalanced);
    }

    public static boolean checkBalanced(String expr) {

        Stack stack = new Stack<>();

        for (char ch : expr.toCharArray()) {

            if (ch == '{' || ch == '(' || ch == '[') {

                stack.push(ch);

            } else if (ch == '}' || ch == ')' || ch == ']') {

                if (stack.isEmpty())
                    return false;

                char top = stack.pop();

                if (!isMatchingPair(top, ch))
                    return false;
            }
        }

        return stack.isEmpty();
    }

    public static boolean isMatchingPair(char open, char close) {

        return (open == '{' && close == '}') ||
               (open == '(' && close == ')') ||
               (open == '[' && close == ']');
    }
}

Java Interview Questions and Answers on Latest Features

Staying updated with the latest advancements in Java is crucial for developers. Interviewers often test candidates on their awareness of recent features to gauge their commitment to continuous learning. Here are some key Java interview questions focusing on the newest additions to this programming language.

52. What are Java Sealed Classes?

Java Sealed Classes allow developers to specify which other classes can extend or implement a particular class or interface. It is especially designed to improve inheritance control. With this class, developers can address the issue of uncontrolled subclassing. This helps to mitigate the chances of unforeseen behavior and make codebases more difficult to maintain.

By restricting the inheritance hierarchy, sealed classes improve code robustness and ensure a more predictable type hierarchy. It can also improve security by limiting potential extension points to a known set of implementations. This feature is particularly useful when modeling a domain with a fixed set of subtypes.

53. How does Pattern Matching in switch simplify conditional logic?

Pattern Matching for switch statements and expressions is a significant evolution in Java programming language. It moves beyond simple constant comparisons and enables developers to match against the type and state of objects directly within case labels. This significantly simplifies complex conditional logic that previously required a series of if-else-if statements along with explicit type casting.

As a result, the code will be more readable and maintainable as the intent of the conditional branches becomes clearer and the amount of boilerplate code associated with type checking and casting is substantially reduced. This feature makes handling diverse object types within a switch construct far more elegant and less error-prone.

54. What are Java Record Classes for data objects?

Java Record Classes provide a concise syntax for creating immutable data carrier objects. By simply declaring the state components, the compiler automatically generates the canonical constructor, equals(), hashCode() and toString() methods. This drastically reduces the verbosity typically associated with creating Plain Old Java Objects (POJOs) or Data Transfer Objects (DTOs).

The inherent immutability of records promotes safer and more predictable code, especially in concurrent environments. They also streamline development by eliminating the need to write repetitive boilerplate.

55. What is the FFM API?

The Foreign Function & Memory (FFM) API in recent Java versions. It modernizes and simplifies Java's interaction with code and memory outside the Java Virtual Machine. It provides a safe and efficient mechanism to invoke native libraries (foreign functions) and to allocate and manage off-heap memory, which is not subject to JVM garbage collection.

This capability opens up new possibilities for Java applications. This enables them to interoperate with performance-critical native codebases, access hardware-specific functionalities and handle large datasets in memory more directly. It potentially leads to significant performance gains in certain scenarios.

56. What are the key recent concurrency updates beyond java.util.concurrent?

The most notable recent update in Java concurrency is the introduction of Virtual Threads (Project Loom). While the java.util.concurrent package remains a cornerstone, virtual threads offer a lightweight alternative to traditional platform threads.

Virtual threads managed by the JVM can be created and managed with significantly less overhead compared to OS-level threads. This allows developers to write highly concurrent applications using a more straightforward, blocking style of programming.

Most Frequently Asked Java Interview Questions

57. Is Java a pure object-oriented language?

This programming language does follow an object oriented approach, but only according to convenience. There are many instances of accessing variables and static methods without creating an object. It also allows some primitive (non-object) data types like int or double.

58. What do you know about the JIT compiler?

JIT compiler

JIT or Just-In-Time compiler compiles programs at runtime. This approach improves the speed and efficiency of applications by compiling bytecode to machine code. It also optimizes the process based on real-time data.

59. What Java class is used to read the user input from the console?

The Scanner class is used to user input in this programming language, as given below -


import java.util.Scanner;

public class ScannerExample {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter some text: ");
        String input = scanner.nextLine();

        System.out.println("You entered: " + input);

        scanner.close();
    }
}

60. Do you know the purpose of using class constructors in Java?

Class constructors set the initial state and ensure the usability of the objects. In other words, it initializes the objects when they are created. They have the same name as the class and do not have a return type.

61. How many types of variables are used in Java?

The following variables are used in this programming language -

  • Local variable
  • Instance variable
  • Static variable

Top 10 Java Multiple Choice Questions (MCQs)

Q1. What is the primary purpose of Java's virtual threads in 2025?

A. Managing database connections
B. Simplifying high-concurrency applications
C. Rendering HTML templates
D. Handling static file serving

Q2. Which Java 22 feature enhances concurrency management in 2025?

A. Pattern Matching
B. Structured Concurrency
C. Native Image Compilation
D. Record Classes

Q3. What is the core paradigm of Java's programming model?

A. Functional Programming
B. Object-Oriented Programming
C. Procedural Programming
D. Logic Programming

Q4. Which Java feature improves type safety in switch statements in 2025?

A. Lambda Expressions
B. Pattern Matching for Switch
C. Stream API
D. Optional Class

Q5. What is a key benefit of GraalVM in Java applications in 2025?

A. Increasing startup time
B. Compiling to native images for faster execution
C. Limiting cloud deployment
D. Disabling concurrency

Q6. Which Java framework supports reactive programming in 2025?

A. Spring Boot
B. Struts
C. JSF
D. Hibernate

Q7. What is the role of the Java Collections Framework?

A. Managing HTTP requests
B. Providing data structures like lists and maps
C. Handling database migrations
D. Rendering templates

Q8. How does Java's Project Loom enhance performance in 2025?

A. By limiting thread scalability
B. By introducing lightweight virtual threads
C. By disabling async programming
D. By managing static assets

Q9. Which tool is used for dependency management in Java projects?

A. npm
B. Maven
C. pip
D. Go Modules

Q10. What is a benefit of Java 23's pattern matching enhancements in 2025?

A. Reducing code readability
B. Simplifying complex data handling
C. Limiting type safety
D. Disabling concurrency
Also Explore: Top Java MCQs

Wrapping Up Java Interview Questions

Java developers have a very strong understanding of all the main fundamental concepts related to this particular language. The list is quite long and encompasses control structures, object-oriented programming, data types and exception handling, amongst others.

Web development technologies like JSP and Servlets are beneficial too. Debugging, critical thinking skills and problem-solving are highly valuable interpersonal skills. These Java interview questions are amongst the best for preparing well and getting the job of your dreams.

Explore Our Trending Articles -

FAQs

Q1. Are Java interview questions difficult for freshers?

For freshers, most Java interview questions focus on basics like OOP, loops, arrays and collections. With regular practice they are easy.

Q2. Are coding questions asked in Java interviews?

Yes, many Java interviews include coding questions to test your logic, problem-solving skills and understanding of Java concepts.

Q3. Which topics to focus on for a Java interview?

Focus on OOP principles, collections framework, exception handling, multithreading, JDBC and basic Java programs. These topics are frequently asked in interviews.

About the Author
Sanjay Prajapat
About the Author

Sanjay Prajapat is a Data Engineer and technology writer with expertise in Python, SQL, data visualization, and machine learning. He simplifies complex concepts into engaging content, helping beginners and professionals learn effectively while exploring emerging fields like AI, ML, and cybersecurity in today’s evolving tech landscape.

Drop Us a Query
Fields marked * are mandatory
×

Your Shopping Cart


Your shopping cart is empty.