Top Core Java Interview Questions and Answers for Freshers

May 6, 2025

Table of contents

Starting your journey into the world of Java development can feel overwhelming, especially when you're preparing for your first technical interview. With the right preparation and understanding, you can confidently navigate this challenge.

The demand for Java developers in India is substantial; projections indicate that over 18.7 million Java developer jobs will be created globally between 2024 and 2026. Whether you’ve just graduated or are transitioning into software development, having a solid understanding of core Java fundamentals is crucial. Interviewers often use technical rounds to test your grasp of object-oriented principles, syntax, and problem-solving abilities. 

The following article explores the top Java interview questions for freshers and sample answers, offering key insights to excel in a Java interview.

Overview of Java

Java is one of the tech industry's most powerful and widely adopted programming languages today. It is platform-independent, object-oriented, and designed to have minimal implementation dependencies, making it ideal for web, mobile, and enterprise applications. As a fresher, you must understand its core concepts like classes, objects, inheritance, polymorphism, memory management, and exception handling. Interviewers often focus on these foundational areas, so reviewing Java interview questions for freshers is important. 

Here are a few core topics typically covered in Java interviews for freshers:

  • Differences between Java and other languages like C++
  • JVM, JRE, and JDK differences
  • Concepts like static vs. instance variables and methods
  • Exception handling, constructors, and method overloading/overriding
  • Multithreading basics and memory management (Heap vs. Stack)
  • Key differences between interfaces and abstract classes

This preparation helps you answer technical questions and boosts your confidence in explaining concepts clearly and logically. Understanding the “why” behind each principle gives you an edge when communicating your interview thought process.

Need help preparing for your Java interview? Topmate offers personalized career guidance to help you excel in your job search and land your dream Java developer job.

Now that we understand Java, let’s examine some basic Java interview questions for freshers.

Basic Java Interview Questions for Freshers

Mastering the basics is essential to succeeding in your first Java interview. In this section, we’ll discuss common Java interview questions for freshers that assess foundational knowledge.

1. Why is Java a platform-independent language?

Why it’s important: Understanding platform independence highlights one of Java’s most powerful features — the ability to run the same program on multiple operating systems without modification.

Sample Answer

Java is platform-independent because it follows the "write once, run anywhere" principle (WORA). This is achieved through the Java Virtual Machine (JVM), which allows Java bytecode (compiled Java code) to be interpreted and executed on any system with a compatible JVM installed. Rather than compiling into machine code specific to one operating system, Java code is compiled into an intermediate form — bytecode — which the JVM interprets.

  • Java source code is compiled into bytecode by the Java Compiler. This bytecode is an intermediate, platform-independent code that the Java Compiler generates from the source code.
  • Bytecode is then executed by the JVM on any platform, whether it's Windows, Linux, or macOS. The JVM interprets the bytecode and translates it into machine-specific instructions, enabling the same Java program to run on any operating system without needing to modify the code. 

This abstraction layer provided by the JVM gives Java its platform independence.

2. Why is Java not a pure object-oriented language?

Why it’s important: This question assesses your understanding of object-oriented programming (OOP) and where Java stands.

Sample Answer

Java is not considered an object-oriented language because it supports primitive data types (such as int, float, and boolean) that are not objects. Everything in a purely object-oriented language must be treated as objects, including control structures and data types. Java does follow the major OOP principles (inheritance, encapsulation, polymorphism, and abstraction), but including primitives for performance reasons makes it not "pure."

  • Java includes eight primitive types that are not objects.
  • Operations on primitives do not use method calls.
  • Wrapper classes (like Integer and Double) can be used to treat primitives as objects when needed.

3. What is the difference between Heap and Stack memory in Java? How does Java use them?

Why it’s important: This question tests your understanding of memory management, which is essential for performance and avoiding memory leaks.

Sample Answer

In Java, memory is divided into Stack and Heap areas. Stack memory is used for thread execution and contains method-specific values like local variables and function calls. Heap memory, on the other hand, stores objects and class instances that require dynamic memory allocation.

  • Stack memory:
    • Stores local variables and method calls
    • Follows LIFO (Last In, First Out) structure
    • Faster and automatically deallocated when the method finishes
  • Heap memory:
    • Stores objects and JRE classes
    • Shared among all threads
    • Requires garbage collection for memory cleanup

Java uses both types of memory efficiently to balance performance and flexibility.

4. How is Java different from C++? 

Why it's important: This question assesses knowledge of both languages and helps interviewers evaluate if you understand memory management, syntax, and object-oriented differences.

Sample Answer

Java and C++ are both object-oriented, but they differ significantly:

  • Java has built-in garbage collection, automatically managing memory, while C++ requires manual memory management, increasing the risk of memory leaks. Java’s approach simplifies memory handling, making it safer compared to C++.
  • Java does not support multiple inheritance through classes but uses interfaces to achieve similar functionality, while C++ allows multiple inheritance directly with classes. This avoids the complexities of multiple inheritance in Java.
  • Java is platform-independent due to bytecode executed by the JVM, while C++ compiles into machine-specific code, making it platform-dependent. Java's approach allows it to run across various platforms without modification.
  • Java syntax is simpler and does not include features like pointers and operator overloading. These differences make Java more suitable for cross-platform and secure applications, while C++ gives more control over system resources.

5. Pointers are used in C/C++. Why does Java not make use of pointers? 

Why it's important: It highlights Java's security and memory management philosophy by avoiding direct memory access.

Sample Answer

Java does not support explicit pointers to enhance security and simplicity. Pointers allow direct memory access, leading to potential vulnerabilities, memory leaks, and crashes. Java manages memory through references and the JVM, ensuring automatic garbage collection. By eliminating pointers, Java reduces the chance of buffer overflows and makes the language more secure and robust for developers.

6. What do you understand about an instance variable and a local variable? 

Why it's important: It clarifies understanding of variable scopes and lifecycles, which are essential for managing memory and logic.

Sample Answer

  • Instance variables are declared inside a class but outside any methods, constructors, or blocks. They are tied to an object of the class and have a longer lifecycle, meaning they exist for as long as the object does. Instance variables can be accessed and modified by any method within the class, and their values persist across method calls. 
  • On the other hand, local variables are declared inside methods, constructors, or blocks of code, and they are only accessible within that specific method or block. They are created when the method is called and destroyed once the method finishes execution. Local variables are temporary and cannot be accessed outside the method, making their scope limited and their life cycle short. 

Instance variables have a broader scope and longer lifecycle, while local variables are temporary and limited to the function's execution.

7. Tell me something about the JIT compiler. 

Why it's important: This question demonstrates your understanding of Java's performance optimisation techniques.

Sample Answer

The JIT (Just-In-Time) compiler is part of the Java Runtime Environment (JRE) that improves performance. It compiles bytecode into native machine code at runtime, allowing it to run faster. The JIT compiler only compiles code that is frequently executed, optimizing it for speed. This dynamic compilation boosts Java programs' efficiency while retaining portability benefits.

Want to stand out in your interview? Practice your HR and technical interview responses with Topmate’s professionals. Book a mock interview today to receive expert feedback and improve your answers.

8. Is it possible that the 'finally' block will not be executed? If yes, then list the case. 

Why it's important: This question helps validate your understanding of exception handling edge cases.

Sample Answer

Although the finally block typically executes regardless of whether an exception occurs, there are rare situations where it might not be executed:

  • Suppose the JVM crashes or is forcibly shut down: In such cases. In that case, the Java Virtual Machine (JVM) might terminate unexpectedly before it can complete any pending operations, including executing the finally block.
  • If System.exit() is called before the ‘finally’ block: The System.exit() method forces the JVM to terminate immediately, which prevents the execution of the finally block since the program halts before reaching that part of the code.
  • If the thread executing it is killed: If the thread running the code is interrupted or terminated unexpectedly (e.g., by a Thread.stop() call), the finally block may not be executed, as the thread may not reach that point in the code.

These cases are uncommon but critical in scenarios requiring guaranteed cleanup operations.

9. When can you use the super keyword?

Why it's important: Understanding super is crucial for mastering inheritance. It allows a subclass to access members of its parent class, which is foundational in object-oriented programming.

Sample Answer

The super keyword is used in Java to refer to the immediate parent class of the current object. It is commonly used in three scenarios:

  • ​​To call the parent class constructor from the subclass constructor. When a subclass constructor is invoked, it implicitly calls the parent class constructor. The super() keyword can be used explicitly to call a specific parent constructor, ensuring proper initialization of the parent class.
  • To access a method from the parent class that has been overridden in the child class. If a subclass overrides a method from the parent class, the super keyword can be used to call the parent class version of the method, allowing access to the original functionality even if it has been overridden.
  • To access parent class variables that are hidden by child class variables. If a subclass declares a variable with the same name as a parent class variable, the super keyword can be used to reference the parent class variable, ensuring the correct variable is accessed instead of the hidden one in the subclass.

This helps maintain a clear hierarchy and avoid redundancy when extending functionality.

10. Why is the main method static in Java?

Why it's important: It tests understanding of Java’s program entry point and the role of static methods in class-level execution.

Sample Answer

The main method in Java is declared static because it needs to be accessible before any class object is created. The Java Virtual Machine (JVM) calls this method directly when launching an application, and static methods can be called without creating class instances. Declaring it static ensures no dependency on object instantiation, which is vital for initializing the program.

11. What is the difference between static methods, static variables, and static classes in Java?

Why it's important: This checks whether you understand how static context works and its implications for memory and access.

Sample Answer

  • Static methods belong to the class, not instances, and can be called without creating an object. They are associated with the class itself, not any particular instance. This means they can be invoked directly using the class name without needing to instantiate the class.
  • Static variables are shared across all instances of a class and maintain a single copy in memory. Unlike instance variables, static variables are common to all objects of the class, meaning they share the same memory location. Any change to a static variable is reflected across all class instances.
  • Static classes (nested) are defined within another class and can only access static members of the outer class. A static nested class is defined within the scope of an outer class but does not require an instance of the outer class to be used. It can only access static members and methods of the outer class, as it cannot access instance-specific data.

Using static is useful for memory efficiency and when shared behaviour or data is required across instances.

12. What is a ClassLoader?

Why it's important: This tests a deeper understanding of Java’s runtime environment and how classes are dynamically loaded.

Sample Answer

A ClassLoader in Java is a part of the JVM that is responsible for loading class files during runtime. It loads classes into memory when they are referenced for the first time. The three main types of class loaders are:

  • Bootstrap ClassLoader: The Bootstrap ClassLoader is responsible for loading the essential classes provided by the Java Runtime Environment (JRE), such as java.lang.*, java.util.*, and other fundamental libraries. 
  • Extension ClassLoader: The Extension ClassLoader loads classes from the ext directory (or equivalent) in the JRE installation, which contains extension libraries that provide additional functionality to the core Java platform. This class loader extends the bootstrap loader and is responsible for any classes not part of the core JRE.
  • Application ClassLoader: The Application ClassLoader is the default class loader for loading application-level classes. It loads classes from the classpath, which is typically specified by the -cp or CLASSPATH environment variable, and includes user-defined classes and libraries for the application. 

ClassLoaders provide flexibility in loading custom or dynamic classes during execution.

13. What part of memory – Stack or Heap – is cleaned in the garbage collection?

Why it's important: This question checks whether you can distinguish between Stack and Heap memory management and how Java uses each.

Sample Answer

Garbage collection primarily targets the Heap memory, where objects and class instances are stored. The Stack is used for method calls and local variables and is automatically cleaned up after a method completes execution. Since the Heap holds objects that may persist beyond method calls, the JVM uses the garbage collector to free up Heap memory from objects no longer referenced.

14. What are shallow copy and deep copy in Java?

Why it's important: Understanding shallow and deep copy concepts in Java is crucial for efficiently managing object references and memory. Knowing the difference helps in ensuring that the object copies behave as expected.

Sample Answer

In Java, a shallow copy of an object means that the object's fields are copied directly. Still, any references to other objects (like arrays or objects within the object) remain pointing to the original objects. If the original or copied object is modified, this can lead to unintended side effects.

On the other hand, a deep copy creates a new object and recursively copies all the fields, including those referenced by the original object, ensuring that changes to the copied object don’t affect the original. In a deep copy, even nested objects are cloned.

Example:

  • Shallow Copy: In Java, the clone() method or Object.assign() creates a shallow copy.
  • Deep Copy: This requires manually copying all nested objects or using serialisation methods, such as writing the object to a byte stream and reading it back.

By understanding these two types of copies, developers can better control object cloning and avoid issues with unintended reference sharing.

15. What happens if the static modifier is not included in the main method signature in Java?

Why it's important: This question tests your understanding of Java runtime processes and the importance of the static modifier. 

Sample Answer

In Java, the main method is the entry point of any standalone application. It is the first method that the JVM looks for when running a program. If the static modifier is not included in the main method, the JVM will try to invoke it on an object, but since no object has been created yet, the method call will fail. Without static, the JVM cannot find a valid way to call the method, which leads to a runtime error.

For example, if the main method lacks the static keyword, the JVM will attempt to create an object of the class to call the main method. However, because no instance of the class exists at that point, it will throw an error, usually a NoSuchMethodError. To avoid this issue and allow the JVM to run the program, the static modifier is essential in the method signature of the main method.

16. Do the keywords ‘final,’ ‘finally,’ and ‘finalize’ have the same function?

Why it's important: Understanding the difference between these keywords is crucial for writing efficient and error-free code, particularly when managing object immutability, exception handling, and garbage collection.

Sample Answer

The final, finally, and finalize keywords in Java are often misunderstood, but they serve very different functions:

  • final: The ‘final’ keyword is used to declare constants, prevent method overriding, and prevent inheritance. For example, when a variable is declared as final, its value cannot be changed once it is assigned. Similarly, a final method cannot be overridden, and a final class cannot be subclassed.
  • finally: The ‘finally’ keyword is used in exception handling to define a block of code that is always executed, regardless of whether an exception is thrown or caught. It ensures that important cleanup tasks (such as closing files or releasing resources) are performed after the ‘try’ block, even if an exception occurs.
  • finalize: The ‘finalize’ method is a method in the Object class called by the garbage collector before an object is garbage collected. It is used to perform cleanup operations on objects, such as releasing resources that are not automatically garbage-collected.

Each of these keywords serves a unique purpose in Java, and understanding their differences is vital for effective programming.

Let Topmate’s professionals review your resume and LinkedIn profile to make sure they highlight your true potential. Schedule a free resume review today and receive tailored feedback to help you stand out!

Once you’ve covered the basics, let’s move to the intermediate level, where we delve into slightly more advanced Java concepts.

Intermediate Java Interview Questions for Freshers

Here, we explore Java interview questions for freshers that test your understanding of intermediate concepts and coding practices.

1. Apart from security, what are the reasons behind making strings immutable in Java?

Why it’s important: Understanding string immutability is crucial because strings are widely used in Java, including in class names, file paths, and keys in collections.

Sample Answer

String immutability in Java ensures that its value cannot be changed once a string object is created. This characteristic provides multiple advantages:

  • Thread safety: Multiple threads can share the same string object without synchronisation, improving performance.
  • Memory efficiency: The JVM uses a string pool where immutable strings can be reused instead of creating new ones.
  • Safe for use in hash-based collections: Since the string’s hashcode doesn’t change, it ensures consistency when used in hashmaps and hashsets. This behaviour helps Java maintain performance and reliability in large applications.

2. What is a singleton class in Java? How to implement a singleton class?

Why it’s important: Singleton classes are commonly used for shared resources, configuration settings, and centralized control logic.

Sample Answer

A singleton class in Java allows only one instance to exist simultaneously. This design pattern ensures that a class has a single instance and provides a global point of access to it.

  • It is useful in logging, where it helps track application behavior and errors for debugging and analysis. It also aids in caching, optimizing performance by storing frequently accessed data, and managing connection pools, ensuring efficient reuse of database connections for improved application performance.
  • It ensures controlled access to a shared resource. The singleton pattern avoids redundant object creation and manages memory effectively by limiting instantiation.

3. How would you differentiate between a String, StringBuffer, and a StringBuilder?

Why it’s important: These three classes are fundamental for handling text, and choosing the right one impacts performance and thread safety.

Sample Answer

  • String: A String is immutable, meaning its value cannot be changed after creation. Any modification results in the creation of a new object, which can lead to performance issues with frequent changes.
  • StringBuffer: Its methods are synchronized, making it mutable and thread-safe. This ensures safe use in multithreaded environments but can reduce performance due to synchronization overhead.
  • StringBuilder: StringBuilder is mutable and not synchronized, making it faster than StringBuffer in single-threaded applications but unsafe for multithreading.

Choosing between them depends on whether thread-safety or performance is the priority. In multithreaded environments, StringBuffer is preferred; otherwise, StringBuilder offers better speed.

4. Using relevant properties, highlight the differences between interfaces and abstract classes. 

Why it’s important: Interfaces and abstract classes are used for abstraction. Knowing when and how to use them effectively is crucial for sound object-oriented design.

Sample Answer

  • Interfaces can only contain abstract methods and constants (until Java 8) and support multiple inheritance. From Java 8, they can also have default and static methods. Interfaces allow a class to implement multiple interfaces, enabling flexible design.
  • Abstract classes can include both abstract methods and concrete methods, along with instance variables. They provide shared functionality and allow partial implementation, which subclasses can extend. This enables code reuse while still allowing for specific customizations in subclasses.

An abstract class is used when classes share a common base implementation, while interfaces define contracts across unrelated courses.

5. What is a Comparator in Java?

Why it’s important: Comparators are essential for sorting and ordering custom objects in collections.

Sample Answer

A Comparator in Java is an interface used to define custom sorting logic for objects. It provides a compare() method, allowing you to compare two objects based on user-defined criteria. This enables sorting collections according to attributes like name or age, without altering the objects themselves.

With a Comparator, you can create multiple sorting orders for the same collection, such as sorting by different fields. This flexibility allows for reusable and adaptable sorting logic. It can be applied in methods like Collections.sort() or Stream.sorted() to sort collections in Java efficiently.

6. In Java, static and private method overriding is possible. Comment on the statement.

Why it’s important: This question explores your understanding of method binding and inheritance in Java.

Sample Answer

In Java, static and private methods are not subject to runtime polymorphism because they are resolved at compile-time. This means that static methods are bound to the class and private methods cannot be inherited, making them immune to polymorphic behaviour.

  • Static methods are resolved at compile-time and belong to the class, not to any instance, which means they are not subject to dynamic method dispatch. They are fixed in the code, and what may seem like overriding is actually method hiding, as a subclass can define a method with the same name but doesn't truly override the original.
  • Private methods are inaccessible outside the class they are defined in, are not inherited by subclasses, and cannot be overridden. As a result, any attempt to define a method with the same name in a subclass does not result in method overriding but instead in method hiding, which can lead to confusion if not understood correctly.

7. What makes a HashSet different from a TreeSet?

Why it’s important: Understanding the underlying differences helps choose the right set implementation for performance or ordering needs.

Sample Answer

  • HashSet does not maintain any order of elements and is backed by a hash table, which allows for constant-time performance for operations like add, remove, and contains. As a result, HashSet is typically faster for these operations compared to other collections that maintain order.
  • TreeSet, on the other hand, maintains elements in a sorted order, which is guaranteed by its underlying tree structure, usually a Red-Black tree. This sorting feature makes TreeSet slower for operations like add and remove compared to HashSet, but it provides efficient retrieval of elements in sorted order.

HashSet is ideal for quick lookups, while TreeSet is useful when sorted data is needed.

8. Why is the character array preferred over String for storing confidential information?

Why it’s important: This highlights Java’s memory management and security principles when handling sensitive data.

Sample Answer

  • Strings are immutable and stored in the String pool, meaning they are not easily removed from memory after use due to their persistence for reuse across the application. This makes them less efficient for managing sensitive information like passwords since they remain in memory longer than needed.
  • Character arrays, unlike Strings, can be explicitly cleared by overwriting their contents, giving developers control over when data is removed. This feature ensures that the information does not remain in memory longer than necessary, making character arrays a safer choice for storing sensitive data such as passwords.

Unsure about your career path or how to elevate your Java skills? Topmate offers personalized career mentorship to help you navigate your professional journey. 

9. What do we get in the JDK file?

Why it’s important: Understanding the Java Development Kit's (JDK) components is essential for developing, debugging, and deploying Java applications effectively.

Sample Answer

The JDK (Java Development Kit) is a full-featured software development environment for building Java applications. It contains the following:

  • JRE (Java Runtime Environment) used to run Java programs. The JRE provides the necessary environment to execute Java bytecode, ensuring that the program runs consistently across various platforms.
  • Compiler (Javac) to convert Java code into bytecode. This compilation step transforms human-readable code into an intermediate form that can be executed by the Java Virtual Machine (JVM) on any platform.
  • Java tools like Javadoc, Java, and Jdb are used for documentation, decompilation, and debugging. Javadoc generates documentation for code, Java decompiles bytecode for inspection, and Jdb is a debugger for diagnosing and fixing issues in Java applications.

The JDK is every Java developer's core toolkit for writing and testing programs.

10. What are the differences between JVM, JRE, and JDK in Java?

Why it’s important: These three components are foundational in the Java ecosystem, and understanding their differences helps set up and run Java applications correctly.

Sample Answer

  • JVM (Java Virtual Machine): Executes Java bytecode. It is platform-dependent and handles memory, security, and garbage collection.
  • JRE (Java Runtime Environment): Provides libraries and the JVM to run Java applications but doesn’t include development tools.
  • JDK (Java Development Kit): A superset of JRE; it includes the compiler, debugger, and other tools necessary for Java development. 

Understanding their roles ensures you choose the correct setup depending on whether you want to develop or only run Java applications.

11. What are the differences between HashMap and Hashtable in Java?

Why it’s important: These are commonly used data structures. Knowing their differences helps make better choices for performance and thread safety.

Sample Answer

  • HashMap is not synchronized, which means it is not thread-safe but offers faster performance in single-threaded environments. It allows one null key and multiple null values, making it flexible for use in scenarios where such values are needed.
  • Hashtable, however, is synchronized, ensuring thread safety when multiple threads access the map concurrently. However, the synchronization mechanism can make it slower than HashMap in multithreaded environments, as it introduces overhead in locking during method execution.

HashMap is part of the Java Collections Framework, while Hashtable is a legacy class. In multithreaded environments, use ConcurrentHashMap instead of Hashtable for better performance.

12. What is the importance of reflection in Java?

Why it’s important: Reflection is a powerful feature that allows runtime access to classes, methods, and fields essential in frameworks, tools, and libraries.

Sample Answer

Reflection in Java enables inspecting and manipulating classes, interfaces, constructors, and methods at runtime.

  • It is commonly used in frameworks like Spring and Hibernate for dependency injection and configuration, where classes are configured dynamically based on annotations or external configuration files. This allows these frameworks to be highly flexible and adaptive to various application needs.
  • Reflection also allows the creation of objects, the invocation of methods, and dynamic access to fields, offering powerful capabilities for building flexible and reusable code. However, despite its versatility, it should be used carefully due to the potential risks related to performance degradation and security vulnerabilities, such as bypassing access control checks.

13. What are the different ways of using threads?

Why it’s important: Multithreading is vital for performance in modern applications. Understanding thread implementation helps build responsive and efficient programs.

Sample Answer

Threads in Java can be implemented in two main ways:

  • The first way is by extending the Thread class, where you override the run() method to define the thread's behaviour. This approach restricts you from extending any other class, as Java allows only single inheritance.
  • The second way is by implementing the Runnable interface, which allows you to define the thread behaviour in the run() method. This method provides more flexibility, as it enables you to extend other classes in addition to implementing the Runnable interface.

Additionally, Executors and thread pools from the java.util.concurrent package provides more scalable and controlled thread management in large applications.

14. What are the different types of Thread priorities in Java? And what is the default priority of a thread assigned by JVM?

Why it’s important: Thread priorities help the JVM decide the order in which threads should be executed, especially in resource-limited environments.

Sample Answer

Java assigns thread priorities from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY), with 5 (NORM_PRIORITY) as the default. These priorities provide the thread scheduler with hints about the relative importance of threads, influencing the order in which they are executed.

  • Higher-priority threads may be executed before lower-priority ones, allowing more critical tasks to get CPU time faster. However, the actual execution order depends on the thread scheduler and system resources, which can vary based on the operating system.
  • JVM behavior is OS-dependent, meaning that thread priorities may not always be respected in the exact order specified by the program. This can lead to unpredictable thread execution, particularly on platforms where thread scheduling is managed differently.

Understanding thread priority helps optimize concurrent task execution by ensuring that critical tasks receive more CPU time when needed. By adjusting priorities appropriately, you can fine-tune the performance of multithreaded applications, improving overall efficiency.

15. What is the difference between the ‘throw’ and ‘throws’ keywords in Java?

Why it’s important: These keywords are key to exception handling in Java. Knowing their use improves code reliability and readability.

Sample Answer

  • ‘throw’ is used to explicitly throw an exception from a method or block of code, allowing you to create and throw custom exceptions when specific conditions are met. This is typically used for manual error handling, giving developers control over when exceptions should be triggered during program execution.
  • ‘throws’ is used in the method signature to declare exceptions that the method might throw, alerting the calling method that it needs to handle those exceptions. It serves as a warning, ensuring that the calling code either catches the exceptions or propagates them further up the call stack.

For example, if a method might cause an exception, ‘throws’ alerts the calling method to handle it, whereas ‘throw’ is used to trigger the exception during execution. This distinction helps in separating exception declaration and handling logic, making the code more readable and maintainable.

16. What do you understand about Object cloning, and how do you achieve it in Java?

Why it's important: Object cloning is a process in Java where you create an exact copy of an object. It's important because sometimes you may need to duplicate an object to avoid modifying the original object, or you may need a new instance with the same state.

Sample Answer

Object cloning in Java is creating an exact copy of an object. Java provides the Cloneable interface to mark a class whose objects can be cloned. The clone() method, which is defined in the Object class, is used to create a copy. However, this method only performs a shallow copy by default, meaning only the object references are copied, not the objects they refer to. To achieve deep cloning, one must manually clone the objects referenced within the object.

17. Can we make the main() thread a daemon thread?

Why it's important: Understanding whether the main() thread can be a daemon thread is important because the main() thread is the entry point to your application, and making it a daemon thread would have implications for your program’s execution lifecycle.

Sample Answer

No, the main() thread cannot be made a daemon thread in Java. The main() thread is the primary thread that begins execution when a Java application is launched, and it cannot be set as a daemon because the JVM will exit only when all user threads (non-daemon threads) are completed. Daemon threads are background threads that can be terminated automatically when the main program finishes execution. The main() thread must be completed before the JVM shuts down, so it cannot be a daemon thread.

Having covered the intermediate questions, let's proceed to the advanced level, where you’ll tackle more complex Java topics.

Advanced Java Interview Questions for Freshers

If you aim to showcase your expertise, advanced Java interview questions for freshers will push your knowledge further, focusing on complex Java concepts and problem-solving skills. Advanced questions test your ability to solve complex problems and your knowledge of advanced features in Java. They cover areas like JVM internals, design patterns, and memory management, which are essential for a deeper understanding of the language and its applications.

1. Although inheritance is a popular OOPs concept, it is less advantageous than composition. Explain.

Why it’s important: This question tests your understanding of software design principles and object-oriented programming, especially regarding code flexibility and maintainability.

Sample Answer

Inheritance allows one class to acquire the properties and behaviours of another. While powerful, it creates a tight coupling between parent and child classes. Changes in the parent class can inadvertently affect child classes. On the other hand, composition promotes reusability by allowing objects to contain other objects. It provides greater flexibility, enabling behaviour changes at runtime without altering existing code. In practice:

  • Inheritance is an “is-a” relationship, meaning that a subclass is a type of its superclass and inherits its properties and behaviours. It establishes a hierarchy between classes, where a derived class can use or override methods from the base class.
  • Composition is a “has-a” relationship, indicating that a class contains references to objects of other classes to build its functionality. This approach promotes greater flexibility and modularity, as components can be easily replaced or extended without altering the class structure.

Developers often prefer composition to keep systems loosely coupled and easier to manage.

2. What is the difference between the ‘>>’ and ‘>>>’ operators in Java?

Why it’s important: This question evaluates your understanding of bitwise operations and how Java handles signed versus unsigned values.

Sample Answer

  • The >> operator is the signed right shift operator. It preserves the sign bit (leftmost bit), meaning negative numbers remain negative after the shift. This operator is useful when working with signed integers and maintaining their sign during bit shifts.
  • The >>> operator is the unsigned right shift operator. It fills the leftmost bits with zeros regardless of the original sign, treating the number as positive. This is commonly used when you want to perform bit shifts without considering the sign of the number.

This distinction is critical when manipulating binary data, especially when working with large datasets or optimizing performance at the bit level.

3. What are composition and aggregation? State the difference.

Why it’s important: Understanding object relationships is essential in designing scalable systems. This question tests your grasp of class collaboration.

Sample Answer

Composition and aggregation both represent "has-a" relationships between objects, indicating one object is part of another. However, they differ in the strength of their relationships and the lifecycle of the objects involved.

  • Composition implies ownership, meaning if the parent object is destroyed, so is the child object. For example, if a car is destroyed, its engine, which is a part of the car, is also destroyed.
  • Aggregation implies a weaker relationship, where the child object can exist independently of the parent. For example, a university can exist without its students, as students can attend different universities or leave at any time.

Objects are tightly bound in composition, whereas aggregation allows more flexibility and modularity in code.

4. How is the creation of a String using new() different from that of a literal?

Why it’s important: This question checks your understanding of memory management and string handling in Java.

Sample Answer

  • A string literal (e.g., "Hello") stores the string in the string pool, which is a special memory area for string literals. If another string with the same content exists in the pool, it reuses the existing one to save memory and improve performance.
  • Using the new String("Hello") creates a new object in the heap memory, even if the string exists in the pool. This ensures that a fresh object is created in the heap, which can lead to unnecessary memory usage compared to string literals.

Thus, literals are memory-efficient, while new always creates a fresh object.

5. How is the new operator different from the newInstance() method in Java?

Why it’s important: This question assesses your knowledge of object creation and reflective programming in Java.

Sample Answer

  • The new operator creates an object at compile time and is type-safe, ensuring that the object is of the correct type. This operator requires you to know the class at compile time, providing compile-time checks to prevent errors.
  • newInstance() is part of reflection and allows dynamic class instantiating at runtime, offering flexibility when you do not know the class type in advance. While it is less type-safe than the new operator, it is valuable for frameworks and libraries where class types are determined dynamically at runtime.

6. Is exceeding the memory limit possible in a program despite having a garbage collector?

Why it’s important: This question tests your understanding of memory management and JVM limitations.

Sample Answer

Yes, it’s possible. The garbage collector reclaims memory from unused objects. Still, memory will eventually run out if memory is allocated faster than it can be reclaimed or if references to unused objects are held. Examples include memory leaks caused by static references or improper object handling in loops. Java will then throw an OutOfMemoryError.

7. Why is synchronization necessary? Explain with the help of a relevant example.

Why it’s important: This question evaluates your understanding of concurrency and thread safety.

Sample Answer

Synchronization ensures that only one thread accesses a resource at a time. In multithreading environments, multiple threads can access shared resources simultaneously, leading to data inconsistency. For example, when two threads update a shared counter without synchronization, the final value may be incorrect. Synchronizing access to the counter ensures accurate results.

Looking to make a strong impression in your Java interview? Topmate can connect you with professionals from leading companies like Google, Microsoft, and Amazon for referrals. Build your referral network and improve your chances of landing your dream job.

8. Define System.out.println().

Why it’s important: This tests your fundamental understanding of Java I/O and class relationships.

Sample Answer

  • System is a final class in java.lang, containing useful fields and methods that provide system-level functionality. It cannot be subclassed, ensuring that its core features remain consistent across all Java programs.
  • out is a static field of System, an instance of PrintStream that is used to output data to the console. It is commonly used for printing text or data to the standard output stream in most Java applications.
  • println() is a method in PrintStream used to print output followed by a newline. This method ensures that the cursor moves to the next line after printing, making it useful for displaying formatted output.

Together, System.out.println() outputs data to the console during program execution.

9. Can you explain the Java thread lifecycle?

Why it’s important: Understanding the thread lifecycle helps you manage multithreading efficiently, ensuring programs are stable and responsive under concurrent operations.

Sample Answer

A Java thread goes through multiple states, each representing a stage in its lifecycle. 

  • New: The thread has been created but has not yet been started, meaning it is initialized and waiting for the start() method to be called. This state indicates that the thread is not yet eligible to run.
  • Runnable: The thread is eligible to run and is waiting for CPU time to be assigned. Although the thread is ready, it might not be executing immediately due to the thread scheduler’s allocation of resources.
  • Running: The thread is actively executing, meaning the CPU has allocated time for it to perform its task. This is the state where the thread is performing its intended function.
  • Blocked/Waiting: The thread is paused, either because it is waiting for a monitor lock to proceed or is waiting for another thread to notify it. During this state, the thread is temporarily inactive but not terminated.
  • Terminated: The thread has completed its execution or has been stopped. In this state, the thread has finished its task, and its resources are cleaned up by the JVM, indicating the thread's lifecycle has ended.

Managing transitions between these states helps developers avoid deadlocks and race conditions.

10. What could be the trade-off between the usage of an unordered array versus the usage of an ordered array?

Why it’s important: This tests your understanding of data structure efficiency and when to use which type based on performance needs.

Sample Answer

An unordered array allows for fast insertions (simply appending to the end) but makes searching less efficient due to linear scanning. An ordered array supports faster searches (using binary search), but insertions are slower because elements must be shifted to maintain order.

  • Use unordered arrays when insertions are frequent, as they allow for faster insertion times without the need to maintain order. However, search performance will be slower since you may need to scan through the entire array to find an element.
  • Use ordered arrays when fast searches are essential, as the elements are arranged in a sorted sequence, allowing for efficient search operations like binary search. However, insertions can be slower because maintaining order requires shifting elements to the correct position.

11. Is it possible to import the same class or package twice in Java, and what happens to it during runtime?

Why it’s important: This question evaluates your knowledge of Java’s import mechanism and compile-time behaviour.

Sample Answer

Java allows importing the same class or package multiple times, but the compiler ignores duplicates, ensuring that only one import statement is processed. This behaviour does not affect runtime performance or functionality, as duplicate imports are simply discarded during compilation.

Import statements are purely a compile-time feature that improve readability by allowing shorthand references to classes or packages. They do not exist in the compiled .class file, which means they have no impact on the final runtime behavior of the program.

12. In case a package has sub-packages, will it suffice to import only the main package?

Why it’s important: This checks your familiarity with Java’s package and import hierarchy.

Sample Answer

No, importing a parent package (e.g., com.myMainPackage.) does not import its sub-packages like com.myMainPackage.mySubPackage.. Each sub-package must be explicitly imported if its classes are to be used, ensuring that only the required classes are included in the code.

This design ensures clarity and prevents unnecessary class loading from unrelated packages, optimizing performance. It also promotes better organization and avoids importing unused classes, reducing potential conflicts in larger projects.

13. Will the ‘finally’ block be executed if the code System.exit(0) is written at the end of the try block?

Why it’s important: This question tests your understanding of the exception handling flow and behaviour of the JVM.

Sample Answer

No, the ‘finally’ block will not be executed if System.exit(0) is called. This is because System.exit(0) forcibly terminates the JVM, bypassing the normal execution path, including any remaining code, such as finally. It’s one of the rare cases where it is finally skipped, as the program exits immediately.

14. What do you understand about marker interfaces in Java?

Why it’s important: This tests your knowledge of interface design patterns and how metadata is used in Java.

Sample Answer

A marker interface is an interface with no methods or constants. It’s used to "mark" a class to indicate some property or capability. Examples include Serializable and Cloneable. The JVM or frameworks check for the presence of these interfaces to enable certain functionalities, like allowing an object to be serialised.

15. Explain the term “Double Brace Initialisation” in Java.

Why it’s important: This checks your awareness of Java syntactic sugar and how objects can be instantiated with initial values.

Sample Answer

Double Brace Initialisation is a technique for initializing collections with values in a compact form. It involves creating an anonymous inner class and an instance initialiser block. While it makes code look concise, it has drawbacks, like creating extra classes and holding a reference to the enclosing object, which can cause memory leaks. Thus, it’s clever but not widely recommended for production code.

16. What are the different categories of Java design patterns?

Why it's important: Understanding the categories of design patterns helps developers choose the most suitable solution for a problem, improving code maintainability and scalability and reducing unnecessary complexity.

Sample Answer

Java design patterns are typically categorised into three main types:

  • Creational Patterns: These patterns deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. Examples include the Singleton, Factory Method, and Abstract Factory patterns.
  • Structural Patterns: These patterns focus on how classes and objects are composed to form larger structures, such as the Adapter, Composite, and Decorator patterns.
  • Behavioural Patterns: These patterns focus on communication between objects and how responsibilities are assigned. Examples include the Observer, Strategy, and Command patterns. 

Understanding and using these patterns can simplify complex problems by applying standard, tried-and-tested solutions.

17. What is the best way to inject dependency?

Why it's important: Dependency injection is used to achieve Inversion of Control (IoC), making code more modular, testable, and maintainable. Understanding the best method of dependency injection is crucial to building clean, scalable, and loosely coupled applications.

Sample Answer

The best way to inject dependencies in Java is by using Constructor Injection. In this approach, dependencies are provided to the class via its constructor. Constructor injection ensures the object is always initialized with the required dependencies, making the class immutable and easier to test. This method also helps manage the object’s lifecycle and enforces that all the necessary dependencies are supplied when the object is created. While other forms, like setter injection, are possible, constructor injection is considered more robust and is widely recommended in frameworks like Spring.

Now, let’s examine next step in your preparation: gathering valuable resources that can help you practice and solidify your Core Java knowledge.

Resources for Core Java Interview Preparation

Preparing for a Core Java interview requires both theoretical knowledge and practical experience. The following resources will help you ace your Core Java interview and improve your coding skills:

1. Java Coding Interview Questions with Solutions

This resource provides answers to common Java coding interview questions. Practice these questions to enhance your understanding and problem-solving skills for interviews. Check out the detailed solutions here.

2. 100 Java Interview Questions with Answers

Gain a competitive edge with a list of 100 Java interview questions, covering a wide range of topics. Each question includes a detailed answer to ensure you understand the solutions. Browse the questions here.

3. Java Interview Programs

Enhance your programming skills with a comprehensive collection of Java interview programs. Solve real-world coding problems and get hands-on experience to improve your coding abilities. Explore the Java interview programs here.

4. Thread Dump Collection in SAP Java System

Learn about thread dumps and troubleshooting techniques in the SAP Java system. This resource helps you understand thread management, an essential skill for Java developers. Learn more about thread dumps here.

5. Advanced JavaScript Interview Questions

Test your JavaScript expertise with advanced-level questions that delve into deeper topics and coding challenges. These questions will push your limits and prepare you for the most complex interview scenarios. Check out the advanced JavaScript interview questions here.

6. Machine Coding Questions – Frontend (React JS)

Enhance your frontend skills by practicing machine coding questions specifically focused on ReactJS. These questions test your ability to build efficient and scalable applications. Explore the machine coding questions here.

7. Back-End: Node.js, Express & MongoDB: 160+ Q&A

Prepare for full-stack development interviews by mastering back-end technologies like Node.js, Express, and MongoDB. This resource includes 160+ questions to enhance your back-end development skills. Start learning back-end development here.

8. React JS Mock Interview Round – Meta Company

Prepare for your ReactJS interview with real-time mock interview practice, conducted by industry professionals from Meta. This mock interview simulates real-world interview conditions, providing valuable feedback. Prepare with a mock interview here.

The above-given Topmate resources will equip you with the knowledge and practice you need to excel in your Core Java interview. Whether you need to practice coding, enhance your understanding of Java-related topics, or test your skills with real-world scenarios, these materials will guide you towards success.

Conclusion

Preparing for Java interviews as a fresher goes beyond memorizing answers—it requires a deep understanding of core concepts and their real-world applications. To succeed, grasp fundamental Java principles like object-oriented concepts, data structures, and algorithms. 

Consistent practice with Java interview questions for freshers will help reinforce your knowledge, while reviewing challenging topics ensures you're fully prepared. Problem-solving exercises and mock interviews will further sharpen your skills and build confidence.

Book a mock interview with Topmate today! We offer expert feedback, career guidance, resume reviews, mentorship, and job referrals to boost your chances.

Contact us for any questions or guidance! We're here to support your success.

Related Blogs

©2025 Topmate