Mastering 100+ Core Java Interview Questions and Answers 2024

Welcome to the world of core Java interview questions and Answers with Real World Examples. Whether you're a fresh graduate stepping into the coding world or an experienced developer seeking to enhance your skills, mastering Java is always challenging.

The Author behind this blog is none other than a developer who has personally encountered the challenges of technical interviews in the programming world. Taking into account all the challenges, we've compiled a set of core Java interview questions and answers designed to cover fundamental concepts as well as advanced topics.

Whether you're gearing up for your first interview or aiming to refine your expertise, these questions will serve as a valuable resource. Let's start preparing from this Java guide, which will not only help you ace interviews but also deepen your understanding of this powerful programming language. Let the exploration begin!

Core Java: Basic Java Interview Questions

To get started, Basic Concepts in Java are the fundamental ideas you need to understand. It is essential for anyone to have a solid understanding of these basic concepts to build applications and solve problems using the Java programming language.

Understanding Java: The Language Overview

1. What do you know about Java? Why Java is a popular choice for development?

Java is a popular choice for development because it’s a very user-friendly high-level programming language. Java Follows the OOP Object Oriented Programming approach and It is recognized as a user programming language that provides platform independence as well as portability. It's also popular for developing cross-platform applications due to its "Write Once, Run Anywhere" philosophy.

2. Can you explain why you prefer Java over other coding languages?

Java is platform-independent, and it’s one of its best features is Java has automatic memory management (takes care of remembering things for you), and supports multithreading (can do many things at once), making it suitable for developing useful applications. It also has a large standard library and a strong community as well.

3. What are the main components of a Java program.

A Java program is made up of components which include, classes, methods, variables, and statements. The key components include the class definition, the main method, and the code which is enclosed within the brackets.

4. Explain the concept of a Java Virtual Machine (JVM)?

JVM is an essential component of Java that takes the compiled code you write in Java and turns it into instructions that computers can understand. Java Virtual Machine provides a runtime environment for Java programs. JVM also makes sure that your Java programs can run on any device, no matter how different they are, without needing any changes.

5. How does Java achieve platform independence?

Java achieves platform independence with the support of Java Virtual Machine (JVM), which makes the execution of Java programs possible, on any platform. It's just like speaking a language that everyone understands, making Java really flexible and easy to use on different machines.

6. What is a class in Java, and how does it differ from an object?

In Java, a class serves as a template or you can say a blueprint that provides a structure. Class defines the properties and behaviors that objects of the class will have. For example, take Class as Car, with properties such as "brand of the car," or "model of the car" and "color of the car" etc. The behavior means the functions or the methods like "Turn off Lights" or “Start the Engine”.

The difference lies in the fact that a class provides a design, while an object is an instance of that class which means, an object of the "Car" class is the actual car, like my favorite "BMW M50”.

7. How is memory management handled in Java?

In Java programming language, memory management is handled through garbage collection. Garbage collection is the process that involves the Java Virtual Machine (JVM) that automatically releases the memory that is no longer required in the program. So with the help of Garbage collection Java prevents memory leaks and improves the efficiency of the program.

8. What is the significance of the 'public static void main' method in Java?

The 'public static void main' method is the entry point for a Java program. It is the method that is called when a Java application starts, without it, your program won't run, it's like the must-have ingredient for starting the whole cooking process in a recipe.

9. In Java what is the role of import statement?

In programming, the import statement allows us to access classes and packages, within our program. It is used to prevent any naming conflicts making it easier to build and organize your projects. It’s like using a specific tool in your workshop. Instead of building every tool from scratch, you can import a ready-made tool and use it directly.

10. What different areas does Java work in?

Java covers various domains, including web development, mobile app development (Android), enterprise applications, scientific computing, and embedded systems, making Java a versatile choice for different application needs.

Data Types and Variables

11. Explain the difference between primitive data types and non-primitive data types.

Think of primitive data types in Java as the basic building blocks of programming. These include integers (for whole numbers), decimals (for numbers with fractions), characters (for single letters or symbols), and Booleans (for true or false values).

On the other hand, non-primitive data types are also known as reference types or objects that can store multiple values or even other objects. In Java, non-primitive data types include Strings, Arrays, Classes and Objects, Interfaces, and Enumerations (Enums).

12. What is the purpose of data types in Java?

Data types in Java define the kind of values a variable can hold. They help ensure data integrity and provide a set of rules for performing operations on the data stored in variables. It's like sorting things into different boxes to keep everything organized.

13. How many primitive data types are there in Java?

Java has eight primitive data types, which include byte, short, int, long, float, double, char, and Boolean. These are the basic building blocks for variable declarations.

14. Can you change the data type of a variable in Java?

Yes, you can change the data type of a variable through a process called type casting. This involves converting a variable of one data type to another, either implicitly or explicitly.

15. How does typecasting work in Java, and what is the difference between implicit and explicit casting?

Type casting involves converting a variable from one data type to another. Implicit casting (widening) occurs automatically when a smaller type is assigned to a larger type, while explicit casting (narrowing) requires manual intervention and may result in data loss.

16. Explain the concept of scope in relation to variables.

Scope in Java refers to the block of the code where a variable can be accessed. Variables have different scopes, such as local, instance, and class scope, determining where they can be used within the program.

17. Discuss the differences between local variables, instance variables, and class variables in Java.

Local variables are declared within methods and have limited scope, instance variables belong to an instance of a class, and class variables are shared among all instances of a class. Class variables are declared with the static keyword. Please use question 16 as an example.

18. Can you have a variable with the same name in different scopes?

Yes, you can have variables with the same name in different scopes. Each scope creates a distinct context, and variables within different scopes do not conflict with each other.

19. What is the default value for an uninitialized variable in Java?

Uninitialized variables in Java have a default value based on their data type. For example, numeric types default to 0, Booleans default to false, and object references default to null.

20. What is the significance of the final keyword in Java?

The final keyword restricts the modification of variables, methods, and classes. A final variable cannot be changed, a final method cannot be overridden, and a final class cannot be extended.

Operators and Control Flow Statements

21. What is the purpose of operators in Java?

Operators in Java are symbols that perform operations on variables and values. They allow you to manipulate and perform computations on data, such as addition, subtraction, and comparison.

22. What is the difference between an operand and an operator in Java?

In Java, an operand is a variable or constant involved in an operation, while an operator is a symbol that performs the operation. For example, in a + b, a and b are operands, and + is the operator performing addition.

23. Explain the difference between unary and binary operators in Java.

Unary operators operate on a single operand, while binary operators work with two operands. For example, the unary minus (-) changes the sign of a single operand, whereas the binary plus (+) adds two operands.

24. What are logical operators, and how are they used in Java?

Logical operators in Java, such as "&&" (AND), "||" (OR), and "!" (NOT), are used to combine multiple conditions in a single "if" statement. For instance, you can use "&&" to check if two conditions are true simultaneously or "||" to check if at least one condition is true.

25. How does the "switch" statement differ from the "if-else" in Java?

The "switch" statement is used when there are multiple possible conditions to evaluate against a single variable. It provides a cleaner and more concise way to handle such situations compared to a series of "if-else" statements. The "switch" statement checks the value of the variable and executes the corresponding case.

26. How does the "default" case function in a "switch" statement?

The "default" case in a "switch" statement is optional and provides a block of code to execute when none of the previous case conditions match the switch expression, ensuring that there is a predefined action if none of the specific cases are met

27. How does the conditional (ternary) operator in Java work, and in what situations is it commonly used?

The conditional operator (? :) evaluates a boolean expression and returns one of two values based on whether the expression is true or false. It is commonly used for concise conditional assignments and expressions.

28. Explain the difference between the pre-increment (++i) and post-increment (i++) operators in Java.

The pre-increment operator (++i) increments the value of a variable before its current value is used, while the post-increment operator (i++) uses the current value before incrementing. Understanding the difference is crucial for correct value assignments.

29. How does the ternary operator differ from traditional "if-else" statements in terms of readability and usage?

The ternary operator offers a concise way to use simple conditional statements in Java, often making the code more readable compared to traditional "if-else" statements. However, it is important to use it carefully, as complex conditions may lead to reduced readability, and in such cases, "if-else" statements might be more appropriate.

30. In Java, how do the "&&" (AND) and "||" (OR) operators function in conditional expressions?

In Java, the "&&" (AND) operator combines two Boolean expressions, resulting in a true value only if both expressions are true. The "||" (OR) operator produces a true value if at least one of the expressions is true. If both expressions are false in either case, the entire expression will be false.

Loops (for, while, do-while)

31. What is an infinite loop, and how can it be avoided?

An infinite loop is a loop that executes indefinitely. To avoid an infinite loop in Java, it is important to design the loop's conditions and update statements carefully, you should ensure that at some point, the loop condition becomes false during the execution of the program.

  public static void main(String[] args) {

    while (true) {

      //This is an infinite loop!



32. Can a "for" loop in Java have multiple update statements?

Yes, It’s possible to have multiple update statements in a "for" loop in Java separated by commas. This is useful in a case when we have more complex update operations, such as incrementing or decrementing multiple variables or performing multiple actions at the end of each iteration.

for (int i = 0, j = 10; i < 5; i++, j--) {



33. What is the purpose of the "do-while" loop in Java?

When we want to execute a block of code at least once, we use a "do-while" loop in Java, regardless of whether the specified condition is true or false. The condition is checked at the end of each iteration.

public static void main(String[] args) {

  int count = 0;

   do {

     } while (count < 5);


34. How does the "break" statement work in loops?

To terminate the execution of a loop early, a "break" statement in Java is used. When we use “break”, it immediately exits the loop. It is particularly useful for ending loops based on certain conditions.

for (int i = 0; i < 5; i++) {

      if (i == 2) {




35. Explain the role of the "continue" statement in loops.

To skip the rest of the code inside a loop for the current iteration and jump to the next iteration, the "continue" statement in Java is used. It is useful when certain conditions are met, and you want to skip the remaining part of the code inside a loop for that specific iteration.

36. How does the "while" loop differ from the "do-while" loop?

The main difference between a "while" loop and a "do-while" loop in Java is that the "while" loop checks the condition before entering the loop, whereas the "do-while" loop checks the condition after completing each iteration. This means a "do-while" loop always executes its block of code at least once.

37. How does the "do-while" loop handle the condition if it is initially false?

The block of code is executed at least once, in a "do-while" loop, regardless of whether the condition is initially false. The condition is checked at the end of each iteration, and if it becomes false, the loop terminates.

38. Can the loop control variable be declared outside the loop?

Yes, of course! We can declare the loop control variable in Java outside the loop, but it is a good practice to declare it in the loop whenever possible. This helps in preventing accidental modification from outside the loop.

39. When should a "for" loop be preferred over a "while" loop, and vice versa?

Use a "for" loop when the number of iterations is known before, and you want a readable loop structure. Choose a "while" loop when the number of iterations is unknown, providing more flexibility in loop control.

40. How can the "for-each" loop be used in Java, and what is its primary advantage?

The "for-each" loop in Java automatically handles the iteration and eliminates the risk of errors, it is useful for iterating over arrays or collections without the need for indexing. It simplifies the syntax and makes the code more readable.

Arrays and Types of Arrays

41. Can the size of an array be changed once it is declared in Java?

No, the size of an array in Java cannot be changed during runtime, because it is fixed upon declaration and to change the size of the existing array, you would need to create a new array with the desired size and copy the elements from the old array.

42. What is the difference between arrays and ArrayList in Java?

The main difference between arrays and ArrayList in Java is that arrays have a fixed size upon declaration, while ArrayLists can dynamically increase or shrink in size. Unlike arrays, ArrayLists also provide built-in methods for easy insertion, deletion, and modification of elements, making them more useful in certain scenarios.

   public static void main(String[] args) {

// Arrays (fixed size)
int[] intArray = new int[3];
intArray[0] = 1;
intArray[1] = 2;
intArray[2] = 3;

// ArrayList (dynamic size)
ArrayList intArrayList = new ArrayList<>();

43. Explain the concept of a multidimensional array in Java.

A multidimensional array in Java also called a 2D array is an array of arrays. It is useful to represent data in multiple dimensions, such as a matrix. In Java, a two-dimensional array is declared by specifying the number of rows and columns.

44. What is the role of the index in Java arrays?

To access individual elements of the arrays, the index is used. It starts from 0 for the first element and increments by 1 for each subsequent element. You should be careful while manipulating indices to avoid "ArrayIndexOutOfBoundsException" errors.

45. What is the difference between a one-dimensional and a two-dimensional array in Java?

A one-dimensional array in Java represents a single list of elements, while a two-dimensional array represents a table or matrix with rows and columns. In a two-dimensional array, each element is identified by two indices, one for the row and one for the column.

// One-dimensional array
int[] oneDimensionalArray = {1, 2, 3};

// Two-dimensional array
int[][] twoDimensionalArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}


46. How does Java handle arrays of primitive data types versus arrays of objects?

In Java, arrays of primitive data types actually store the values, while arrays of objects store references to the objects. This difference is important because when we do any operations on primitive arrays, it directly manipulates the values, whereas object arrays manipulate the references (memory addresses) to objects when we do any operation on arrays of objects.

47. Can an array in Java store elements of different data types?

No, they can only store elements of the same data type, because Java arrays are homogeneous. If you need to store elements of different data types, you may need to use an array of objects or other data structures like ArrayList.

48. Explain the difference between length and length() when working with arrays in Java.

Length is a property of arrays in Java, it represents the number of elements in the array. On the other hand, length() is a method used to get the length of the string.

49. Can an array in Java have a negative index?

No, attempting to access elements with a negative index will result in runtime errors, because in Java, array indices must be non-negative integers.

50. In Java arrays, how can you update, delete, and insert elements?

Update: To update the value of an element in a Java array, simply assign a new value to the required index of the element. For example, if you have an array named cars and want to update the value at index 2, you can use cars[2] = newValue;.

Delete: We cannot directly delete an element in Java arrays because of their fixed size but, if you create a new array with a size one less than the original, and exclude the element you want to "delete," and copy all the remaining elements to the new array, you will be able to delete the desired element from an array, but it’s not recommended.

int[] newArray = new int[numbers.length - 1];

 // Copy elements from the original array to the new array, excluding the element to be deleted

 for (int i = 0, j = 0; i < numbers.length; i++) {

  if (i != indexToDelete) {

   newArray[j++] = numbers[i];



 // Update the original array reference to point to the new array

 numbers = newArray;

Insert: To insert a new element at a specific position in a Java array, create a new array with a size one greater than the original, copy the elements up to the insertion point, insert the new element, and then copy the remaining elements. // Original array.

 int[] originalArray = {3, 4, 5, 6, 7};

// index Position to insert
int position = 2;

// Element to insert
int elementToInsert = 22;

// Create a new array with +1 size
int[] newArray = new int[originalArray.length + 1];

// Copy elements before the insertion point
for (int i = 0; i < position; i++) {
    newArray[i] = originalArray[i];

// Insert the new element
newArray[position] = elementToInsert;

// Copy elements after the insertion point
for (int i = position + 1; i < newArray.length; i++) {
    newArray[i] = originalArray[i - 1];

Core Java: Object-Oriented Programming (OOP) Interview Questions

This set of core Java interview questions and Answers focuses on Object-Oriented Programming (OOP). It's designed for people getting ready for Java programming interviews. These questions cover the basics of OOP like encapsulation, inheritance, polymorphism, and abstraction, all within the context of Java programming. It's a useful resource to help you get familiar with OOP concepts.

Classes and Objects

51. How are objects created from classes in Java?

Objects are created using the new keyword followed by the class name, and then we write constructor brackets to initialize the object.

// Creating objects from the Car class

 Car car1 = new Car("Toyota GLI", 2022);

 Car car2 = new Car("BMW Accord", 2020);

52. Explain the difference between a class and an object.

A class is a blueprint or template in Java where we have attributes (also known as properties) and methods (also known as functions) representing that class. On the other hand, an object is an instance of a class. For example, let's suppose we have a class called 'CakeRecipe', then its object will be an instance which is (cake) itself, created by following that recipe, with different variations.

class CakeRecipe{

    String color;

    String flavor;


// Create an object from the "CakeRecipe" class

CakeRecipe cake = new CakeRecipe();

cake.color = "pink";

cake.flavor = "mango";

53. What are instance variables in Java classes?

Instance variables are basically the attributes or properties that are declared within a class but must not be inside any method. These variables have a separate set of values for each instance of the class. Please use question 16 as an example

54. How are class variables different from instance variables?

Class variables, declared with the static keyword, are shared among all instances of a class, while instance variables are specific to each object. A real-world example would be The bank's management board wants to know the total sum of money held by all customers (objects) in the bank.

55. How does the ‘this’ keyword function in Java classes?

This keyword in Java refers to the current instance of the class. It is usually used to differentiate between instance variables and local variables when they have the same name.

public class Person {

// Instance variables
String name;
int age;

// Constructor
public Person(String name, int age) {
// Using 'this' to distinguish between instance variable and constructor parameter = name;
this.age = age;

public static void main(String[] args) {
// Creating an instance of the Person class
Person person1 = new Person("John", 25);


56. Can a Java class be both abstract and final?

No, a Java class cannot be both abstract and final. An abstract class is meant to be sub-classed, while a final class cannot be sub-classed. Combining both concepts would create a logical problem.

57. What is a final class in Java?

A final class in Java is a class that cannot be extended or sub-classed. Once marked as final, you cannot make any further subclasses. This is done to make sure the class stays as it is, without any changes. A real-world example would be similar to a closed book; you can't add more chapters.

58. How does garbage collection impact Java objects?

Garbage collection in Java is an automatic process handled by the Java Virtual Machine (JVM) that frees up memory by removing objects that are no longer in use. This mechanism gives efficient memory management and improves the overall performance of Java programs. A real-world example would be if a newspaper is read and no one wants it anymore, you will remove it from the room. So that the room doesn't get messy with unnecessary items.

59. What is a singleton class in Java?

In Java, a singleton class is a class that allows only one single instance of itself to be created, and a singleton class can be accessed from anywhere as it provides a global point of access to that instance. Singleton class has only one private constructor.

60. How are arrays of objects handled in Java?

In Java, we use arrays of objects when we have a collection of instances of a specific class. Each element of the array is an object of the specified class, allowing developers to create multiple instances in a structured way.

Student[] students = new Student[3];

// Initializing array elements with Student objects
students[0] = new Student("warner", 20);
students[1] = new Student("smith", 22);
students[2] = new Student("Clarke", 21);

Constructors And Their Types

61. Explain the concept of a copy constructor.

In simple terms, a copy constructor is used for creating a copy of an existing object. It is a special type of constructor that takes an object of the same class as a parameter and creates a new object.

public class Person {

// Instance variables
String name;
int age;

// Parameterized constructor
public Person(String name, int age) { = name;
this.age = age;

// Copy constructor
public Person(Person otherPerson) { =;
this.age = otherPerson.age;

public static void main(String[] args) {
// Creating a Person object using the parameterized constructor
Person person1 = new Person("John", 25);

// Creating a new Person object using the copy constructor
Person person2 = new Person(person1);


62. What is constructor overloading?

Constructor overloading is about defining multiple constructors within a class, each with a different parameter list. This makes the code more flexible and user-friendly.

public class Car {

private String make;
private String model;
private int year;

// Constructor with no parameters
public Car() {
make = "Unknown";
model = "Unknown";
year = 0;

// Constructor with parameters for make and model
public Car(String make, String model) {
this.make = make;
this.model = model;
year = 0; // Default year

// Constructor with parameters for make, model, and year
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;


63. How does Java distinguish between overloaded constructors?

Based on the provided arguments, the compiler selects the appropriate constructor. So Java differentiates between overloaded constructors based on the types of parameters and on the number of parameters they accept during object creation.

64. Can a class have multiple constructors?

Yes, as we discussed in question 62, a class in Java can have multiple constructors, and the concept is called constructor overloading which allows the creation of objects with different sets of parameters.

65. What is the default constructor?

Java provides a default constructor. This default constructor takes no parameters and initializes the object with default values.

66. What happens if a class has no constructor?

Java automatically provides a default constructor. This default constructor initializes the instance variables with their default values.

67. Explain the role of the "this" keyword in a constructor.

The "this" keyword in a constructor is used to refer to the current instance of the class. It is usually used to differentiate instance variables from local variables when they have the same name, ensuring that the correct values are assigned

68. Can constructors call other constructors in the same class?

Yes, This process is known as constructor chaining, constructors can call other constructors in the same class using the "this" keyword, where one constructor invokes another to avoid redundant code.

public class Person {

private String name;
private int age;

// Default constructor
public Person() {
this("Unknown", 0); // Call the parameterized constructor with default values

// Parameterized constructor
public Person(String name, int age) { = name;
this.age = age;


69. Can constructors have access modifiers?

Yes, of course, constructors can have access modifiers like public, private, or protected, used for the visibility of the constructor to other classes.

70. What is the purpose of a parameterized constructor?

A parameterized constructor is used to accept parameters, which provides flexibility in creating objects with different initial states.

71. Explain the difference between a constructor and a method.

constructors have the same name as the class, and they don't have a return type. Both constructors and methods are types of functions in Java. Methods are actually used for performing different actions or operations whereas constructors are used for initializing objects during their creation.

72. How does the order of constructor execution work in the case of inheritance? Can constructors be inherited in Java?

The constructor of the superclass is executed before the constructor of the subclass, However, Constructors are not inherited in the traditional sense.

73. Is it possible to have a return type for a constructor?

No, constructors do not have a return type, not even "void." Their only purpose is to initialize the object.

74. Can a constructor be private?

Yes, a constructor can be private. This is actually done to implement a singleton pattern, which means there will be only a single instance of the class.

75. How do you invoke a superclass constructor in a subclass?

You can use the "super" keyword and this is typically done in the first line of the subclass constructor.

class Animal {
private String species;

// Constructor of the superclass
public Animal(String species) {
this.species = species;

class Dog extends Animal {
private String breed;

// Constructor of the subclass
public Dog(String species, String breed) {
super(species); // Invoke the constructor of the superclass
this.breed = breed;

76. What is the significance of the "final" keyword in a constructor?

This means that no other class can inherit from a class with a "final" constructor. The "final" keyword in a constructor declaration prevents the class from being subclassed.

77. Can constructor overloading involve a mix of parameter types and order?

Yes, in constructor overloading you can have constructors with different numbers or types of parameters, or both.

78. Can constructors be used to create an object without the "new" keyword?

No, you cannot call a constructor like a regular method. Constructors are called only when an object is created using the "new" keyword. They initialize the object's state and allocate memory.

79. What happens if a constructor is declared with a return type?

It won't be recognized as a constructor if a constructor is declared with a return type, it will be treated as a regular method. Constructors don't have return types, not even "void."

80. Can constructors have the "abstract" or "static" modifiers?

Static constructors are not supported in Java and Abstract constructors are not allowed because they are meant to be instantiated.

Inheritance in Java

81. What is the role of the 'extends' keyword in class inheritance?

The 'extends' keyword indicates that the child class inherits properties and behaviors from the parent class. So in general, we use extends in Java to establish a relationship between a subclass and its superclass.

82. Can a class in Java inherit from multiple classes?

No, Java supports single inheritance for classes to avoid the "diamond problem" and maintain a simpler class hierarchy.

83. What is the "diamond problem" in the context of inheritance?

The "diamond problem" occurs in multiple inheritance when a class inherits from two classes that have a common ancestor. It causes conflicts about which method or attribute should be inherited.

class A {
    void doSomething() {

class B extends A {
    void doSomething() {

class C extends A {
    void doSomething() {

// Use interfaces to provide additional functionality
interface BInterface {
    void doSomethingB();

interface CInterface {
    void doSomethingC();

// Implement interfaces to provide specific behaviors
class D implements BInterface, CInterface {
    void doSomethingB() {
        // Implement B specific behavior

    void doSomethingC() {
        // Implement C specific behavior

84. How does Java handle the "diamond problem"?

Java avoids the "diamond problem" by supporting single inheritance for classes. Multiple inheritance is achieved through interfaces, allowing a class to implement multiple interfaces without ambiguity.

85. Explain the concept of superclasses and subclasses in inheritance.

A superclass is basically the parent class whose properties and behaviors are inherited, while a subclass is a child class that inherits from the superclass. The subclass can extend or override the inherited attributes and methods.

86. Can a subclass override a private method of its superclass?

No, private methods are not accessible in the subclass. Method overriding works with methods having at least package-private (protected) visibility.

87. How does the 'super' keyword work in Java?

The 'super' keyword is used to call the superclass's members (fields or methods) in a subclass. When the subclass has overridden a method, and you want to call the superclass's version of that method.

class Vehicle {
    protected String brand;

    public Vehicle(String brand) {
        this.brand = brand;

    public void start() {

class Car extends Vehicle {
    public Car(String brand, int numberOfDoors) {
        super(brand); // Calling the constructor of the superclass using 'super'

    // Override the start method of the superclass
    public void start() {
        super.start(); // Calling the overridden method of the superclass using 'super'

88. Can constructors be inherited in Java?

Subclass or child class constructor implicitly calls the default constructor of the superclass (parent) if there is no explicit call to a superclass constructor using the 'super' keyword.

89. Explain the concept of interface inheritance in Java.

Interface inheritance in Java allows a class to implement multiple interfaces, Classes implementing interfaces must provide concrete implementations for all the methods declared in the interfaces.

90. How does the 'final' keyword impact inheritance in Java?

A class, method, or variable with a final keyword restricts further extension or modification. In the context of inheritance, a final class cannot be subclassed, and final methods cannot be overridden by subclasses.

Polymorphism in Java

91. What is polymorphism in Java?

Polymorphism in Java is a feature that allows objects from different classes to be treated as if they belong to a common type. Let’s understand it with real-life examples.

In this example, we have a common interface Bowler, and three classes FastBowler, SpinBowler, and MediumPaceBowler that implement this interface. Each bowler class provides its own implementation of the bowl method.

// Common interface for all bowlers
interface Bowler {
    void bowl();

// FastBowler class implementing Bowler
class FastBowler implements Bowler {
    public void bowl() {
        //Fast bowler delivers the ball at high speed!

// SpinBowler class implementing Bowler
class SpinBowler implements Bowler {
    public void bowl() {
        //Spin bowler imparts spin on the ball!

// MediumPaceBowler class implementing Bowler
class MediumPaceBowler implements Bowler {
    public void bowl() {
        //Medium-pace bowler combines speed and swing!

public class CricketGame {
  public static void main(String[] args) {
    // Using polymorphism to treat different bowlers as Bowler objects
    Bowler fastBowler = new FastBowler();
    Bowler spinBowler = new SpinBowler();
    Bowler mediumPaceBowler = new MediumPaceBowler();

    // Calling the bowl method for each type of bowler

92. How does polymorphism promote code reusability in Java?

Polymorphism promotes code reusability by allowing a single method or interface to be shared among multiple classes. This means that different classes can provide their own implementation. This enhances the flexibility and maintainability of code.

class Shape {
    public void draw() {
        //Drawing a shape

class Circle extends Shape {
    public void draw() {
    	//Drawing a circle

93. What are the two types of polymorphism in Java?

In Java we have two types of polymorphism: compile-time (or static) polymorphism and runtime (or dynamic) polymorphism. Compile-time polymorphism is achieved through method overloading, while runtime polymorphism is achieved through method overriding.

94. How is method overloading related to polymorphism?

Method overloading is a form of compile-time polymorphism where multiple methods in the same class have the same name but differ in their parameter types or the number of parameters.

// Method to add two integers
public int add(int a, int b) {
    return a + b;

// Overloaded method to add three integers
public int add(int a, int b, int c) {
    return a + b + c;

95. Explain the concept of method overriding in the context of polymorphism.

When a subclass provides a specific implementation for a method that is already defined in its superclass, this concept is called method overriding.

// Superclass
class Animal {
    // Method in the superclass
    public void makeSound() {
        //Generic animal sound;

// Subclass
class Dog extends Animal {
    // Overriding the makeSound method in the subclass
    public void makeSound() {
        //Bark! Bark!;

96. Can polymorphism be achieved without inheritance?

Yes, polymorphism in Java can be achieved without inheritance through interfaces as they allow multiple classes to implement the same interface, facilitating polymorphic behavior.

97. How does polymorphism contribute to the flexibility of code design?

Polymorphism enhances code flexibility by allowing different classes to share a common interface. This enables developers to write code that can work with various types without being dependent on their specific implementations, promoting flexibility of code.

98. In what scenarios is runtime polymorphism particularly useful?

Runtime polymorphism is especially useful in scenarios when working with collections of objects. It allows for more dynamic and flexible behavior.

99. How does polymorphism impact the performance of Java applications?

Modern Java compilers and virtual machines are optimized to handle polymorphic code efficiently. Polymorphism itself does not significantly impact the performance of Java applications.

100. Can polymorphism be achieved across different packages in Java?

Yes, the classes and interfaces must have appropriate access modifiers (e.g., public) for visibility across packages. This enables the use of polymorphic behavior even in a modular codebase.

Abstraction in Java

101. What is an abstraction in OOP?

Abstraction is all about hiding the internal details of an application, it helps us to understand and use things without worrying about all the details.

For example, when you drive a car, you don't need to worry about how the engine works, you just need to know how to drive.     

102. How abstraction is achieved in Java?

Well, Abstraction is achieved through interfaces and abstract classes. Abstract classes can have both abstract and concrete methods, while interfaces only have abstract methods that must be implemented by classes.

abstract class Bowler {

  abstract void bowl(); // Abstract method (no implementation)


class FastBowler extends Bowler {

  void bowl() {

     //Fast Bowler Bowling



class SpinBowler extends Bowler {

  void bowl() {

     //Spin Bowler Bowling



interface Bowler {

    void bowl(); // Abstract method (no implementation)



class FastBowler implements Bowler {

  public void bowl() {

     //Fast Bowler Bowling



class SpinBowler implements Bowler {

  public void bowl() {

      //Spin Bowler Bowling



103. Can we create an instance of an abstract class in Java?

No, because Abstract classes are meant to be extended, we cannot create an instance of an abstract class directly.

104. What is an abstract method?

An abstract method is a method declared without an implementation in an abstract class. Subclasses must provide a concrete implementation for these methods. An abstract class can have both abstract and non-abstract methods.

abstract class Bowler {

  abstract void bowl(); // Abstract method (no implementation)


class FastBowler extends Bowler {

   void bowl() {

     //Fast Bowler Bowling



105. What is an interface in Java? Can a class implement multiple interfaces in Java? Provide a simple example of an interface.

In Java, an interface is all about a set of rules that a class promises to follow. It defines a list of methods that any class implementing the interface must provide.

Yes, a class can implement multiple interfaces in Java. This is useful when a class needs to inherit behavior from multiple sources.

interface Bowler {

    void bowl(); // Abstract method (no implementation)


class FastBowler implements Bowler {

  public void bowl() {

     //Fast Bowler Bowling



class SpinBowler implements Bowler {

  public void bowl() {

     //Spin Bowler Bowling



106. How does abstraction benefit developers, and what advantages does it offer in Java?

Abstraction reduces code complexity, and abstract classes and interfaces enable the creation of reusable code. It promotes a cleaner code structure, making it easier to maintain and extend in projects.

Encapsulation in Java

107. What is encapsulation and how to achieve encapsulation in Java?

Encapsulation is all about hiding the internal implementation details and restricting someone from direct access. Encapsulation is achieved in Java by declaring the variables as private and providing public methods to access those variables like (getters and setters). This way, the internal details of the class are hidden from the outside world.

108. What are access modifiers in encapsulation?

Access modifiers define the visibility of variables and methods in Java.

Public: Accessible from any class.

Protected: Accessible within its package and by subclasses.

Default (no modifier): Accessible only within its package.

Private: Accessible only within its own class.

109. Can you give an example of encapsulation in a Java class?

public class BankBalance {

    // Private field encapsulating balance data

    private double balance;

    // Public constructor

    public BankBalance(double initialBalance) {

        this.balance = initialBalance;


    // Public method to get balance (read-only)

    public double getBalance() {

        return balance;


    // Public method to set balance

    public void setBalance(double balance) {

        this.balance = balance;



110. Can encapsulation be achieved without using access modifiers?

To control the visibility of variables and methods, encapsulation relies on access modifiers. Without access modifiers, there would be no way to restrict direct access.

Ending our Java Exploration: Conclusion!

In wrapping up, getting good at Core Java interviews is a big deal for anyone learning to code. I hope these questions and answers have been a big help to you. We covered everything from the basics to advance like Object-Oriented Programming.

Remember, it's not just about memorizing answers. Try to understand how things work and try them out in real scenarios. The world of programming is always changing, so keep learning, keep practicing, and try new things.

Whenever you find yourself in need of programming assistance or suggestions, I'm just a message away. I'm available 24 hours a day to help you out. Stay Blessed, and Keep on coding!

Post a Comment