Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
A Brief Introduction to Core Java
3.
Beginner-Level Core Java Interview Questions
3.1.
Q1. What are the data types in Java?
3.2.
Q2. What are wrapper classes?
3.3.
Q3. Are there dynamic arrays in Java?
3.4.
Q4. What is JVM?
3.5.
Q5. Why is the Java platform independent?
3.6.
Q6. What are local variables and global variables?
3.7.
Q7. What is data encapsulation?
3.8.
Q8. What is function overloading?
3.9.
Q9. What is function overriding?
3.10.
Q10. Why is the main method static in Java?
3.11.
Q11. What is the difference between the throw and throws keywords in Java?
3.12.
Q12. What do you mean by singleton class?
3.13.
Q13. Does every try block need a catch block?
3.14.
Q14. What is the usage of the super keyword in Java?
3.15.
Q15. What do you mean by final keyword?
3.16.
Q16. How is an exception handled in Java?
3.17.
Q17. How can objects in a Java class be prevented from serialisation?
3.18.
Q18. What is the difference between a constructor and a method in Java?
3.19.
Q19. Why is reflection used in Java?
3.20.
Q20. What are the types of ClassLoader in Java?
3.21.
Q21. What is a copy constructor in Java?
3.22.
Q22. What is object cloning in Java?
3.23.
Q23. Is Java a purely object-oriented language?
3.24.
Q24. What is a package in Java?
3.25.
Q25. What is coercion in Java?
3.26.
Q26. Is it possible to override a private method?
3.27.
Q27. What is the life cycle of a thread created in Java?
3.28.
Q28. What are marker interfaces in Java?
3.29.
Q29. What is a memory leak in Java?
3.30.
Q30. What is the difference between new and newInstance operators in Java?
4.
Intermediate-Level Core Java Interview Questions
4.1.
Q31. What does the "assert" statement help? 
4.2.
Q32. What is the difference between ArrayList and LinkedList? 
4.3.
Q33. What is the purpose of the hashCode() method? 
4.4.
Q34. What is the purpose of the toString() method? 
4.5.
Q35. How is encapsulation achieved in Java? 
4.6.
Q36. Explain the concept of method references.
4.7.
Q37. What are annotations in Java? 
4.8.
Q38. What is the BitSet class used for?
4.9.
Q39. What is a CyclicBarrier in Java?
4.10.
Q40. What are the JDBC statements?
4.11.
Q41. What is Java String Pool?
4.12.
Q42. What is the difference between Path and Classpath?
4.13.
Q43. What is the difference between Heap and Stack memory?
4.14.
Q44. Can we use String with a switch case?
4.15.
Q45. What are the different types of classloaders?
4.16.
Q46. What is the difference between fail-safe and fail-fast iterators in Java?
4.17.
Q47.What is a compile-time constant in Java?
4.18.
Q48. What is the difference between Map and Queue in Java? 
4.19.
Q49. What is the difference between LinkedHashMap and PriorityQueue in Java?
4.20.
Q50. What is the memory-mapped buffer in Java?
4.21.
Q51. What is the difference between notify() and notifyAll() methods?
4.22.
Q52. What are the various types of exceptions?
4.23.
Q53. What is OutOfMemoryError?
4.24.
Q54. What is the difference between == and equals()?
4.25.
Q55. How can you concatenate multiple strings in Java?
4.26.
Q56. What are the main differences between array and collection?
4.27.
Q57. What do you understand by BlockingQueue?
4.28.
Q58. What is the difference between process and thread?
4.29.
Q59. What are the advantages of multithreading?
4.30.
Q60. What is context switching?
5.
Advanced-Level Core Java Interview Questions 
5.1.
Q61. How does the JVM handle method overloading and overriding internally?
5.2.
Q62. Explain Java's Non-blocking Algorithms and how they differ from traditional blocking algorithms.
5.3.
Q63. How can you create an immutable class in Java?
5.4.
Q64. Describe the Contract of HashCode and Equals methods.
5.5.
Q65. What is Type Inference in Generics?
5.6.
Q66. Explain the inner workings of the ConcurrentHashMap.
5.7.
Q67. Describe the Java Memory Fence and its importance.
5.8.
Q68. Explain the concept of False Sharing in Java.
5.9.
Q69. How do you handle OutOfMemoryError in Java?
5.10.
Q70. Describe Escape Analysis in the context of Java optimizations.
5.11.
Q71. Explain the concept of Thread Starvation and how to prevent it.
5.12.
Q72. How does Class Data Sharing work in JVM?
5.13.
Q73. Explain Java’s TLAB (Thread-Local Allocation Buffers).
5.14.
Q74. How does the Fork/Join Framework work?
5.15.
Q75. What is the difference between Pessimistic Locking and Optimistic Locking in the context of Java's Concurrency API?
5.16.
Q76. Explain the inner workings of the Java Agent.
5.17.
Q77. Describe the uses of Java Compiler API.
5.18.
Q78. What is the Principle of Locality and how does it apply to Java?
5.19.
Q79. How does the G1 Garbage Collector work?
5.20.
Q80. Explain the concept of Polymorphic Inline Caching.
5.21.
Q81. What is the difference between a StampedLock and a ReentrantLock?
5.22.
Q82. Explain the term "Busy Spin" in multi-threading.
5.23.
Q83. How can you implement a custom ClassLoader?
5.24.
Q84. Describe the Java JIT Compiler optimizations like Loop Unrolling and Vectorization.
5.25.
Q85. Explain the use of the jstack tool.
5.26.
Q86. Describe Java's Project Loom and its impact on concurrency.
5.27.
Q87. What is a Java Decompiler, and how can it be used securely?
5.28.
Q88. What are the challenges in implementing Distributed Garbage Collection?
5.29.
Q89. Describe the impact of the JVM flags on performance tuning.
5.30.
Q90. What are Java Modules, and how do they enhance security and maintainability?
6.
Frequently Asked Questions
6.1.
What are the core Java interview questions?
6.2.
How to prepare core Java interview questions?
6.3.
What is core in Java?
6.4.
What are the most important topics of core Java?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Core Java Interview Questions and Answers (2023)

Author Rituraj Seal
0 upvote
gp-icon
Data structures & algorithms (Beginner to Intermediate)
Free guided path
13 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Interview questions for core Java

Do you want to get a job as a Java developer? Does your dream company demand Java as a skill? Well, you are at the right place. In this article, we will be discussing core java interview questions. We will cover all the aspects that will help you ace your following interview. This article will help you learn many new things about Java and brush up on your Java concepts. So get ready, as we will look into core java interview questions to prepare you for your dream job.

A Brief Introduction to Core Java

Core Java consists of basic Java with which you can create general-purpose applications. It includes primarily object-oriented concepts like abstraction, encapsulation, polymorphism and inheritance. Core Java is used to write general applications which are robust and can run on any Java-supported platform. Core Java is straightforward to understand and learn. It lays the foundation for advanced concepts in Java. Core Java is the place to start when one is thinking about learning Java. Below we have discussed core java interview questions based on their difficulty levels.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Beginner-Level Core Java Interview Questions

Some of the beginner level core java interview questions you might get asked in an interview are given below -

Q1. What are the data types in Java?

Java has two types of data types, namely, primitive and non-primitive data type. 

  • Primitive data types: This includes data types like char, boolean, byte, short, int, long, double and float. 
     
  • Non-primitive data types: This type of data type includes classes, interfaces and arrays.

Q2. What are wrapper classes?

Wrapper classes are classes of primitive data types. They are used to create objects of primitive data types and convert them back into primitive data types. They are needed when an object needs to be made if there is a need to change the arguments passed into a method.

Q3. Are there dynamic arrays in Java?

No, arrays in Java are not dynamic. In Java, you can declare the size of the array at the time of memory allocation. After the memory has been allocated, the array size can neither be decreased nor increased.

Q4. What is JVM?

JVM or Java Virtual Machine is a virtual machine that creates a runtime environment for the Java application. The JVM is a part of the Java Runtime Environment (JRE). The JVM is responsible for converting bytecode into machine code for a specific machine.

Q5. Why is the Java platform independent?

Java is platform-independent because the Java Runtime Environment uses a JVM to create an executable file. The Java code, when compiled, is first converted into a bytecode. The bytecode is platform-independent, and the JVM can convert the bytecode into the machine code of a specific machine. This makes Java platform independent.

Q6. What are local variables and global variables?

Local variables are variables which are declared within a function. This type of variable has its access scope limited to the function in which they are defined. 

Global variables are declared outside of any function. The global variables are declared in the body of a class. They can be accessed in any function and have the highest scope for a variable in a class.

Q7. What is data encapsulation?

Data encapsulation means wrapping the attributes of an object and all its related functionalities into a single unit. Data encapsulation helps in hiding data from being accessed from any part of the application. Data encapsulation helps in abstraction by only showing the necessary functionalities and data.

Q8. What is function overloading?

In Java, it is possible to have multiple functions with the same name. This is possible by having different function signatures. The number of attributes of a function and the attributes' data type define the function's signature. Function overloading helps create functions that serve the same purpose but vary in some minor areas.

public class Figure 
{
	public int area(int a, int b)
	{ 
  	int rectangleArea = a*b;
  	return rectangleArea;
	}
	public  int area(int a)
	{
  	int squareArea = a;
  	return squareArea;
	}

public static void main(String[] args )
	{
  	Figure f = new Figure();
  	System.out.println("Area of square " + f.area(5));
  	System.out.println("Area of Rectangle " + f.area(5,3));
	}
}

Output:

Output

Q9. What is function overriding?

Function overriding means re-implementing a function already defined in a parent class. Function overriding serves an essential purpose in places where a function performs a general operation. With the help of function overriding, the broad implementation of the function can be specialised for the sub-classes where the function is inherited.

Q10. Why is the main method static in Java?

The main method is static because the "static: keyword makes it a class method. By making the main method a class method, it is no more necessary to create an object of the class to call the main method.

Q11. What is the difference between the throw and throws keywords in Java?

Throw Throws
The throw keyword explicitly throws an exception inside a block of code. The throws keyword is written in the signature of a function to show that the function may throw an exception of a particular type.
The throw keyword can only throw a single exception. The throws keyword can be used to declare multiple exceptions. The exceptions are declared with the help of the throws keyword in the function syntax using commas.

Q12. What do you mean by singleton class?

A singleton class is a class which only allows the creation of a single object. A singleton class can be created by simply creating a static variable. A static variable is a variable which is shared by all objects of a class. By having a static variable, it can be known whether the object of the class has been created or not.

Q13. Does every try block need a catch block?

No, every try block does not need a catch block. The try block can be succeeded by either a catch block, a finally block, or even both. A catch block is needed for catching the exceptions raised in try block. The absence of a catch block after a try block, though syntactically correct, is not much of use practically. The finally block might be needed after try block if some critical operations like closing a file needs to be done.

Q14. What is the usage of the super keyword in Java?

The super keyword refers to an object of the parent class. The super keyword creates an object of the parent class. The super keyword can also be used to call all the functions of the parent class and all the global variables, which can be either public or protected.

Q15. What do you mean by final keyword?

The final keyword is used to create a constant. A constant also called a literal, is a variable whose value, once assigned during initialisation, cannot be changed. The final keyword can be added before the data type of any variable to make the variable a constant.

Q16. How is an exception handled in Java?

An exception in Java can be handled using a try-catch block. The error-prone code is written in a try block. The catch block can be configured to handle different types of errors which might occur. The try block can also be followed by a finally block which is always run after the execution of the try block.

Q17. How can objects in a Java class be prevented from serialisation?

Serialisation is the conversion of an object to an array. The converted array can be stored in a file and then deserialised when the object is needed. We can prevent serialisation in Java class with the help of NotSerialiazeableException. We can implement the functions needed for serialisation and add the exception in those classes. Serialisation prevention can be required when the super-class is serialisable, but we do not want the child class's object to get serialised.

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

Constructor Method
It has no return type. It always has a return type. It has a return type void when not returning anything.
It always has the same name as the class name. It can have any name of its choice.

 

Q19. Why is reflection used in Java?

Reflection is used in Java as it allows an executing Java program to examine the functions and variables in it and manipulate the program's internal working. Reflection is used in JavaBeans. JavaBean uses reflection to obtain the properties of Java components while they are being loaded.

Q20. What are the types of ClassLoader in Java?

There are three types of ClassLoaders, namely.

  • Bootstrap ClassLoader: It loads the first pure Java ClassLoader. This loader loads the JDK class files and other core classes from rt.jar. It is not a Java class. This loader is also called the Primordial ClassLoader. It loads class files from jre, lib, and rt.jar.
     
  • Extensions ClassLoader: This loader uses the parent to process the class loading request. If the loading of a class fails, it loads classes from the jre or lib or ext directory. It is implemented in the sun.misc.Launcher$ExtClassLoader in Java Virtual Machine.
     
  • System ClassLoader: This loader loads the Application type classes stored in the environment variable CLASSPATH, -cp or -classpath command line option. The System ClassLoader is a child class of Extension ClassLoader.

Q21. What is a copy constructor in Java?

A copy constructor is a constructor in which an object is created using another object. In a copy constructor, a single object whose copy we want to make is set as the argument. The copy constructor then creates a new object by simply passing the properties of the object in the argument into the original constructor of the class.

Q22. What is object cloning in Java?

Cloning is also a way to create a copy of an object in Java. By using object cloning, we make a shallow copy, whereas copy constructor can create a deep copy. The difference between a shallow copy and a deep copy is that in the case of memory-heavy data structures like arrays, the shallow copy shares the same array with the original object. The whole array is reconstructed in deep copy by coping each value individually.

Q23. Is Java a purely object-oriented language?

No, Java is not a pure object-oriented language. In Java, we have primitive data types like int, char, boolean, short, float, long, and double. For Java to be a purely object-oriented language, there should not be any non-object data type. 

Q24. What is a package in Java?

In Java, a collection of classes is called a package. Packages can be thought of as a folder containing many related Java classes. Packages can be inbuilt or user-defined. Inbuilt packages are Java.lang and Java.util, which are part of the Java programming language. User-defined packages are those which the programmer creates.

Q25. What is coercion in Java?

Coercion in Java is converting a value of one type into another. Coercion can be implicit or explicit. Implicit type conversions occur when a data type of higher precedence is converted to one of lower precedence. Implicit casting occurs automatically. Explicit type conversions are done when converting a data type of lower precedence to one of higher precedence.

Q26. Is it possible to override a private method?

If a function or variable in a parent class is private, it would be inaccessible to the child. So the child class would not be visible to the child class for it to be overridden.

Q27. What is the life cycle of a thread created in Java?

A thread undergoes multiple phases in its life cycle. The phases in the life cycle of a thread in Java are

  • New: In this phase, a thread has been created and is ready to be executed.
     
  • Active: In the active phase, the CPU executes the thread. In this phase, the actual execution of the program occurs.
     
  • Blocked: In this phase, the thread is temporarily inactive. The thread in this phase is blocked or in a waiting state.
     
  • Timed waiting: In this phase, the thread waits for a set amount. This occurs when a method calls sleep(). The thread is sent back to its active state once the time-out occurs or is set to active explicitly.
     
  • Terminated: After the thread runs, completes its job or is closed early due to some error, the thread is sent to the terminated state.

Q28. What are marker interfaces in Java?

A marker interface is empty. It does not have any functions or variables in it. A marker interface provides information about the object during runtime. It is also called a tagging interface. These days annotations are preferred over marker interfaces.

Q29. What is a memory leak in Java?

A memory leak in Java occurs when the garbage collector does not remove previously created objects. The unused object remains in the memory, causing a memory leak. Memory leak uses up space and slows down the application over time. A memory leak occurs in objects referenced in the application, preventing them from being removed. Not closing objects, as objects for input and output operations, can also cause memory leaks.

Q30. What is the difference between new and newInstance operators in Java?

The new operator creates an object of a particular known class by allocating memory. It is a static process and speedy, as it is known which class's object has to be created.

The newInstance operator is used where it needs to be known which class's object we have to create. It is used to create an object of a class dynamically. It is much slower as the JVM must find the class and check for access permissions before making the object for it.

Intermediate-Level Core Java Interview Questions

After you feel comfortable with the above questions, it is time to turn up the heat. Here are some of the intermediate level core java interview questions.

Q31. What does the "assert" statement help? 

In programming, the "assert" statement assists in validating conditions or assumptions by checking if a provided expression is true. If not, it raises an exception, commonly utilized for debugging and testing to identify unforeseen situations or errors.

Q32. What is the difference between ArrayList and LinkedList? 

ArrayList is a dynamic array-based data structure with contiguous memory, offering fast random access but slower inserts/deletes. LinkedList is a node-based data structure where elements are linked, providing efficient inserts/deletes but slower random access. ArrayList suits scenarios with frequent access, while LinkedList is better for frequent modifications.

Q33. What is the purpose of the hashCode() method? 

In Java, the hashCode() method generates a numerical value (hash code) that portrays the content of an object. It is commonly used in data structures like hash tables to locate objects efficiently. HashCode () provides a fast way to index and retrieve objects from collections by converting the object's internal state into a numerical value. It allows efficient searching, sorting, and retrieval operations on large datasets.

Q34. What is the purpose of the toString() method? 

In object-oriented programming, the toString() method transforms an object's state or data into a string representation. It enables more accessible display, debugging, and logging of object information. The method is commonly utilized when printing objects or concatenating them with strings, providing a human-readable summary of an object's content and facilitating effective communication of its properties and values.

Q35. How is encapsulation achieved in Java? 

In Java, access modifiers (private, protected, public) are used to control the visibility of class members (variables and methods) and achieve encapsulation. Private members are accessible only within the class, while protected and public members are accessible to derived classes and the outside world.

Q36. Explain the concept of method references.

Method references in programming, often used in languages like Java, Kotlin, and others, provide a concise way to refer to methods as values. They allow functions to be treated as first-class citizens and passed around without invoking them immediately. It simplifies code by replacing explicit lambda expressions with direct references to existing methods, enhancing code readability and maintainability.

Q37. What are annotations in Java? 

Annotations in Java are metadata elements that provide additional information about code elements such as classes, methods, variables, and more. They start with the "@" symbol and convey instructions or data to the compiler, runtime, or tools. Annotations aid in documentation, code organization, and behavior modification. It is used for configuration, validation, and code generation.

Q38. What is the BitSet class used for?

The BitSet class represents a fixed-size sequence of bits (binary values: 0 or 1) as a collection of boolean values. It is often used for efficient storage and manipulation of sets of flags or indicators, where each bit corresponds to a specific state. This class provides methods to set, clear, toggle, and check the status of individual bits within the sequence.

Q39. What is a CyclicBarrier in Java?

A CyclicBarrier in Java is a synchronization mechanism that allows a group of threads to wait for each other to reach a common barrier point before proceeding together. It synchronizes threads when they need to perform specific tasks in parallel, ensuring they all wait until all threads have reached the barrier before continuing their execution simultaneously.

Q40. What are the JDBC statements?

JDBC (Java Database Connectivity) statements actively interact with databases in Java applications. They encompass 'Statements' for executing straightforward SQL queries, 'PreparedStatement' for handling precompiled queries with parameters, and 'CallableStatement' for actively invoking database stored procedures. These statements actively facilitate database operations and parameter binding while assuring security and optimizing performance.

Q41. What is Java String Pool?

Java String Pool is a memory-saving technique where the JVM stores and reuses string literals to conserve memory. Identical string literals are referenced to a single memory location, reducing memory usage. It improves performance and ensures efficient memory management for frequently used strings.

Q42. What is the difference between Path and Classpath?

The environment variable "Path" designates directories wherein the operating system seeks executable files. 

In Java, the environment variable "Classpath" identifies directories and JAR files that the Java Virtual Machine (JVM) explores for loading class files while executing programs.

Q43. What is the difference between Heap and Stack memory?

Heap memory stores objects and data that must persist throughout the program, managed by the JVM's garbage collector.

Stack memory holds method call frames and local variables, managing method invocations and ensuring automatic memory deallocation when methods exit.

Q44. Can we use String with a switch case?

Yes, starting from Java 7, you can use strings in switch-case statements. This improvement lets you switch based on string values, making code more readable and concise. If you're using Java 7 or later, using strings in switch-case is a convenient feature enhancement.

Q45. What are the different types of classloaders?

Java features three primary built-in Class Loaders:

  1. The Bootstrap ClassLoader loads JDK internal classes and typically handles the loading of core classes such as rt.jar.
  2. The Extensions Class Loader, responsible for loading classes from the JDK extensions directory, is commonly found at $JAVA_HOME/lib/ext.
  3. The System Class Loader is intended to load classes from the present classpath, becoming active when a program is invoked, and can be tailored using the -cp or -classpath command-line options.

Q46. What is the difference between fail-safe and fail-fast iterators in Java?

Fail-safe and fail-fast iterators are mechanisms in Java for iterating through collections. Fail-safe iterators create copies of the collection and work on them, preventing concurrent modification exceptions. Fail-fast iterators detect modifications made during the iteration and immediately throw exceptions, ensuring data integrity but potentially causing unexpected errors.

Q47.What is a compile-time constant in Java?

In Java, a compile-time constant refers to a value determined and assigned during compilation, which remains unchanged throughout the program's execution. These constants are typically primitive or String literals and are directly substituted into the code during compilation, optimizing performance.

Q48. What is the difference between Map and Queue in Java? 

Map in Java stores key-value pairs, enabling rapid data retrieval based on keys. It doesn't allow duplicate keys. A Queue holds a collection of elements for processing in a specific order, such as FIFO (First-In-First-Out) or priority order. While a Map facilitates key-based data storage and retrieval, a Queue handles ordered element processing.

Q49. What is the difference between LinkedHashMap and PriorityQueue in Java?

LinkedHashMap maintains insertion order and maps keys to values, allowing predictable iteration. PriorityQueue arranges elements based on their priority, determined by the object's comparable or custom comparator. While LinkedHashMap emphasizes order, PriorityQueue emphasizes priority-driven retrieval.

Q50. What is the memory-mapped buffer in Java?

The memory-mapped buffer in Java is a mechanism that allows files to be mapped directly into memory. It enables more efficient data transfer between the file and memory and seamless interaction between Java programs and external data sources. It's beneficial for dealing with large files and can improve I/O performance through direct memory access.

Q51. What is the difference between notify() and notifyAll() methods?

The distinction between notify() and notifyAll() lies in their impact on threads. notify() wakes up a single waiting thread, chosen arbitrarily, while notifyAll() awakens all waiting threads. The former is more efficient when multiple threads are in similar states, whereas the latter ensures all threads can proceed.

Q52. What are the various types of exceptions?

Java encompasses two types of exceptions: checked exceptions and unchecked exceptions. Checked exceptions, like IOException, must be handled explicitly in the code. Unchecked exceptions, such as NullPointerException, don't necessitate immediate handling and can be caught during runtime. These exception types assist in identifying and addressing errors, enhancing the reliability of Java programs.

Q53. What is OutOfMemoryError?

OutOfMemoryError is a runtime exception in Java that occurs when the Java Virtual Machine (JVM) cannot allocate more memory to create new objects or store data. It's thrown when the heap space is exhausted. This error indicates that the application has consumed all available memory, leading to performance degradation or application crash.

Q54. What is the difference between == and equals()?

In Java, == compares object references to check if they refer to the same memory location. The equals() method compares the content or value of objects, and it's often overridden in classes to provide a meaningful comparison. While == checks for reference equality, equals() verifies for content equality.

Q55. How can you concatenate multiple strings in Java?

In Java, you can concatenate multiple strings using the + operator. This operator combines string values and creates a new string containing the concatenated content. The StringBuilder class is recommended for more efficient concatenation within loops or complex scenarios due to its mutable nature, reducing unnecessary memory overhead compared to repeated use of the + operator.

Read more:  Wordpress Interview Questions

Q56. What are the main differences between array and collection?

Arrays are fixed-size data structures that store elements of the same type in contiguous memory. Collections are dynamic and can hold elements of different types, providing resizable structures like lists, sets, and maps. Collections offer more flexibility in adding, removing, and manipulating elements, whereas arrays have a fixed length and require manual resizing.

Q57. What do you understand by BlockingQueue?

A BlockingQueue is a Java interface representing a thread-safe collection designed for inter-thread communication. It provides methods for adding, removing, and inspecting elements while managing synchronization between producer and consumer threads. BlockingQueue implementations handle blocking operations when the queue is complete (for adding) or empty (for removal), facilitating efficient data exchange between threads.

Q58. What is the difference between process and thread?

A process is an independent executing unit with its own memory space, while a thread is a smaller unit within a process that shares the same memory space as other threads.

Processes are isolated from each other, while threads share resources like memory, making threads more lightweight and efficient in multitasking scenarios.

Q59. What are the advantages of multithreading?

Multithreading offers enhanced resource utilization, enabling concurrent execution of tasks, thus maximizing CPU utilization. It enhances application responsiveness, particularly in GUI applications. Multithreading can boost efficiency in multi-core processors, allowing tasks to be divided and executed simultaneously. It also supports efficiently using I/O operations and facilitates complex task management, improving overall program performance.

Q60. What is context switching?

Context switching refers to the process in multitasking operating systems where the CPU switches from executing the context of one thread or process to another. It involves saving a running thread's current state, loading the next thread's saved state, and changing the execution context. It efficiently allows multiple tasks to share a single CPU core, giving the illusion of parallel execution.

Advanced-Level Core Java Interview Questions 

Finally, let's discuss some of the advanced-level core java interview questions that you might encounter in an interview.

Q61. How does the JVM handle method overloading and overriding internally?

Method overloading is resolved at compile-time, and the method signature is changed to include argument types. Method overriding is resolved at runtime, and dynamic method dispatch is used to decide which method to invoke.

Q62. Explain Java's Non-blocking Algorithms and how they differ from traditional blocking algorithms.

Non-blocking algorithms allow multiple threads to operate on shared data without using locks. This contrasts with traditional blocking algorithms, where locks are used to synchronize access.

Q63. How can you create an immutable class in Java?

To create an immutable class, make the class final, all its fields final and private, and don't provide setters. Also, ensure deep copies of objects for mutable fields.

Q64. Describe the Contract of HashCode and Equals methods.

The contract specifies that if two objects are equal according to the equals() method, they must have the same hashCode() value. However, two objects with the same hashCode() are not necessarily equal.

Q65. What is Type Inference in Generics?

Type inference is the compiler's ability to determine the type of generic classes by evaluating the constructor and methods invoked.

Q66. Explain the inner workings of the ConcurrentHashMap.

ConcurrentHashMap uses segment locking or bucket locking to allow concurrent read and updates without blocking the entire collection.

Q67. Describe the Java Memory Fence and its importance.

Memory fences are barriers that prevent the reordering of instructions, ensuring that memory operations occur in the expected order, which is crucial in multi-threaded environments.

Q68. Explain the concept of False Sharing in Java.

False sharing occurs when threads accidentally impact each other’s performance due to the layout of their data in the CPU cache, even though they are not explicitly sharing any resources.

Q69. How do you handle OutOfMemoryError in Java?

Handling OutOfMemoryError can be complex and may involve freeing up memory resources, triggering garbage collection, or gracefully shutting down the application to prevent data corruption.

Q70. Describe Escape Analysis in the context of Java optimizations.

Escape analysis is a compiler optimization technique that analyzes the scope of new objects and determines if they can be allocated on the stack instead of the heap, thus improving performance.

Q71. Explain the concept of Thread Starvation and how to prevent it.

Thread starvation occurs when a thread cannot access the CPU for an extended period. It can be prevented by using fair locking mechanisms and thread priorities.

Q72. How does Class Data Sharing work in JVM?

Class Data Sharing allows pre-loaded classes to be shared between JVM instances, reducing startup time and memory footprint.

Q73. Explain Java’s TLAB (Thread-Local Allocation Buffers).

TLABs are segments of Eden space that are exclusively used by individual threads, reducing contention during object allocation in a multi-threaded environment.

Q74. How does the Fork/Join Framework work?

The Fork/Join framework is designed for parallel execution. It works by recursively breaking down a task into smaller tasks and combining their results.

Q75. What is the difference between Pessimistic Locking and Optimistic Locking in the context of Java's Concurrency API?

Pessimistic Locking locks resources for a transaction's entire duration, while Optimistic Locking allows concurrent access but checks for conflict before commit.

Q76. Explain the inner workings of the Java Agent.

Java Agents are tools for instrumentation, which can modify bytecode at load time or runtime, enabling advanced profiling or monitoring functionalities.

Q77. Describe the uses of Java Compiler API.

The Java Compiler API allows programs to be dynamically compiled and loaded during runtime, offering possibilities for developing IDEs, hot-reloading functionalities, and more.

Q78. What is the Principle of Locality and how does it apply to Java?

The Principle of Locality refers to the tendency of a processor to access the same set of memory locations repetitively. Understanding this can help in optimizing Java programs for better cache utilization.

Q79. How does the G1 Garbage Collector work?

G1 Garbage Collector works by dividing the heap into regions and prioritizing the collection of regions with more garbage, aiming for high throughput and low latency.

Q80. Explain the concept of Polymorphic Inline Caching.

Polymorphic Inline Caching is an optimization technique to improve dynamic method dispatch by remembering the last method called for a particular call site.

Q81. What is the difference between a StampedLock and a ReentrantLock?

StampedLock provides better performance through optimistic locking, while ReentrantLock is a more traditional, pessimistic locking mechanism.

Q82. Explain the term "Busy Spin" in multi-threading.

Busy Spin is a technique where a thread repeatedly checks a condition rather than waiting to be notified, usually to achieve lower latency at the cost of higher CPU usage.

Q83. How can you implement a custom ClassLoader?

A custom ClassLoader can be implemented by subclassing ClassLoader and overriding methods like findClass, loadClass, and defineClass.

Q84. Describe the Java JIT Compiler optimizations like Loop Unrolling and Vectorization.

Loop Unrolling reduces the overhead of loop control code by increasing the number of operations in the loop body. Vectorization allows operations to be performed on multiple data points simultaneously.

Q85. Explain the use of the jstack tool.

jstack is a Java utility for displaying stack traces of Java threads, useful for debugging and performance analysis.

Q86. Describe Java's Project Loom and its impact on concurrency.

Project Loom aims to simplify concurrency in Java by introducing lightweight, user-mode threads known as fibers, making it easier to handle high levels of concurrency.

Q87. What is a Java Decompiler, and how can it be used securely?

A Java Decompiler converts bytecode back into source code. It's crucial to use decompilers responsibly and in accordance with software licenses.

Q88. What are the challenges in implementing Distributed Garbage Collection?

Distributed Garbage Collection deals with the complexities of identifying and collecting garbage objects across multiple JVMs, making it a challenge in terms of performance and resource management.

Q89. Describe the impact of the JVM flags on performance tuning.

JVM flags like -Xms, -Xmx, -XX:+UseG1GC, etc., allow tuning the JVM behavior, impacting aspects like heap size, garbage collection strategy, and performance.

Q90. What are Java Modules, and how do they enhance security and maintainability?

Java Modules, introduced in Java 9, allow the packaging of Java classes and resources into modular JAR files, enhancing security by providing strong encapsulation and improving maintainability by resolving dependencies explicitly.

Frequently Asked Questions

What are the core Java interview questions?

Core Java interview questions cover OOP, data types, control structures, exceptions, threading, collections, and more. They assess a candidate's fundamental Java knowledge and problem-solving skills.

How to prepare core Java interview questions?

Study fundamental concepts like OOP, data structures, and multithreading to prepare for core Java interview questions. Practice coding, review common questions, and understand real-world applications.

What is core in Java?

In Java, a core usually refers to a CPU core, a processing unit within a computer's CPU that can execute tasks independently, enabling parallel processing.

What are the most important topics of core Java?

Core Java's crucial topics include OOP concepts, data types, control structures, exception handling, classes and objects, inheritance, polymorphism, collections, and multithreading.

Conclusion

In this article, we have discussed core java interview questions you might encounter in an interview. The questions are also sorted by their difficulty. After reading this article, we hope you will feel confident about your following interview.

Some of the articles you might find useful:

Previous article
Stack Memory and Heap Memory in Java
Next article
Java garbage collection: What is it and how does it work?
Guided path
Free
gridgp-icon
Data structures & algorithms (Beginner to Intermediate)
13 chapters
109+ Problems
gp-badge
Earn badges and level up
Live masterclass