Home Icon Home Computer Science List Of 50 Core Java Interview Questions With Answers (2022)

List Of 50 Core Java Interview Questions With Answers (2022)

Shreeya Thakur
Schedule Icon 0 min read
List Of 50 Core Java Interview Questions With Answers (2022)
Schedule Icon 0 min read

Table of content: 

  • Difference between core Java and advanced Java
  • Important Core Java Questions
  • Tips for Preparing for Core Java
expand

Did you know that Java is the third most popular programming language in the world? The programming language is used by developers to develop applications for mobile phones, computers, data centers, game consoles, etc.

Java is a general-purpose, high-level, object-oriented programming language. Developed by Sun Microsystems which is a subsidiary of Oracle, Java is a secure, high-performance, and multithreaded programming language. Because it has a runtime environment and API, Java can also be considered a platform. When we speak of core Java, the word 'core' describes the fundamental concepts of Java programming. Hence, beginners need to start with core Java and gradually proceed towards the advanced level of Java. 

Because of its important applications, questions from Java are frequently asked in software developer or IT-related job interviews. In this article, we shall cover the top 50 core Java interview questions to help you prepare well. But first, let's understand the difference between core Java and advanced Java.  

Difference between core Java and advanced Java

Core Java Advanced Java
Covers the basic concepts of the Java programming language. Covers the advanced topics and concepts of the Java programming language.
Used for computing or desktop applications. Used for enterprise applications.
Covers some topics like data types, OOP, operators, exception handling, threading, etc. Covers some topics like web services, database connectivity, JSP, Servlets, EJB, etc.
It is the first step, to begin with, Java. It is the next step after completing the Core Java.
Based on single-tier architecture. It is thus known as a stand-alone application. Based on two-tier architecture. It requires a strong client-server architecture. 
It comes under Java SE. It comes under Java EE or J2EE.

Important Core Java Questions

Q1. Differentiate between C++ and Java

C++ Java
Platform-dependent. Platform-independent.
Mainly used for system programming. Mainly used for application programming. 
Designed for systems and applications programming. It is an extension of C.  Designed as a support network computing with a goal of being easy to use and accessible to a broader audience.
Supports multiple inheritance. Doesn't support multiple inheritance through class. 
Supports operator overloading. Doesn't support operator overloading.
Compiled and run using the compiler which converts source code into machine code.   Java uses compiler and interpreter both. 
Supports both call by value and call by reference. Supports call by value only. 
Supports structures and unions. Supports structures and unions.
Doesn't have built-in support for threads.  Has built-in thread support.
Supports virtual keywords. Has no virtual keyword. 
Creates a new inheritance tree always. Uses a single inheritance tree always because all classes are the child of an object class in Java. 
Interactive with hardware. Not so interactive with hardware.

Q2. What is an abstract class in Java?

A class that is declared using the 'abstract' keyword is known as an abstract class. It is a restricted class that cannot be used to create objects. Hence, for accessing an abstract class, it must be inherited from another class.


          abstract class Animal {
 public abstract void animalSound();
 public void sleep() {
 System.out.println("Zzz");
 }
}
        

From the above class, it is not possible to create an object of the Animal class. 

Q3. What are the features of Java Programming language?

Following are the features in Java Programming Language:

  • Easy to learn: Java is a simple language. The syntax of Java is based on C++ which makes it easier. 
  • Object-Oriented Language: Java has an object-oriented paradigm allowing us to maintain our code as a combination of different type of objects. This incorporates both data and behavior.
  • Platform Independent: Java is a platform-independent programming language and comes with its platform on which its code is executed. It doesn't need operating system to be executed.
  • Secured: Java is secured as it doesn't make use of explicit pointers and utilizes the concept of ByteCode and Exception handling.
  • Portable: Java supports the read-once-write-anywhere approach making it executable on any machine.
  • High Performance: Java is faster than other traditional interpreted programming languages. However, it is slower than a compiled language such as C++
  • Multithreaded: Java uses multi threads wherein we can write programs that deal with many tasks at once.
  • Robust: Java uses strong memory management, automatic garbage collection, exception handling, etc. making it a strong programming language.
  • Distributed: Java is distributed which can make it access files by calling the methods from any machine on the internet.
  • Dynamic: Java is a dynamic language and thus classes in Java are loaded on demand. It even supports functions from its native languages such as C and C++.

Q4. What do you understand by Java virtual machine?

It is a virtual machine that enables the computer to run the Java program. Abbreviated as JVM, Java Virtual Machine acts like a run-time engine that calls the main method present in the Java code. The Java code is compiled by JVM to be a Bytecode that is machine independent and close to the native code.

Q5. How many types of memory areas are allocated by JVM?

JVM or Java Virtual machine has the following memory areas: 

  • Class(Method) Area: Stores per-class structures such as the runtime constant pool, field, method data, code for methods, etc.
  • Heap: Runtime data area in which the memory is allocated to the objects
  • Stack: Holds local variables and partial results, and plays a part in method invocation and return. 
  • Program Counter Register: Contains the address of the current Java Virtual Machine instruction being executed.
  • Native Method Stack: Contains all the native methods used in the application.

Q6. What is the difference between Heap and Stack Memory in Java? 

Stack Memory Heap Memory
Used to store items that have a short life like local variables or a reference variable of objects Allocated to store objects and JRE classes.
Always reserved in a LIFO (last in first out) order Uses dynamic allocation where there is no fixed pattern for allocating and de-allocating blocks in memory
Can be used to increase stack memory size by using the JVM parameter -XSS. Can increase or decrease heap memory size by using JVM option -Xms and -Xmx
Variables are visible only to the owner thread It is visible to all threads

Q7. What is a JIT compiler?

JIT or Just-In-Time Compiler is actually a translator that is used to improve the performance by compiling parts of the bytecode having similar functionality at one time. This reduces the amount of time needed for compilation. JIT translates the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU. 

Q8. What is the platform?

A platform is defined as the hardware or software environment wherein a part of the software is executed. Platforms can be of 2 types: software-based and hardware-based. Java provides a software-based platform.

Q9. Differentiate between the Java platform and other platforms?

Following are the differences between the Java platform and other platforms.

  • Java is a software-based platform while other platforms may be hardware platforms or software-based platforms.
  • Java is executed on top of other hardware platforms. However, other platforms can only have the hardware components.

Q10. What is a classloader in Java?

Classloader is a subsystem of JVM that can be used to load class files. Any Java program is first loaded by the classloader. There are three built-in Java classloader types:

  1. Bootstrap ClassLoader: First classloader which is the superclass of Extension classloader. It loads the rt.jar file that contains all class files of Java Standard Edition like java. lang package classes, java.net package classes, and java.util package classes, java.io package classes, java.sql package classes, etc.
  2. Extension ClassLoader: Child classloader of Bootstrap and parent classloader of System classloader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
  3. System/Application ClassLoader: Child classloader of Extension classloader that loads the class files from the classpath. 

Q11. Explain overloading and overriding in Java?

  • Overloading is when a Java program has more than one method with the same name in a single class but the arguments are different. 
  • Overriding happens in inheritance. For example: when two methods have the same name and same signature, one is parent class and another is child class. Here the method of child class is overridden to make sure that is any changes are done to the parent class, the child class also gets changed accordingly. 

Q12. What are the various access specifiers in Java?

Access specifiers are the keywords used to define the access scope of the method, class, or variable in Java. There are four access specifiers:

  • Public: Can be accessed by any class or method.
  • Protected: Can be accessed by the class of the same package, by the sub-class of this class, or within the same class.
  • Default: Are accessible within the package only. All the variables, classes, and methods are of default scope.
  • Private:  Class, methods, or variables defined as private can be accessed within the class only.

Q13. Differentiate between Array list and vector in Java.

ArrayList Vector
Not synchronized. Synchronized.
Is faster as it is non-synchronized. Slow as it is thread-safe.
Does not define the increment size. Defines the increment size.
Can only use an iterator for traversing. Can use both enumeration and iterator for traversing.

Q14. What is a class in Java?

Class is a set of objects which share common characteristics and attributes. It is a group of variables of different data types and group of methods. Class is not a real-world entity and is just a prototype from which objects are created. It doesn't occupy memory. A class in java may contain the following:
• Data member
• Method
• Constructor
• Nested class and
• Interface

Syntax:


          Syntax to declare a class:

access_modifier class
{
 data member;
 method;
 constructor;
 nested class;
 interface;
}
        

On the other hand, an object is a member or an instance of a Java class. Every object has an identity, behavior, and state. An object can be created using a new keyword. When an instance of the class or object is created, memory is allocated for the newly created object and also returns the reference of that object to that memory. The syntax for creating an object is:

ClassName object = new ClassName();

Q15. What is the difference between JDK, JRE and JVM?

JDK JRE JVM
Stands for Java Development Kit. Stands for Java Runtime Environment. Stands for Java Virtual Machine.
It is a software development kit that develops applications in Java. Along with JRE, the JDK also consists of various development tools (Java Debugger, JavaDoc, compilers, etc.) It is an implementation of JVM and is a type of software package that provides class libraries of Java, JVM, and various other components for running Java applications.  It is a platform-independent abstract machine that has three notions in the form of specifications. It describes the requirement of JVM implementation.
Assists in executing codes. It primarily functions in development. Creates an environment for the execution of code. Providing all of the implementations to the JRE.
Platform-dependent.  Platform-dependent. Platform-independent. 

Q16. Define the term 'Double Brace Initialization' in Java

Double Brace Initialization is a term that refers to the combination of two independent processes. It has two braces. The first brace creates an anonymous inner class. The second brace is an initialization block. When used together, it is known as Double Brace Initialization. 

Advantages:

  • Has lesser lines of code compared to the native way of creation and initialization.
  • The code is more readable.
  • Creation and Initialization are done in the same expression.

Disadvantages:

  • It is obscure.
  • Creates an extra class every time.
  • Holds a hidden reference to the enclosing instance that may cause memory leaks.

Q17. What are the advantages of packages in Java?

Packages in Java are used to group related classes. Following are the advantages of packages in Java.

  • Avoid name clashes.
  • Provides easy access control.
  • Makes it easier to locate the related classes.

Q18. Explain object-oriented paradigm

The object-oriented paradigm is a programming paradigm that aims to incorporate the advantages of modularity and reusability. It is based on objects having data and methods defined in the class to which it belongs. Following are the features of the object-oriented paradigm:

  • Focus on data with methods to operate upon the data of the object.
  • Follows the bottom-up approach in program design.
  • Includes concepts like encapsulation and abstraction which hides the complexities from the user and highlights only the functionality.
  • Examples of the object-oriented paradigm are C++, Python, C#, etc.

Q19. What is the major difference between an object-oriented programming language and an object-based programming language?

The major difference between an object-oriented programming language and an object-based programming language is as follows: 

Object-oriented Programming Language Object-based Programming Language
All features of object-oriented programming are supported. Characteristics of object-oriented programming such as inheritance and polymorphism are not supported.
Don't have a built-in object. Example: C++. Have built-in objects. Example: JavaScript has a window object.
Java is an example of object-oriented programing language which supports creating and inheriting one class from another. VB is an example of object-based language.

Q20. Why is Java called as platform independent?

Java is called platform independent because its byte codes can run on any system irrespective of its underlying operating system. Hence, it is not dependent of any platform. 

Q21. Define wrapper classes in Java

Wrapper classes convert the Java primitives into reference types (objects). These are known as wrapper classes because they 'wrap' the primitive data types (int, boolean, etc.) into an object of that class. Hence, the wrapper class in Java provides a mechanism to convert primitive into object and object into primitive.

Q22. Is Java 100% Object-oriented?

No, Java is not 100% object-oriented. This is because it makes use of primitive data types such as boolean, byte, char, int, float, double, long, and short which are not considered objects

Q23. Explain constructors in Java

Constructor refers to a block of code that is used to initialize an object. It must have the same name as that of the class. It has no return type and it is automatically called when an object is created. 

Types of Constructor

  • Default Constructor: A default constructor is the one that does not take any inputs. These are no argument constructors which will be created by default if no other constructor is defined by the user. Its main purpose is to initialize the instance variables with the default values. 
  • Parameterized Constructor: The parameterized constructor is the constructor which is capable of initializing the instance variables with the provided values. In other words, parameterized constructors take arguments. 

Q24. Define 'static' keyword in Java. 

The purpose of adding static before any entity is to make that entity a class entity. Hence, adding static before a method or a variable makes it a class method or class variable respectively. Any static member can be accessed before any objects of its class are created and without reference to any object. The static keyword is used mainly for memory management and can be applied with variables, methods, blocks, and nested classes.


          // Making a function as static
static void func()
{}
// Making a variable as static
static int var;
        

Q25. Explain the Static Void methods in Java

Speaking of the static void methods, these are static methods that do not return anything. Static methods can be called directly by class names. On the other hand, a void method is a method that returns nothing but one needs to create a class object to call such a method. 

Q26. What is a static Variable in Java?

As explained above, if a variable is declared static, it is known as a static variable. It can be used to refer to the common property of all objects that is not unique for each object. For example, the company name of employees, school names of students, etc. Static variable gets memory only once in the class area at the time of class loading.

Q27. What are static blocks? 

When the static keyword is attached to a block of code, the block is called a static block. Static blocks in Java are executed automatically when the class is loaded in memory. These are executed before the main() method and are executed only once as the class file is loaded to memory.

Q28. Define abstraction in Object-oriented programming.

Abstraction in object-oriented programming is defined as hiding unnecessary details from the user so as to focus on the essential details or functionality. It increases efficiency and thus reduces complexity. In Java, abstraction can be achieved using abstract classes and methods. 

Q29. What is an abstract method? 

When a method is declared using the abstract keyword within an abstract class and does not have a definition is called an abstract method. An abstract method is also called subclass responsibility as it doesn't have the implementation in the superclass. This means that a subclass must override it to provide the method definition.

The syntax for abstract method:

abstract return_type method_name( [ argument-list ] );

Q30. What are string objects in Java? 

Strings are data types used in Java programs. They come with special support from the Java libraries. While these are described as arrays in many programming languages, strings are defined as objects called string objects in Java. String objects in Java are immutable and thus can't be modified after being initialized.

Q31. What is a Try-Catch Block in Java?

The try-catch block in Java is used to handle exceptions and prevents the abnormal termination of the program. The syntax of this block is as follows: 


try{ // code } catch(exception) { // code }

While the try block includes the code that might generate an exception, the catch block includes the code that is executed when an exception occurs inside the try block.

Q32. Explain object cloning in Java

In Java, object cloning is a method to create an exact copy of an object. The clone() method of Object class is used to clone an object. (By default, no class in Java supports cloning but there is an interface in Java called java.lang.Cloneable, which helps to make a duplicate copy of the object. Here, java.lang.Cloneable is implemented to avoid runtime exceptions).

The clone() method saves processing time for creating the exact copy of an object. Generally, the clone() method of an object creates a new instance of the same class, and copies all the fields to the new instance, and returns it. This is called a shallow copy.

It is important to note that if the original object has any references to other objects as fields, only the references of those objects are copied into the clone object. Copy of those objects is not created.

Q33. What is a method signature in Java?

The method signature is part of the method declaration in Java. It is a combination of the method name and the parameter list. Here is an example:


          public class MethodSignature {
 public int add(int a, int b){
 int c = a+b;
 return c;
 }
 public static void main(String args[]){
 MethodSignature obj = new MethodSignature();
 int result = obj.add(40, 30);
 System.out.println(result);
 }
}
        

Output: 70

Q34. What is method overloading in Java? 

If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. It happens when there are two methods with the same name but different arguments. Overloaded methods are differentiated based on the number and type of parameter passed as arguments to the methods. Following is an example of method overloading:


          void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
        

In the above example, func() is overloaded. 

Q35. Difference between static and non-static methods in Java. 

Static Method Non-Static Method
Can access only static members.  Can access both static as well as non-static members.
Utilizes compile-time binding or early binding. Uses run time binding or dynamic binding.
Cannot be overridden by compile time binding. Can be overridden by dynamic binding.
Take less space and memory allocation Occupy more space. 
Declared using a static keyword. Doesn't require any special keyword.

Q36. How to create a thread in Java? 

A thread can be created in two ways in Java: 

1. By extending the thread class. The example is as follows:


          class Multi extends Thread{

public void run(){

System.out.println("thread is running...");

}

public static void main(String args[]){

Multi t1=new Multi();

t1.start();

}

}
        

2. By implementing a runnable interface. The example is as follows:


          class Multi3 implements Runnable{

public void run(){

System.out.println("thread is running...");

}

public static void main(String args[]){

Multi3 m1=new Multi3();

Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)

t1.start();

}

}
        

Q37. What is the difference between equals() and == in Java?

Equals() method is defined in the object class in Java. It is used for checking the equality of two objects defined by business logic.

“==” is called the equality operator in Java. It is a binary operator used to compare primitives and objects. 

Q38. What is a compile-time error in Java?

When a problem stops the program execution in Java, it is known as an error. Errors can occur because of syntax issues while others occur at the time of program execution. The errors with syntax issues are known as compile-time errors. Examples of compile-time errors are missing parenthesis or a missing semicolon. The other type of programming error that occurs at runtime is called runtime error.

Types of compile-time programming errors:

  • Syntactical Errors
  • Semantic Errors
  • Lexical Errors

Q39. What is a throwable class in Java? 

A throwable class in Java is a class that is the superclass of all exceptions and errors that can occur in a Java program. A throwable class extends the object class. Actually, a throwable class is itself a subclass of the superclass of all Java classes and object classes. Some important methods present in throwable class are:

  • toString(): Returns information about an exception in the form of a string.
  • getMessage(): Returns a detailed message of an exception that has recurred.
  • printStackTrace(): Prints the stack trace of an exception.
  • getClause(): Returns the exception that caused the occurrence of the current exception.

Q40. Define constructor chaining in Java. 

Constructor chaining is defined as the ability to call a constructor inside another constructor. For constructor chaining in Java, the keyword 'this' is used to call a constructor from within another constructor in the same class. Constructor chaining makes a program more readable and easy to understand for the reader. 

Q41. How to achieve thread safety in Java? 

Thread safety is a process used in Java to make programs safe for use in a multithreaded environment. It happens when a thread is working on an object while preventing another thread from working on the same object. A thread-safe code handles shared data structures in a way that ensures that all threads behave well and fulfill their specifications without any unintended interaction.

Q42. What is a Boiler Plate code in Java?

By definition, boilerplate code refers to a pile of code blocks with a fixed pattern. It can be widely applied to various program modules. The name comes from the newspaper printing industry where repetitive text was used in various contexts and pages. Boilerplate codes can be helpful for developers to make more standardized formats, improve the quality of codes, and increase the coding speed.

Here is a typical boilerplate code:


          try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {

 String line;

 while (Objects.nonNull(line = reader.readLine())) {

 // process a line
 ...
 }
} catch (IOException e) {

 String message = String.format("read file(%s) exception", fileName);

 log.error(message, e);

 throw new ExampleException(message, e);
}
        

Q43. What is a super keyword in Java?

A super keyword refers to the superclass objects or the parent objects. It is thus a reference variable. The super keyword can be used to:

  • refer immediate parent class instance variable.
  • invoke immediate parent class method.
  • invoke immediate parent class constructor.

Q44. What is a derived class?

In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes. A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).

Q45. Name the types of classes in Java

There are seven types of classes in Java:

  1. Static Class
  2. Final Class
  3. Abstract Class
  4. Concrete Class
  5. Singleton Class
  6. POJO Class
  7. Inner Class

Q46. What are the different types of inheritance in Java?

Inheritance in Java is a mechanism through which one object acquires all the properties and behaviors of a parent object. The original class is known as the base class/parent class while the new class is called the derived class or the child class. 

The types of inheritance in Java are:

  • Single Inheritance
  • Multi-level Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

Q47. Explain thread lifecycle in Java.

A thread in Java is the path or direction that is taken up while a program is being executed. At any instance, a thread always exists in any one of the following states.

  1. NEW: The newly created thread that has not yet started the execution
  2. RUNNABLE/ACTIVE: Running or ready for execution but it's waiting for resource allocation
  3. BLOCKED or WAITING: Inactive for a particular span of time. 
  4. TIMED WAITING: Waiting for some other thread to perform a specific action for a specified period.
  5. TERMINATED: Has completed its execution.

Q48. Name the types of Loops on Java

loops are used to repeat a block of code. There are three kinds of loops which are – the for loop, the while loop, and the do-while loop. All these three loop constructs of Java execute a set of repeated statements as long as a specified condition remains true. This particular condition is generally known as loop control.

Q49. Define Serialization, Deserialization and Transient Keyword In Java

In Java, serialization is a mechanism of writing the state of an object into a byte stream (sequence of bytes). On the other hand, deserialization is the process of converting a stream of bytes back into a copy of the original object. Taking these two into view, a transient keyword is used to indicate that a field should not be serialized. This means that if at the time of serialization, the coder does not want to save the value of a particular variable in the file, they can make use of the transient keyword. Hence when Java Virtual Machine ( the abstract machine that executes Java programming) comes across a transient keyword, it ignores the original value of the variable and saves the default value of that variable data type.

Q50. What are the features of Java 8?

Java 8 version of Java was released by Oracle in March 2014. It is considered a revolutionary software development platform. Some interesting features of Java 8 are: 

  • Lambda expression: Adds functional processing capability to Java.
  • Date Time API: Improved date time API.
  • Default and Static methods in Interfaces.
  • Nashorn, JavaScript Engine: A Java-based engine to execute JavaScript code.
  • Method references: Referencing functions by their names instead of invoking them directly.
  • New tools: New compiler tools and utilities to figure out dependencies.
  • Stream API: New stream API to facilitate pipeline processing.

Tips for Preparing for Core Java

Now that you have browsed through the above questions, you might have become aware of the important topics in core Java that you must go through before facing a job interview. If you are a beginner in Java, taking courses to understand the basics of Java can be very helpful. Apart from this, here are some tips to help you get a good grasp on this programming language:

  • Start with the basics
  • Practice Java coding through writing codes
  • Interact with other beginners to discuss the tricky areas
  • Analyze the algorithm carefully
  • Read Java books for beginners for an in-depth understanding of Java concepts. 

More Reads:

  1. Important Accenture Interview Questions That You Must Not Ignore!
  2. Most Common Programming Interview Questions With Answers 2022
  3. Top 50 OOPs Interview Questions With Answers 2022
  4. 50 Frequently Asked LinkedList Interview Questions With Answers 2022
Edited by
Shreeya Thakur
Sr. Associate Content Writer at Unstop

I am a biotechnologist-turned-content writer and try to add an element of science in my writings wherever possible. Apart from writing, I like to cook, read and travel.

Tags:
Interview Interview Preparation Interview Questions Engineering

Comments

Add comment
comment No comments added Add comment