• Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

Related Articles

  • Solve Coding Problems
  • Java Programs - Java Programming Examples

Java Basic Programs

  • How to Read and Print an Integer value in Java
  • Ways to read input from console in Java
  • Java Program to Multiply two Floating-Point Numbers
  • Java Program to Swap Two Numbers
  • Java Program to Add Two Binary Strings
  • Java Program to Add two Complex Numbers
  • Java Program to Check if a Given Integer is Odd or Even
  • Java Program to Find the Largest of three Numbers
  • Java Program to Find LCM of Two Numbers
  • Java Program to Find GCD or HCF of Two Numbers
  • Java Program to Display All Prime Numbers from 1 to N
  • Java Program to Find if a Given Year is a Leap Year
  • Java Program to Check Armstrong Number between Two Integers
  • Java Program to Check If a Number is Neon Number or Not
  • Java Program to Check Whether the Character is Vowel or Consonant
  • Java Program for factorial of a number
  • Java Program to Find Sum of Fibonacci Series Numbers of First N Even Indexes
  • Java Program to Calculate Simple Interest
  • Java Program for compound interest
  • Java Program to Find the Perimeter of a Rectangle

Java Pattern Programs

  • Java Program to Print Right Triangle Star Pattern
  • Java Program to Print Left Triangle Star Pattern
  • Java Program to Print Pyramid Number Pattern
  • Java Program to Print Reverse Pyramid Star Pattern
  • Java Program to Print Upper Star Triangle Pattern
  • Java Program to Print Mirror Upper Star Triangle Pattern
  • Java Program to Print Downward Triangle Star Pattern
  • Java Program to Print Mirror Lower Star Triangle Pattern
  • Java Program to Print Star Pascal’s Triangle
  • Java Program to Print Diamond Shape Star Pattern
  • Java Program to Print Square Star Pattern
  • Java Program to Print Pyramid Star Pattern
  • Java Program to Print Spiral Pattern of Numbers

Java Conversion Programs

  • Java Program to Convert Binary to Octal
  • Java Program to Convert Octal to Decimal
  • Java Program For Decimal to Octal Conversion
  • Java Program For Hexadecimal to Decimal Conversion
  • Java Program For Decimal to Hexadecimal Conversion
  • Java Program for Decimal to Binary Conversion
  • Boolean toString() method in Java with examples
  • Convert String to Double in Java
  • Java Program to Convert Double to String
  • Java Program to Convert String to Long
  • Java Program to Convert Long to String
  • Java Program For Int to Char Conversion
  • Java Program to Convert Char to Int

Java Classes and Object Programs

  • Classes and Objects in Java
  • Abstract Class in Java
  • Singleton Method Design Pattern in Java
  • Interfaces in Java
  • Encapsulation in Java
  • Inheritance in Java
  • Abstraction in Java
  • Difference Between Data Hiding and Abstraction in Java
  • Polymorphism in Java
  • Method Overloading in Java
  • Overriding in Java
  • Super Keyword in Java
  • 'this' reference in Java
  • static Keyword in Java
  • Access Modifiers in Java

Java Methods Programs

  • Java main() Method - public static void main(String[] args)
  • Difference between static and non-static method in Java
  • HashTable forEach() method in Java with Examples
  • StringBuilder toString() method in Java with Examples
  • StringBuffer codePointAt() method in Java with Examples
  • How compare() method works in Java
  • Short equals() method in Java with Examples
  • Difference Between next() and hasNext() Method in Java Collections
  • What does start() function do in multithreading in Java?
  • Difference between Thread.start() and Thread.run() in Java

Java Searching Programs

  • Java Program for Linear Search
  • Binary Search in Java
  • Java Program To Recursively Linearly Search An Element In An Array

Java 1-D Array Programs

  • Check if a value is present in an Array in Java
  • Java Program to find largest element in an array
  • Arrays.sort() in Java with examples
  • Java Program to Sort the Array Elements in Descending Order
  • Java Program to Sort the Elements of an Array in Ascending Order
  • Remove duplicates from Sorted Array
  • Java Program to Merge Two Arrays
  • Java Program to Check if two Arrays are Equal or not
  • Remove all occurrences of an element from Array in Java
  • Java Program to Find Common Elements Between Two Arrays
  • Array Copy in Java
  • Java Program For Array Rotation

Java 2-D Arrays (Matrix) Programs

  • Print a 2 D Array or Matrix in Java
  • Java Program to Add two Matrices
  • Sorting a 2D Array according to values in any given column in Java
  • Java Program to Find Transpose of Matrix
  • Java Program to Find the Determinant of a Matrix
  • Java Program to Find the Normal and Trace of a Matrix
  • Java Program to Print Boundary Elements of the Matrix
  • Java Program to Rotate Matrix Elements
  • Java Program to Compute the Sum of Diagonals of a Matrix
  • Java Program to Interchange Elements of First and Last in a Matrix Across Rows
  • Java Program to Interchange Elements of First and Last in a Matrix Across Columns

Java String Programs

  • Java Program to get a character from a String
  • Replace a character at a specific index in a String in Java
  • Reverse a string in Java
  • Java Program to Reverse a String using Stack
  • Sort a String in Java (2 different ways)
  • Swapping Pairs of Characters in a String in Java
  • Check if a given string is Pangram in Java
  • Print first letter of each word in a string using regex
  • Java Program to Determine the Unicode Code Point at Given Index in String
  • Remove Leading Zeros From String in Java
  • Compare two Strings in Java
  • Compare two strings lexicographically in Java
  • Java program to print Even length words in a String
  • Insert a String into another String in Java
  • Split a String into a Number of Substrings in Java

Java List Programs

  • Initializing a List in Java
  • How to Find a Sublist in a List in Java?
  • Min and Max in a List in Java
  • Split a List into Two Halves in Java
  • How to remove a SubList from a List in Java
  • How to Remove Duplicates from ArrayList in Java
  • How to sort an ArrayList in Ascending Order in Java
  • Get first and last elements from ArrayList in Java
  • Convert a List of String to a comma separated String in Java
  • How to Add Element at First and Last Position of LinkedList in Java?
  • Find common elements in two ArrayLists in Java
  • Remove repeated elements from ArrayList in Java

Java Date and Time Programs

  • Java Program to Format Time in AM-PM format
  • Java Program to Display Dates of a Calendar Year in Different Format
  • Java Program to Display Current Date and Time
  • Java Program to Display Time in Different Country Format
  • How to Convert Local Time to GMT in Java?

Java File Programs

  • Java Program to Create a New File
  • Java Program to Create a Temporary File
  • Java Program to Rename a File
  • Java Program to Make a File Read-Only
  • Comparing Path of Two Files in Java
  • Different Ways to Copy Content From One File to Another File in Java
  • Java Program to Print all the Strings that Match a Given Pattern from a File
  • Java Program to Append a String in an Existing File
  • Java Program to Read Content From One File and Write it into Another File
  • Java Program to Read and Print All Files From a Zip File

Java Directory Programs

  • Java Program to Traverse in a Directory
  • Java Program to Get the Size of a Directory
  • Java Program to Delete a directory
  • Java Program to Create Directories Recursively
  • Java Program to Search for a File in a Directory
  • Java Program to Find Current Working Directory
  • Java Program to List all Files in a Directory and Nested Sub-Directories

Java Exceptions and Errors Programs

  • Exceptions in Java
  • Types of Errors in Java with Examples
  • Java Program to Handle the Exception Hierarchies
  • Java Program to Handle the Exception Methods
  • Java Program to Handle Checked Exception
  • Java Program to Handle Unchecked Exception
  • Java Program to Handle Divide By Zero and Multiple Exceptions
  • Unreachable Code Error in Java
  • Thread Interference and Memory Consistency Errors in Java

Java Collections Programs

  • Collections in Java
  • How to Print a Collection in Java?
  • Java Program to Compare Elements in a Collection
  • Java Program to Get the Size of Collection and Verify that Collection is Empty
  • Collections.shuffle() Method in Java with Examples
  • Collections.reverse() Method in Java with Examples
  • Java Program to Change a Collection to an Array
  • Convert an Array into Collection in Java
  • How to Replace a Element in Java ArrayList?
  • Java Program to Rotate Elements of the List
  • How to iterate any Map in Java

Java Multithreading Programs

  • Thread isAlive() Method in Java With Examples
  • How to Temporarily Stop a Thread in Java?
  • Joining Threads in Java
  • Daemon Thread in Java

Java More Java Programs

  • Program to Print Fibonacci Series in Java
  • How to convert LinkedList to Array in Java?
  • Program to Convert a Vector to List in Java
  • Convert a String to a List of Characters in Java
  • Convert an Iterator to a List in Java
  • Program to Convert List to Map in Java
  • Program to Convert List to Stream in Java
  • Convert List to Set in Java
  • Java Program to Convert InputStream to String
  • Convert Set of String to Array of String in Java
  • Java Program to Convert String to Object
  • How to Convert a String value to Byte value in Java with Examples

Java Programs – Java Programming Examples

Java Programming Examples: Java is one of the most popular programming languages today because of its simplicity. Java programming concepts such as control statements, arrays, strings, object-oriented programming (OOP), etc. are very important from an interview perspective as well as from exams. 

Whether you are a fresher preparing for job interviews or a beginner who has covered Java fundamentals and wants to practice Java concepts. then, This JAVA Programs article covers everything in an organized manner from Basic Java programs like the Fibonacci series , Prime numbers , Factorial numbers , and Palindrome numbers to advanced Java programs.

Prerequisites : JAVA  

Java Programs

Java programs: Topic-Wise

  • Java Program to Read The Number From Standard Input
  • Java Program to Get Input from the User
  • Java Program to Multiply Two Floating-Point Numbers
  • Java Program to Add Two Complex Numbers
  • Java Program to Check Even or Odd Integers
  • Java Program to Find Largest Among 3 Numbers
  • Java Program to Find LCM of 2 numbers
  • Java Program to Find GCD or HCF of 2 numbers
  • Java Program to Check Leap Year
  • Java Program to Check whether the input number is a Neon Number
  • Java Program to Check whether input character is vowel or consonant
  • Java Program to Find Factorial of a number
  • Java Program to Find Even Sum of Fibonacci Series Till number N
  • Java Program to Calculate Compound Interest
  • Java Program to Print Star Pascal’s Triangle
  • Java Program to Print Diamond Star Pattern
  • Java Program For Binary to Octal Conversion
  • Java Program For Octal to Decimal Conversion
  • Java Program For Decimal to Binary Conversion
  • Java Program For Binary to Decimal Conversion
  • Java Program For Boolean to String Conversion
  • Java Program For String to Double Conversion
  • Java Program For Double to String Conversion
  • Java Program For String to Long Conversion
  • Java Program For Long to String Conversion
  • Java Program For Char to Int Conversion
  • Java Program to Create a Class and Object
  • Java Program to Create Abstract Class
  • Java Program to Create Singleton Class
  • Java Program to Create an Interface
  • Java Program to Show Encapsulation in Class
  • Java Program to Show Inheritance in Class
  • Java Program to Show Abstraction in Class
  • Java Program to Show Data Hiding in Class
  • Java Program to Show Polymorphism in Class
  • Java Program to Show Overloading of Methods in Class
  • Java Program to Show Overriding of Methods in Classes
  • Java Program to Show Use of Super Keyword in Class
  • Java Program to Show Use of This Keyword in Class
  • Java Program to Show Usage of Static keyword in Class
  • Java Program to Show Usage of Access Modifier
  • Java Program to Show Usage of Main() method
  • Java Program to Show Use of Static and Non-static Methods
  • Java Program to Show Usage of forEach() Method
  • Java Program to Show Usage of toString() Method
  • Java Program to Show Usage of codePointAt() Method
  • Java Program to Show Usage of compare() Method
  • Java Program to Show Usage of equals() Method
  • Java Program to Show Usage of hasNext() and next() Method
  • start() Method
  • run() Method
  • Java Program For Linear Search
  • Java Program For Binary Search
  • Java Program to Recursively Linearly Search an Element in an Array
  • Java Program to Search an Element in an Array
  • Java Program to Find the Largest Element in an Array
  • Java Program to Sort an Array
  • Java Program to Sort the Elements of an Array in Descending Order
  • Java Program to Remove Duplicate Elements From an Array
  • Java Program to Check if Two Arrays Are Equal or Not
  • Java Program to Remove All Occurrences of an Element in an Array
  • Java Program to Find Common Array Elements
  • Java Program to Copy All the Elements of One Array to Another Array
  • Java Program to Print a 2D Array
  • Java Program to Add Two Matrices
  • Java Program to Sort the 2D Array Across Columns
  • Java Program to Check Whether Two Matrices Are Equal or Not
  • Java Program to Find the Transpose
  • Java Program to Find the Determinant
  • Java Program to Find the Normal and Trace
  • Java Program to Print Boundary Elements of a Matrix
  • Java Program to Get a Character From the Given String
  • Java Program to Replace a Character at a Specific Index
  • Java Program to Reverse a String
  • Java Program to Reverse a String Using Stacks
  • Java Program to Sort a String
  • Java Program to Swapping Pair of Characters
  • Java Program to Check Whether the Given String is Pangram
  • Java Program to Print first letter of each word using regex
  • Java Program to Determine the Unicode Code Point at a given index
  • Java Program to Remove leading zeros
  • Java Program to Compare two strings
  • Java Program to Compare two strings lexicographically
  • Java Program to Print even length words
  • Java Program to Insert a string into another string
  • Java Program to Splitting into a number of sub-strings
  • Java Program to Initializing a List
  • Java Program to Find a Sublist in a List
  • Java Program to Get Minimum and Maximum From a List
  • Java Program to Split a list into Two Halves
  • Java Program to Remove a Sublist from a List
  • Java Program to Remove Duplicates from an Array List
  • Java Program to Remove Null from a List container
  • Java Program to Sort Array List in an Ascending Order
  • Java Program to Get First and Last Elements from an Array List
  • Java Program to Convert a List of String to Comma Separated String
  • Java Program to Add Element at First and Last Position of a Linked list
  • Java Program to Find Common Elements in Two ArrayList
  • Java Program to Remove Repeated Element From An ArrayList
  • Java Program to Format time in AM-PM format
  • Java Program to Display Dates of Calendar Year in Different Format
  • Java Program to Display current date and time
  • Java Program to Display time in different country’s format
  • Java Program to Convert the local Time to GMT
  • Java Program to Create a new file
  • Java Program to Create a temporary file
  • Java Program to Write into a file
  • Java Program to Rename a file in java
  • Java Program to Compare Paths of Two files
  • Java Program to Copy one file into another file
  • Java Program to Print all the Pattern that Matches Given Pattern From a File
  • Java Program to Read content from one file and writing it into another file
  • Java Program to Read and printing all files from a zip file
  • Java Program to Traverse in a directory
  • Java Program to Get the size of a directory
  • Java Program to Delete a Directory
  • Java Program to Create directories recursively
  • Java Program to Search for a file in a directory
  • Java Program to Find the current working directory
  • Java Program to Display all the directories in a directory
  • Java Program to Show Runtime Exceptions
  • Java Program to Show Types of Errors
  • Java program to Handle the Checked exceptions
  • Java Program to Handle the Unchecked Exceptions
  • Java Program to Show Unreachable Code Error
  • Java Program to Show Thread interface and memory consistency errors
  • Java Program to Use Different Types of Collection
  • Java Program to Print a Collection
  • Java Program to Get the Size of the Collection
  • Java Program to Shuffle the Elements of a Collection
  • Java Program to Reverse a Collection
  • Java Program to Convert Collection into Array
  • Java Program to Convert Array into Collection
  • Java Program to Replace Elements in a List
  • Java Program to Rotate Elements of a List
  • Java Program to Iterate through Elements of HashMap
  • Java Program to Check the Thread Status
  • Java Program to Suspend a thread
  • Java Program to Join Threads
  • Java Program to Show Daemon Thread
  • Java Program to Print Fibonacci Series in Different Ways
  • Java Program to Convert Linked List to an Array
  • Java Program to Convert Vector to a List
  • Java Program to Convert String to a List of Characters
  • Java Program to Convert Iterator to a List
  • Java Program to Convert List to a Map
  • Java Program to Convert List to a Stream
  • Java Program to Convert List to Set
  • Java Program to Convert Set of String to Array of String
  • Java Program to Convert string value to byte value

In this article, we dealt with a variety of Java programming questions categorized as basic programs, control statements, arrays , strings , oops , and much more that are frequently asked in interviews and exams.

Each Java program will give you a different approach to solving a particular problem in Java. If you are new to Java programming, we highly recommend you to go through our article on Java tutorial , where we’ve covered all the basics and advanced topics of Java programming with practical examples and programs.

Please Login to comment...

  • kapoorsagar226
  • deepanshusajwan1

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Java Coding Practice

core java problem solving questions

What kind of Java practice exercises are there?

How to solve these java coding challenges, why codegym is the best platform for your java code practice.

  • Tons of versatile Java coding tasks for learners with any background: from Java Syntax and Core Java topics to Multithreading and Java Collections
  • The support from the CodeGym team and the global community of learners (“Help” section, programming forum, and chat)
  • The modern tool for coding practice: with an automatic check of your solutions, hints on resolving the tasks, and advice on how to improve your coding style

core java problem solving questions

Click on any topic to practice Java online right away

Practice java code online with codegym.

In Java programming, commands are essential instructions that tell the computer what to do. These commands are written in a specific way so the computer can understand and execute them. Every program in Java is a set of commands. At the beginning of your Java programming practice , it’s good to know a few basic principles:

  • In Java, each command ends with a semicolon;
  • A command can't exist on its own: it’s a part of a method, and method is part of a class;
  • Method (procedure, function) is a sequence of commands. Methods define the behavior of an object.

Here is an example of the command:

The command System.out.println("Hello, World!"); tells the computer to display the text inside the quotation marks.

If you want to display a number and not text, then you do not need to put quotation marks. You can simply write the number. Or an arithmetic operation. For example:

Command to display the number 1.

A command in which two numbers are summed and their sum (10) is displayed.

As we discussed in the basic rules, a command cannot exist on its own in Java. It must be within a method, and a method must be within a class. Here is the simplest program that prints the string "Hello, World!".

We have a class called HelloWorld , a method called main() , and the command System.out.println("Hello, World!") . You may not understand everything in the code yet, but that's okay! You'll learn more about it later. The good news is that you can already write your first program with the knowledge you've gained.

Attention! You can add comments in your code. Comments in Java are lines of code that are ignored by the compiler, but you can mark with them your code to make it clear for you and other programmers.

Single-line comments start with two forward slashes (//) and end at the end of the line. In example above we have a comment //here we print the text out

You can read the theory on this topic here , here , and here . But try practicing first!

Explore the Java coding exercises for practicing with commands below. First, read the conditions, scroll down to the Solution box, and type your solution. Then, click Verify (above the Conditions box) to check the correctness of your program.

core java problem solving questions

The two main types in Java are String and int. We store strings/text in String, and integers (whole numbers) in int. We have already used strings and integers in previous examples without explicit declaration, by specifying them directly in the System.out.println() operator.

In the first case “I am a string” is a String in the second case 5 is an integer of type int. However, most often, in order to manipulate data, variables must be declared before being used in the program. To do this, you need to specify the type of the variable and its name. You can also set a variable to a specific value, or you can do this later. Example:

Here we declared a variable called a but didn't give it any value, declared a variable b and gave it the value 5 , declared a string called s and gave it the value Hello, World!

Attention! In Java, the = sign is not an equals sign, but an assignment operator. That is, the variable (you can imagine it as an empty box) is assigned the value that is on the right (you can imagine that this value was put in the empty box).

We created an integer variable named a with the first command and assigned it the value 5 with the second command.

Before moving on to practice, let's look at an example program where we will declare variables and assign values to them:

In the program, we first declared an int variable named a but did not immediately assign it a value. Then we declared an int variable named b and "put" the value 5 in it. Then we declared a string named s and assigned it the value "Hello, World!" After that, we assigned the value 2 to the variable a that we declared earlier, and then we printed the variable a, the sum of the variables a and b, and the variable s to the screen

This program will display the following:

We already know how to print to the console, but how do we read from it? For this, we use the Scanner class. To use Scanner, we first need to create an instance of the class. We can do this with the following code:

Once we have created an instance of Scanner, we can use the next() method to read input from the console or nextInt() if we should read an integer.

The following code reads a number from the console and prints it to the console:

Here we first import a library scanner, then ask a user to enter a number. Later we created a scanner to read the user's input and print the input out.

This code will print the following output in case of user’s input is 5:

More information about the topic you could read here , here , and here .

See the exercises on Types and keyboard input to practice Java coding:

Conditions and If statements in Java allow your program to make decisions. For example, you can use them to check if a user has entered a valid password, or to determine whether a number is even or odd. For this purpose, there’s an 'if/else statement' in Java.

The syntax for an if statement is as follows:

Here could be one or more conditions in if and zero or one condition in else.

Here's a simple example:

In this example, we check if the variable "age" is greater than or equal to 18. If it is, we print "You are an adult." If not, we print "You are a minor."

Here are some Java practice exercises to understand Conditions and If statements:

In Java, a "boolean" is a data type that can have one of two values: true or false. Here's a simple example:

The output of this program is here:

In addition to representing true or false values, booleans in Java can be combined using logical operators. Here, we introduce the logical AND (&&) and logical OR (||) operators.

  • && (AND) returns true if both operands are true. In our example, isBothFunAndEasy is true because Java is fun (isJavaFun is true) and coding is not easy (isCodingEasy is false).
  • || (OR) returns true if at least one operand is true. In our example, isEitherFunOrEasy is true because Java is fun (isJavaFun is true), even though coding is not easy (isCodingEasy is false).
  • The NOT operator (!) is unary, meaning it operates on a single boolean value. It negates the value, so !isCodingEasy is true because it reverses the false value of isCodingEasy.

So the output of this program is:

More information about the topic you could read here , and here .

Here are some Java exercises to practice booleans:

With loops, you can execute any command or a block of commands multiple times. The construction of the while loop is:

Loops are essential in programming to execute a block of code repeatedly. Java provides two commonly used loops: while and for.

1. while Loop: The while loop continues executing a block of code as long as a specified condition is true. Firstly, the condition is checked. While it’s true, the body of the loop (commands) is executed. If the condition is always true, the loop will repeat infinitely, and if the condition is false, the commands in a loop will never be executed.

In this example, the code inside the while loop will run repeatedly as long as count is less than or equal to 5.

2. for Loop: The for loop is used for iterating a specific number of times.

In this for loop, we initialize i to 1, specify the condition i <= 5, and increment i by 1 in each iteration. It will print "Count: 1" to "Count: 5."

Here are some Java coding challenges to practice the loops:

An array in Java is a data structure that allows you to store multiple values of the same type under a single variable name. It acts as a container for elements that can be accessed using an index.

What you should know about arrays in Java:

  • Indexing: Elements in an array are indexed, starting from 0. You can access elements by specifying their index in square brackets after the array name, like myArray[0] to access the first element.
  • Initialization: To use an array, you must declare and initialize it. You specify the array's type and its length. For example, to create an integer array that can hold five values: int[] myArray = new int[5];
  • Populating: After initialization, you can populate the array by assigning values to its elements. All elements should be of the same data type. For instance, myArray[0] = 10; myArray[1] = 20;.
  • Default Values: Arrays are initialized with default values. For objects, this is null, and for primitive types (int, double, boolean, etc.), it's typically 0, 0.0, or false.

In this example, we create an integer array, assign values to its elements, and access an element using indexing.

In Java, methods are like mini-programs within your main program. They are used to perform specific tasks, making your code more organized and manageable. Methods take a set of instructions and encapsulate them under a single name for easy reuse. Here's how you declare a method:

  • public is an access modifier that defines who can use the method. In this case, public means the method can be accessed from anywhere in your program.Read more about modifiers here .
  • static means the method belongs to the class itself, rather than an instance of the class. It's used for the main method, allowing it to run without creating an object.
  • void indicates that the method doesn't return any value. If it did, you would replace void with the data type of the returned value.

In this example, we have a main method (the entry point of the program) and a customMethod that we've defined. The main method calls customMethod, which prints a message. This illustrates how methods help organize and reuse code in Java, making it more efficient and readable.

In this example, we have a main method that calls the add method with two numbers (5 and 3). The add method calculates the sum and returns it. The result is then printed in the main method.

All composite types in Java consist of simpler ones, up until we end up with primitive types. An example of a primitive type is int, while String is a composite type that stores its data as a table of characters (primitive type char). Here are some examples of primitive types in Java:

  • int: Used for storing whole numbers (integers). Example: int age = 25;
  • double: Used for storing numbers with a decimal point. Example: double price = 19.99;
  • char: Used for storing single characters. Example: char grade = 'A';
  • boolean: Used for storing true or false values. Example: boolean isJavaFun = true;
  • String: Used for storing text (a sequence of characters). Example: String greeting = "Hello, World!";

Simple types are grouped into composite types, that are called classes. Example:

We declared a composite type Person and stored the data in a String (name) and int variable for an age of a person. Since composite types include many primitive types, they take up more memory than variables of the primitive types.

See the exercises for a coding practice in Java data types:

String is the most popular class in Java programs. Its objects are stored in a memory in a special way. The structure of this class is rather simple: there’s a character array (char array) inside, that stores all the characters of the string.

String class also has many helper classes to simplify working with strings in Java, and a lot of methods. Here’s what you can do while working with strings: compare them, search for substrings, and create new substrings.

Example of comparing strings using the equals() method.

Also you can check if a string contains a substring using the contains() method.

You can create a new substring from an existing string using the substring() method.

More information about the topic you could read here , here , here , here , and here .

Here are some Java programming exercises to practice the strings:

In Java, objects are instances of classes that you can create to represent and work with real-world entities or concepts. Here's how you can create objects:

First, you need to define a class that describes the properties and behaviors of your object. You can then create an object of that class using the new keyword like this:

It invokes the constructor of a class.If the constructor takes arguments, you can pass them within the parentheses. For example, to create an object of class Person with the name "Jane" and age 25, you would write:

Suppose you want to create a simple Person class with a name property and a sayHello method. Here's how you do it:

In this example, we defined a Person class with a name property and a sayHello method. We then created two Person objects (person1 and person2) and used them to represent individuals with different names.

Here are some coding challenges in Java object creation:

Static classes and methods in Java are used to create members that belong to the class itself, rather than to instances of the class. They can be accessed without creating an object of the class.

Static methods and classes are useful when you want to define utility methods or encapsulate related classes within a larger class without requiring an instance of the outer class. They are often used in various Java libraries and frameworks for organizing and providing utility functions.

You declare them with the static modifier.

Static Methods

A static method is a method that belongs to the class rather than any specific instance. You can call a static method using the class name, without creating an object of that class.

In this example, the add method is static. You can directly call it using Calculator.add(5, 3)

Static Classes

In Java, you can also have static nested classes, which are classes defined within another class and marked as static. These static nested classes can be accessed using the outer class's name.

In this example, Student is a static nested class within the School class. You can access it using School.Student.

More information about the topic you could read here , here , here , and here .

See below the exercises on Static classes and methods in our Java coding practice for beginners:

Tutorial Playlist

Java tutorial for beginners, 10 reasons that explain why you need to learn java, what is java: a beginners guide to java, what is jdk in java why do we need it, one-stop solution for java installation in windows, how to get started with eclipse ide, what are java strings and how to implement them, arrays in java: declare, define, and access array, what are java collections and how to implement them, what are java classes and objects and how do you implement them, how to implement the revolutionary oops concepts in java, what is encapsulation in java and how to implement it, what is an abstract class in java and how to implement it, what is inheritance in java and how to implement it, what is java interface and why it's needed, what is polymorphism in java and how to implement it, what is a java lambda expression and how to implement it, your one-stop solution for multithreading in java, the differences between c++ and java that you need to know, java vs. python: which is the best programming language, java vs javascript: know the 8 major differences, top 25 pattern programs in java for printing numbers, java ee tutorial: all you need to know about java ee, what is exception handling in java, what is java jdbc the complete reference, what is java api and the need for java apis, introduction to java servlets and its life-cycle, 10 best java frameworks you should know in 2021, top 25+ brilliant java project ideas for beginners, 180+ core java interview questions and answers for 2024, java programming: the complete reference you need, all you need to know to implement junit testing in java, what is junit a look into the best java testing framework, ruby on rails, the best guide to know what is vue js, type casting in java: everything you need to know, prime number program in java, scanner in java: everything you need to know, access modifiers in java: everything you need to know, armstrong number in java: everything you need to know, singleton class in java: everything you need to know, final keyword in java: all you need to know, wrapper class in java: a complete guide, fibonacci series in java: explained with examples, 180 core java interview questions and answers [2024].

Lesson 29 of 43 By Ravikiran A S

180+ Core Java Interview Questions and Answers for 2024

Table of Contents

Reviewed and fact-checked by Sayantoni Das

Java is the most widely used programming language  in the current IT industry. One major reason for the vast number of beginners and professionals in the field of programming is the career potential that Java knowledge comes with. This article is dedicated to the same purpose. Here is a complete guide on how to help you crack the most frequently asked Core Java Interview questions.

Want a Top Software Development Job? Start Here!

Want a Top Software Development Job? Start Here!

Most Asked Java Interview Questions

Here are some of the most asked Java interview questions.

  • What is Java?
  • Why is Java a platform independent language?
  • What are the differences between C++ and Java?
  • Why is Java not a pure object oriented language?
  • List the features of the Java Programming language?
  • What do you get in the Java download file?
  • Explain JVM, JRE, and JDK.
  • What is a ClassLoader?
  • What are the Memory Allocations available in JavaJava?
  • What are the differences between Heap and Stack Memory in Java?

Now, let's discuss the key Java interview questions for freshers and their answers.

Java Interview Questions for Freshers

So let’s get started with the first set of basic core Java technical interview questions which is primarly useful for freshers.

1. What are the differences between C++ and Java?

C++ is not platform-independent; the principle behind C++ programming is “write once, compile anywhere.”

In contrast, because the byte code generated by the Java compiler is platform-independent, it can run on any machine, Java programs are written once and run everywhere.

Also Read: Learn C++ Programming

Languages Compatibility.

C++ is a programming language that is based on the C programming language . Most other high-level languages are compatible with C++.

Most of the languages of Java are incompatible. Java is comparable to those of C and C++.

Interaction with the library.

It can access the native system libraries directly in C++. As a result, it’s better for programming at the system level.

Java’s native libraries do not provide direct call support. You can use Java Native Interface or access the libraries.

Characteristics.

C++ distinguishes itself by having features that are similar to procedural and object-oriented languages. The characteristic that sets Java apart is automatic garbage collection. Java doesn’t support destructors at the moment.

The semantics of the type.

Primitive and object types in C++ have the same kind of semantics. The primitive and object and classes of Java , on the other hand, are not consistent.

In the context of Compiler and Interpreter.

Java refers to a compiled and interpreted language. In contrast, C++ is only a compiled language.

In Java, the source code is the compiled output is a platform-independent byte code.

In C++, the source program is compiled into an object code that is further executed to produce an output.

2. List the features of the Java Programming language?

A few of the significant features of Java Programming Language are:

Easy: Java is a language that is considered easy to learn. One fundamental concept of OOP Java has a catch to understand.

Secured Feature: Java has a secured feature that helps develop a virus-free and tamper-free system for the users.

OOP: OOP stands for Object-Oriented Programming language. OOP signifies that, in Java, everything is considered an object.

Independent Platform: Java is not compiled into a platform-specific machine; instead, it is compiled into platform-independent bytecode. This code is interpreted by the Virtual Machine on which the platform runs.

3. What do you get in the Java download file? How do they differ from one another?

We get two major things along with the Java Download file. 

JDK - Java Development Kit

JRE - Java Runtime Environment

4. What is a ClassLoader?

A classloader in Java is a subsystem of Java Virtual Machine, dedicated to loading class files when a program is executed; ClassLoader is the first to load the executable file.

Java has Bootstrap, Extension, and Application classloaders.

Also Read: What is Bootstrap and How to Embed Bootstrap into Angular?

5. What are the Memory Allocations available in JavaJava?

Java has five significant types of memory allocations.

  • Class Memory
  • Heap Memory
  • Stack Memory
  • Program Counter-Memory
  • Native Method Stack Memory

6. What are the differences between Heap and Stack Memory in Java?

Stack memory in data structures is  the amount of memory allocated to each individual programme. It is a fixed memory space. Heap memory, in contrast, is the portion that was not assigned to the Java code but will be available for use by the Java code when it is required, which is generally during the program's runtime.

7. Will the program run if we write static public void main?

Yes, the program will successfully execute if written so. Because, in Java, there is no specific rule for the order of specifiers

8. What is the default value stored in Local Variables?

Neither the Local Variables nor any primitives and Object references have any default value stored in them. 

9. Explain the expected output of the following code segment?

public class Simplilearn   

    public static void main (String args[])   

        System.out.println(100 + 100 +“Simplilearn");   

        System.out.println(“E-Learning Company" + 100 + 100);  

The answers for the two print statements are as follows.

  • 200Simplilearn
  • E-Learning Company100100

10. What is an Association?

An Association can be defined as a relationship that has no ownership over another. For example, a person can be associated with multiple banks, and a bank can be related to various people, but no one can own the other.

11. What do you mean by aggregation?

The term aggregation refers to the relationship between two classes best described as a “whole/part” and “has-a” relationship. This kind is the most specialized version of an association relationship. It contains the reference to another class and is said to have ownership of that class.

12. Define Copy Constructor in Java

A Copy Constructor in Java is a constructor that initializes an object through another object of the same class.

13. What is a Marker Interface?

An empty interface in Java  is referred to as a Marker interface. Serializable and Cloneable are some famous examples of Marker Interface. 

14. What is Object Cloning?

An ability to recreate an object entirely similar to an existing object is known as Object Cloning in Java. Java provides a clone() method to clone a current object offering the same functionality as the original object.

15. Can Java be said to be the complete object-oriented programming language

No, Java cannot be treated as a complete object-oriented programming language.

16. What is an object-oriented paradigm?

A Paradigm that is based on the concepts of “Objects.” It contains data and code. Data that is in the form of fields, and regulation, that is in the form of procedures. The exciting feature of this paradigm is that the object’s procedures can access and often modify the data fields themselves.

17. Define Wrapper Classes in Java.

In Java, when you declare primitive datatypes, then Wrapper classes are responsible for converting them into objects(Reference types). 

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

A class that can possess only one object at a time is called a singleton class. To implement a singleton class given steps are to be followed:

  • Make sure that the class has only one object
  • Give global access to that object

Preparing Your Blockchain Career for 2024

Preparing Your Blockchain Career for 2024

19. Define package in Java.

The package is a collective bundle of classes and interfaces and the necessary libraries and JAR files. The use of packages helps in code reusability.

20. Can you implement pointers in a Java Program?

Java Virtual Machine takes care of memory management implicitly. Java's primary motto was to keep programming simple. So, accessing memory directly through pointers is not a recommended action. Hence, pointers are eliminated in Java. 

21. Differentiate between instance and local variables.

For instance, variables are declared inside a class, and the scope of variables in javascript is limited to only a specific object.

A local variable can be anywhere inside a method or a specific block of code. Also, the scope is limited to the code segment where the variable is declared.  

22. Explain Java String Pool.

A collection of strings in Java's Heap memory is referred to as Java String Pool. In case you try to create a new string object, JVM first checks for the presence of the object in the pool. If available, the same object reference is shared with the variable, else a new object is created.

23. What is an Exception?

An Exception handling in Java is considered an unexpected event that can disrupt the program's normal flow. These events can be fixed through the process of Exception Handling.

24. What is the final keyword in Java?

The term final is a predefined word in Java that is used while declaring values to variables. When a value is declared using the final keyword, then the variable's value remains constant throughout the program's execution.

25. What happens when the main() isn't declared as static?

When the main method is not declared as static, then the program may be compiled correctly but ends up with a severe ambiguity and throws a run time error that reads "NoSuchMethodError."

26. Why is Java a platform independent language?

One of the most well-known and widely used programming languages is Java. It is a programming language that is independent of platforms. Java doesn't demand that the complete programme be rewritten for every possible platform. The Java Virtual Machine and Java Bytecode are used to support platform independence. Any JVM operating system can run this platform-neutral byte code. The application is run after JVM translates the byte code into machine code. Because Java programmes can operate on numerous systems without having to be individually rewritten for each platform, the language is referred to as "Write Once, Run Anywhere" (WORA).

27. Why is the main method static in Java?

Java's main() function is static by default, allowing the compiler to call it either before or after creating a class object. The main () function is where the compiler begins programme execution in every Java programme. Thus, the main () method needs to be called by the compiler. If the main () method is permitted to be non-static, the JVM must instantiate its class when calling the function. 

28. What part of memory - Stack or Heap - is cleaned in the garbage collection process?

On Heap memory, garbage collection is employed to release the memory used by objects with no references. Every object created in the Heap space has access to the entire application and may be referred to from anywhere.

29. What is the difference between the program and the process?

A programme is a non-active entity that includes the collection of codes necessary to carry out a specific operation. When a programme is run, an active instance of the programme called a process is launched. A process is begun by a programme once it has been run. The process carries out the program's specified instructions.

30. What are the differences between constructor and method of a class in Java?

Initializing the state of the object is done by constructors. A function Object () { [native code] }, like methods, contains a group of statements (or instructions) that are carried out when an object is created. A method is a group of statements that work together to complete a certain task and return the outcome to the caller. A method has the option of working without returning anything.

31. Which among String or String Buffer should be preferred when there are a lot of updates required to be done in the data?

Because StringBuilder is quicker than StringBuffer, it is advised to utilize it wherever possible. However, StringBuffer objects are the best choice if thread safety is required.

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

The main function is called by the JVM even before the objects are created, thus even if the code correctly compiles, there will still be an error at runtime.

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

This technique designates whether the active thread is a user thread or a daemon thread. For instance, tU.setDaemon(true) would convert a user thread named tU into a daemon thread. On the other side, executing tD.setDaemon(false) would convert a Daemon thread, tD, into a user thread.

34. What happens if there are multiple main methods inside one class in Java?

There is no limit to the number of major approaches you can use. Overloading is the ability to have main methods with different signatures than main (String []), and the JVM will disregard those main methods.

35. How does an exception propagate in the code?

In the event that an exception is not caught, it is initially thrown from the top of the stack and then moves down the call stack to the preceding method. The runtime system looks for a way to handle an exception that a method throws. The ordered list of methods that were called to get to the method where the error occurred is the collection of potential "somethings" that can be used to manage the exception. The call stack is the list of methods, and exception propagation is the search technique.

36. How do exceptions affect the program if it doesn't handle them?

If you don't deal with an exception once it occurs, the programme will end abruptly and the code after the line where the exception occurred won't run.

37. Is it mandatory for a catch block to be followed after a try block?

Each attempt block does not necessarily have to be followed by a catch block. Either a catch block or a final block ought to come after it. Additionally, any exceptions that are expected to be thrown should be mentioned in the method's throws clause.

38. Can you call a constructor of a class inside another constructor?

Yes, a class may include any number of constructors, and each function Object () {[native code] } may call the others using the this() function Object() { [native code] } call function [please do not mix the this() function Object() { [native code] } call function with this keyword]. The constructor's first line should be either this () or this(args). Overloading of constructors is what this is called.

39. Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList. Explain.

Primitive data types like int, float, and others are typically present in an array. In such circumstances, the array immediately saves these elements at contiguous memory regions. While an ArrayList does not contain primitive data types. Instead of the actual object, an ArrayList includes the references to the objects' many locations in memory. The objects are not kept in consecutive memory regions because of this.

40. Why does the java array index start with 0?

The distance from the array's beginning is just an offset. There is no distance because the first element is at the beginning of the array. Consequently, the offset is 0.

41. Why is the remove method faster in the linked list than in an array?

Because there is no background scaling of an array, insertion, addition, and removal operations are quicker with a LinkedList. Only references in adjacent items need to update when a new item is added in the middle of the list.

42. How many overloaded add() and addAll() methods are available in the List interface? Describe the need and uses.

List is an interface in the Java Collections Framework. The add() and addAll() methods      are the main methods at the List interface. The add() method is used to add an element to the list, while the addAll() method is used to add a collection of elements to the list.

The List interface contains two overloaded versions of the add() method:

The first add() method accepts a single argument of type E, the element to be added to the list.

The second add() method accepts a variable number of arguments of type E, which are the elements to be added to the list.

The List interface also contains two overloaded versions of the addAll() method:

The first addAll() method accepts a single argument of type Collection<? Extends E>, which is the collection of elements to be added to the list.

The second addAll() method accepts a variable number of arguments of type E, which are the elements to be added to the list.

43. How does the size of ArrayList grow dynamically? And also state how it is implemented internally?

A resizable array implementation in Java is called ArrayList. Dynamically expanding array lists make it possible to add new elements at any time. The underlying data structure of the ArrayList is an array of the Object class. The ArrayList class in Java has three constructors. There are available readObject and writeObject methods specific to it. The Object Array in an ArrayList is temporary. There are implemented and Serialization-capable versions of RandomAccess, Cloneable, and java.io (that are Marker Interface in Java).

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

A class's testability is improved through composition over inheritance. If a class is comprised of another class, it is simple to create a mock object to simulate the combined class for testing purposes. This privilege is not given by inheritance. Even while Composition and Inheritance both let you reuse code, Inheritance has the drawback of breaking encapsulation. If the function of the subclass depends on the superclass's action, it suddenly becomes vulnerable. Sub-class functionality may be broken without any alteration on the part of the super-class when its behaviour changes.

45. What are Composition and Aggregation? State the difference.

Aggregation (HAS-A) and composition are its two forms (Belongs-to). In contrast to composition, which has a significant correlation, the aggregation has a very modest association. Aggregation can be thought of as a more confined version of the composition. Since all compositions are aggregates but not all aggregates are compositions, aggregate can be thought of as the superset of composition.

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

The new () operator always produces a new object in heap memory when creating a String object. The String pool may return an existing object if we build an object using the String literal syntax, such as "Baeldung," on the other hand.

47. How is the ‘new' operator different from the ‘newInstance()' operator in java?

Both the new operator and the newInstance() method are used to create objects in Java. If we already know the kind of object to create, we can use the new operator; however, if the type of object to create is supplied to us at runtime, we must use the newInstance() function.

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

Yes, even with a garbage collector in place, the programme could still run out of memory. Garbage collection aids in identifying and removing programme objects that are no longer needed in order to release the resources they use. When an object in a programme cannot be reached, trash collection is executed with respect to that object. If there is not enough memory available to create new objects, a garbage collector is used to free up memory for things that have been removed from the scope. When the amount of memory released is insufficient for the creation of new objects, the program's memory limit is exceeded.

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

Multiple threads trying to access the same resources in a multi-threaded software may frequently result in unexpected and incorrect outcomes. Therefore, it must be ensured through some form of synchronization that only one thread can access the resource at any given time. Java offers a method for setting up threads and synchronizing their operations with the aid of synchronized blocks. The synchronized keyword in Java is used to identify synchronized blocks. In Java, a synchronized block is one that is tied to an object. Only one thread can be running at a time inside synchronized blocks since they are all synchronized on the same object. Until the thread inside the synchronized block exits the block, all other threads trying to enter the block are blocked. 

50. Define System.out.println().

System.out.println() in Java outputs the argument that was supplied to it. On the monitor, the println() method displays the findings. An objectname is typically used to call a method.

Kickstart Your UI/UX Career Right Here!

Kickstart Your UI/UX Career Right Here!

51. Can you explain the Java thread lifecycle?

A thread can be in any of the following states in Java. These are the states:

  • New: A new thread is always in the new state when it is first formed. The function hasn't been run yet, thus it hasn't started to execute for a thread in the new state.
  • Active: A thread switches from the new state to the active state when it calls the start() method. The runnable state and the running state are both contained within the active state.
  • Blocked or Waiting: A thread is either in the blocked state or the waiting state when it is inactive for a while (but not indefinitely).
  • Timed waiting: When we use the sleep () method on a particular thread, we are actually engaging in timed waiting. The thread enters the timed wait state using the sleep () function. The thread awakens when the allotted time has passed and resumes execution where it left off.
  • Termination: A thread that has been terminated means it is no longer active in the system. In other words, the thread is inactive and cannot be revived (made active again after being killed).

52. What could be the tradeoff between the usage of an unordered array versus the usage of an ordered array?

When opposed to an unordered array, which has a time complexity of O, an ordered array's search times have a time complexity of O(log n) (n). Due to the need to shift the elements with higher values to create room for the new member, an ordered array has a temporal complexity of O(n) during the insertion process. Instead, an unordered array's insertion operation requires a constant O amount of time (1).

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

The same package or class may be imported more than once. Neither the JVM nor the compiler raise an objection. Even if you import the same class several times, the JVM will only internally load it once.

54. In case a package has sub packages, will it suffice to import only the main package? e.g. Does importing of com.myMainPackage.* also import com.myMainPackage.mySubPackage.*?

Sub-packages won't be imported when a package is imported. When you import a package, all of its classes and interfaces—with the exception of those from its sub-packages—are imported.

55. Will the final block be executed if the code System.exit(0) is written at the end of the try block?

The system is established as the last line to be run, after which nothing will happen, therefore both the catch and finally blocks are essentially ignored.

56. Explain the term “Double Brace Initialisation” in Java?

The outer braces of the double-brace initialization construct an anonymous class that is descended from the provided class and gives an initializer block for that class (the inner braces).

57. Why is it said that the length() method of String class doesn't return accurate results?

Since this char [] array is used by the Java String class internally, the length variable cannot be made public.

58. What are the possible ways of making objects eligible for garbage collection (GC) in Java?

If a reference variable for an object is removed from the programme while it is running, the object may be trash collected. They are also referred to as inaccessible objects occasionally.  The new operator returns a reference to an object after dynamically allocating memory for it.

59. In the below Java Program, how many objects are eligible for garbage collection?

I don't know about the program, but generally, three objects are eligible for garbage collection. 

The first object is created when the program is started and is no longer needed when the program ends. 

The second object is created when the user inputs their name and is no longer required when the program ends. 

The third object is created when the user inputs their address and is no longer needed when the program ends.

60. What is the best way to inject dependency? Also, state the reason.

Constructor injection. A class requesting its dependencies through its function Object() { [native code] } is the most typical instance of dependency injection. Since the client cannot be constructed without the required dependencies, this guarantees that it is always in a correct state.

61. How we can set the spring bean scope. And what supported scopes does it have?

There are four ways to set the scope of a Spring bean: singleton, prototype, request, and session.

The singleton scope creates a single instance of a bean, which is shared by all objects that request it. 

The prototype scope creates a new instance of a bean for each object that requests it.

The request and session scopes are only available in a web-based context. The request scope creates a new bean instance for each HTTP request, and the session scope creates a single instance of a bean shared by all objects in a single HTTP session.

62. What are the different categories of Java Design patterns?

The three categories of Java design patterns are creational, structural, and behavioural design patterns.

63. What is a Memory Leak? Discuss some common causes of it.

A memory leak is the slow degradation of system performance over time brought on by the fragmentation of a computer's RAM as a result of shoddy application design or programming that fails to release memory chunks when they are no longer required. These memory leaks frequently result from session items in excess, insertion into Collection objects without deletion, infinite caches, excessive page switching on the operating system, listener methods that are not called, and bespoke data structures that are poorly written.

64. Assume a thread has a lock on it, calling the sleep() method on that thread will release the lock?

No, the thread might release the locks using notify, notifyAll(), and wait() methods.

65. Write a Java Program to print Fibonacci Series using Recursion.

class FibonacciExample2{  

 static int n1=0,n2=1,n3=0;    

 static void printFibonacci(int count){    

    if(count>0){    

         n3 = n1 + n2;    

         n1 = n2;    

         n2 = n3;    

         System.out.print(" "+n3);   

         printFibonacci(count-1);    

 public static void main(String args[]){    

  int count=10;    

  System.out.print(n1+" "+n2);//printing 0 and 1    

  printFibonacci(count-2);//n-2 because 2 numbers are already printed   

66. Write a Java program to check if the two strings are anagrams.

import java.util.Arrays;     

public class AnagramString {  

    static void isAnagram(String str1, String str2) {  

        String s1 = str1.replaceAll("\\s", "");  

        String s2 = str2.replaceAll("\\s", "");  

        boolean status = true;  

        if (s1.length() != s2.length()) {  

            status = false;  

        } else {  

            char[] ArrayS1 = s1.toLowerCase().toCharArray();  

            char[] ArrayS2 = s2.toLowerCase().toCharArray();  

            Arrays.sort(ArrayS1);  

            Arrays.sort(ArrayS2);  

            status = Arrays.equals(ArrayS1, ArrayS2);  

        }  

        if (status) {  

            System.out.println(s1 + " and " + s2 + " are anagrams");  

            System.out.println(s1 + " and " + s2 + " are not anagrams");  

    public static void main(String[] args) {  

        isAnagram("Keep", "Peek");  

        isAnagram("Mother In Law", "Hitler Woman");  

Keep and Peek are anagrams

MotherInLaw and HitlerWoman are anagrams

67. Write a Java Program to find the factorial of a given number.

4! = 4*3*2*1 = 24  

5! = 5*4*3*2*1 = 120  

68. Given an array of non-duplicating numbers from 1 to n where one number is missing, write an efficient java program to find that missing number.

Input: arr[] = {1, 2, 4, 6, 3, 7, 8}, N = 8

             Output: 5

            Explanation: The missing number between 1 to 8 is 5

69. Write a Java Program to check if any number is a magic number or not. A number is said to be a magic number if after doing the sum of digits in each step and in turn doing the sum of digits of that sum, the ultimate result (when there is only one digit left) is 1.

  // Java program to check if

// a number is Magic number.

public static boolean isMagic(int n)

            int sum = 0;        

            // Note that the loop continues

            // if n is 0 and sum is non-zero.

            // It stops when n becomes 0 and

            // sum becomes single digit.

            while (n > 0 || sum > 9)

            {

                           if (n == 0)

                           {

                                          n = sum;

                                          sum = 0;

                           }

                           sum += n % 10;

                           n /= 10;

            }

           

            // Return true if sum becomes 1.

            return (sum == 1);

// Driver code

public static void main(String args[])

            int n = 1234;

            if (isMagic(n))

                           System.out.println("Magic Number");

                          

            else

                           System.out.println("Not a magic Number");

class InvalidAgeException  extends Exception  

    public InvalidAgeException (String str)  

// calling the constructor of parent Exception  

        super(str);  

70. Write a Java program to create and throw custom exceptions.

// class that uses custom exception InvalidAgeException  

public class TestCustomException1  

    // method to check the age  

    static void validate (int age) throws InvalidAgeException{    

       if(age < 18){  

        // throw an object of user defined exception  

        throw new InvalidAgeException("age is not valid to vote");    

       else {   

        System.out.println("welcome to vote");   

        }   

    // main method  

    public static void main(String args[])  

        try  

        {  

            // calling the method   

            validate(13);  

        catch (InvalidAgeException ex)  

            System.out.println("Caught the exception");  

            // printing the message from InvalidAgeException object  

            System.out.println("Exception occured: " + ex);  

        System.out.println("rest of the code...");    

71. Write a Java program to rotate arrays 90 degree clockwise by taking matrices from user input.

public class RotateMatrixClockwise  

public static void main(String args[])  

//matrix to rotate   

int a[][]= {{1,2,3},{4,5,6},{7,8,9}};    

System.out.println("Original Matrix: \n");  

//loop for rows  

for(int i=0;i<3;i++)  

//loop for columns  

for(int j=0;j<3;j++)  

//prints the elements of the original matrix  

System.out.print(" "+a[i][j]+"\t");  

System.out.println("\n");  

System.out.println("Rotate Matrix by 90 Degrees Clockwise: \n");  

for(int j=2;j>=0;j--)  

//prints the elements of the rotated matrix  

System.out.print(""+a[j][i]+"\t");  

72. Write a java program to check if any number given as input is the sum of 2 prime numbers.        

// C program to check if a prime number

// can be expressed as sum of

// two Prime Numbers

#include <stdio.h>

#include <math.h>

#include <stdbool.h>

// Function to check whether a number

// is prime or not

bool isPrime(int n)

            if (n <= 1)

                           return false;

            for (int i = 2; i <= sqrt(n); i++)

                           if (n % i == 0)

                                          return false;

            return true;

// Function to check if a prime number

bool isPossible(int N)

            // if the number is prime,

            // and number-2 is also prime

            if (isPrime(N) && isPrime(N - 2))

                           return true;

            int n = 13;

            if (isPossible(n))

                           printf("%s", "Yes");

                           printf("%s", "No");

            return 0;

73. Write a Java program for solving the Tower of Hanoi Problem.

 // Java recursive program to solve tower of hanoi puzzle

            // Java recursive function to solve tower of hanoi puzzle

            static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)

                           if (n == 1)

                                          System.out.println("Move disk 1 from rod " + from_rod + " to rod " +to_rod);

                                          return;

                           towerOfHanoi(n-1, from_rod, aux_rod, to_rod);

                           System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " +to_rod);

                           towerOfHanoi(n-1, aux_rod, to_rod, from_rod);

            }     

            // Driver method

            public static void main(String args[])

                           int n = 4; // Number of disks

                           towerOfHanoi(n, \'A\', \'C\', \'B\'); // A, B and C are names of rods

74. Implement Binary Search in Java using recursion.

// Java Program to Illustrate Recursive Binary Search

// Importing required classes

import java.util.*;

// Main class

class GFG {

            // Method 1

            // Recursive binary search

            // Returns index of x if it is present

            // in arr[l..r], else return -1

            int binarySearch(int arr[], int l, int r, int x)

                           // Restrict the boundary of right index

                           // and the left index to prevent

                           // overflow of indices

                           if (r >= l && l <= arr.length - 1) {

                                          int mid = l + (r - l) / 2;

                                          // If the element is present

                                          // at the middle itself

                                          if (arr[mid] == x)

                                                         return mid;

                                          // If element is smaller than mid, then it can

                                          // only be present in left subarray

                                          if (arr[mid] > x)

                                                         return binarySearch(arr, l, mid - 1, x);

                                          // Else the element can only be present

                                          // in right subarray

                                          return binarySearch(arr, mid + 1, r, x);

                           // We reach here when element is not present in

                           // array

                           return -1;

            // Method 2

            // Main driver method

                           // Creating object of above class

                           GFG ob = new GFG();

                           // Custom input array

                           int arr[] = { 2, 3, 4, 10, 40 };

                           // Length of array

                           int n = arr.length;

                           // Custom element to be checked

                           // whether present or not

                           int x = 10;

                           // Calling above method

                           int result = ob.binarySearch(arr, 0, n - 1, x);

                           // Element present

                           if (result == -1)

                                          // Print statement

                                          System.out.println("Element not present");

                           // Element not present

                           else

                                        // Print statement

                                          System.out.println("Element found at index "

                                                                                                      + result);

75. Is delete, next, main, exit or null keyword in java?

No, these keywords do not exist in Java. Delete, Next, Exit are the operations performed in the Java program, Main is the predefined method, and Null is the default String type.

With this we are done with the first section that is Basic Java Interview Question, Now, lets move on to our next section of Intermediate Java Interview Questions.

Java Interview Coding Questions For Intermediate

Now, let's have a look at some of the most asked Java technical interview questions for intermediate experienced professionals.

76. What is JDK? Mention the variants of JDK?

JDK is an abbreviation for Java Development Kit. It is a combined Package of JRE and Developer tools used for designing Java Applications and Applets. Oracle has the following variants.

  • JDK Standard Edition
  • JDK Enterprise Edition
  • JDK Micro Edition

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

JVM has a Just in Time (JIT) compiler tool that converts all the Java source code into the low-level compatible machine language. Therefore, it runs faster than the regular application.

JRE has class libraries and other JVM supporting files. But it doesn’t have any tool for java development such as compiler or debugger.

JDK has tools that are required to write Java Programs and uses JRE to execute them. It has a compiler, Java application launcher, and an applet viewer.

78. What is a JIT compiler?

JIT compiler refers to Just in Time compiler. It is the simplest way of executing the computer code that takes in compilation during the execution of a program rather than before performance. It commonly uses bytecode translation to machine code. It is then executed directly.

79. What are Brief Access Specifiers and Types of Access Specifiers?

Access Specifiers are predefined keywords used to help JVM understand the scope of a variable, method, and class. We have four access specifiers.

  • Public Access Specifier 
  • Private Access Specifier 
  • Protected Access Specifier 
  • Default Access Specifier

80. How many types of constructors are used in Java?

There are two types of constructors in Java .

Parameterized Constructors: Parameterized constructor accepts the parameters with which users can initialize the instance variables. Users can initialize the class variables dynamically at the time of instantiating the class.

Default constructors: This type doesn’t accept any parameters; rather, it instantiates the class variables with their default values. It is used mainly for object creation.

81. Can a constructor return a value?

Yes, A constructor can return a value. It replaces the class's current instance implicitly; you cannot make a constructor return a value explicitly.

82. Explain ‘this’ keyword in Java.

The term "this" is a particular keyword designated as a reference keyword. The "this" keyword is used to refer to the current class properties like method, instance, variable, and constructors.

83. Explain ‘super’ keyword in Java.

The term "super" is a particular keyword designated as a reference keyword. The "super" keyword refers to the immediate parent class object.

84. Explain Method Overloading in Java.

The process of creating multiple method signatures using one method name is called Method Overloading in Java. Two ways to achieve method overloading are:

  • Varying the number of arguments
  • Changing the return type of the Method 

85. Can we overload a static method?

No, Java does not support the Overloading of a static method. The process would throw an error reading "static method cannot be referenced."

86. Define Late Binding.

Binding is a process of unifying the method call with the method's code segment. Late binding happens when the method's code segment is unknown until it is called during the runtime. 

87. Define Dynamic Method Dispatch.

The Dynamic method dispatch is a process where the method call is executed during the runtime. A reference variable is used to call the super-class. This process is also known as Run-Time Polymorphism.     

88. Why is the delete function faster in the linked list than an array?

Delete Function is faster in linked lists in Java as the user needs to make a minor update to the pointer value so that the node can point to the next successor in the list

89. Give a briefing on the life cycle of a thread.

The life cycle of a thread includes five stages, as mentioned below.

  • New Born State
  • Runnable State
  • Running State
  • Blocked State

90. Explain the difference between >> and >>> operators.

Although they look similar, there is a massive difference between both.

  • >> operator does the job of right shifting the sign bits
  • >>> operator is used in shifting out the zero-filled bits

91. Brief the life cycle of an applet.

The life cycle of an applet involves the following.

  • Initialization

92. Why are generics used in Java Programming?

Compile-time type safety is provided by using generics. Compile-time type safety allows users to catch unnecessary invalid types at compile time. Generic methods and classes help programmers specify a single method declaration, a set of related methods, or related types with an available class declaration. 

93. Explain the Externalizable interface.

The Externalizable interface helps with control over the process of serialization. An "externalisable" interface incorporates readExternal and writeExternal methods.

94. What is the Daemon Thread?

The Daemon thread can be defined as a thread with the least priority. This Daemon thread is designed to run in the background during the Garbage Collection in Java.

The setDaemon() method creates a Daemon thread in Java.

95. Explain the term enumeration in Java.

Enumeration or enum is an interface in Java . Enum allows the sequential access of the elements stored in a collection in Java.

96. Why is Java is Dynamic?

Java is designed to adapt to an evolving environment. Java programs include a large amount of runtime information that is used to resolve access to objects in real-time. 

97. Can you run a code before executing the main method?

Yes, we can execute any code, even before the main method. We will be using a static block of code when creating the objects at the class's load time. Any statements within this static block of code will get executed at once while loading the class, even before creating objects in the main method.

98. How many times is the finalize method called?

The finalize method is called the Garbage collector. For every object, the Garbage Collector calls the finalize() method just for one time.

Java Interview Questions for Experienced

Now, lets move on to our last section of Advanced Core Java Interview Questions which is primarly useful for experienced and working professionals.

99. Can "this" and "super" keywords be used together?

No, "this" and "super" keywords should be used in the first statement in the class constructor. The following code gives you a brief idea.

public class baseClass {  

     baseClass() {  

         super();   

         this();  

         System.out.println(" baseClass object is created");  

     public static void main(String []args){  

         baseClass bclass = new baseClass();  

100. What is a JSP page?

JSP is an abbreviation for Java Servlet Page. The JSP page consists of two types of text.

  • Static Data 
  • JSP elements

101. What is JDBC?

JDBC is an abbreviation for Java Database Connector.

JDBC is an abstraction layer used to establish connectivity between an existing database and a Java application

102. Explain the various directives in JSP.

Directives are instructions processed by JSP Engine. After the JSP page is compiled into a Servlet, Directives set page-level instructions, insert external files, and define customized tag libraries. Directives are defined using the symbols below:

start with "< %@" and then end with "% >" 

The various types of directives are shown below:

  • Include directive

It includes a file and combines the content of the whole file with the currently active pages.

  • Page directive

Page Directive defines specific attributes in the JSP page, like the buffer and error page.

Taglib declares a custom tag library, which is used on the page.

103. What are the observer and observable classes?

Objects that inherit the "Observable class" take care of a list of "observers." 

When an Observable object gets upgraded, it calls the update() method of each of its observers. 

After that, it notifies all the observers that there is a change of state. 

The Observer interface gets implemented by objects that observe Observable objects.

104. What is Session Management in Java?

A session is essentially defined as the random conversation's dynamic state between the client and the server. The virtual communication channel includes a string of responses and requests from both sides. The popular way of implementing session management is establishing a session ID in the client's communicative discourse and the server.

105. Briefly explain the term Spring Framework.

Spring is essentially defined as an application framework in Java and inversion of control containers for Java. The spring framework creates enterprise applications in Java. Especially useful to keep in mind that the spring framework's central features are essentially conducive to any Java application.

106. How to handle exceptions in Spring MVC Framework?

Spring MVC has two approaches for handling the exceptions:

  • Exception handler method: In this kind of exception handling, the user will get the @ExceptionHandler annotation type used to annotate a method to handle exceptions.
  • XML Configuration: The user can use the SimpleMappingExceptionResolver bean in Spring’s application file and map the exception.

107. What is JCA in Java?

Java Cryptography Architecture gives a platform and provides architecture and application programming interfaces that enable decryption and encryption. 

Developers use Java Cryptography Architecture to combine the application with the security applications. Java Cryptography Architecture helps in implementing third party security rules and regulations. 

Java Cryptography Architecture uses the hash table, encryption message digest, etc. to implement the security.

108. Explain JPA in Java.

The Java Persistence API enables us to create the persistence layer for desktop and web applications. Java Persistence deals in the following:

  • Java Persistence API
  • Query Language
  • Java Persistence Criteria API
  • Object Mapping Metadata

109. Explain the different authentications in Java Servlets.

Authentication options are available in Servlets: There are four different options for authentication in servlet:

Basic Authentication: 

Usernames and passwords are given by the client to authenticate the user.

Form-based authentication: 

In this, the login form is made by the programmer by using HTML.

Digest Authentication: 

It is similar to basic authentication, but the passwords are encrypted using the Hash formula. Hash Formula makes digest more secure.

Client certificate Authentication:

It requires that each client accessing the resource has a certificate that it sends to authenticate itself. Client Authentication requires the SSL protocol.

110. Explain FailFast iterator and FailSafe iterator along with examples for each.

FailFast iterators and FailSafe iterators are used in Java Collections. 

FailFast iterators do not allow changes or modifications to the Java Collections, which means they fail when the latest element is added to the collection or an existing element gets removed from the collection. The FailFast iterators tend to fail and throw an exception called ConcurrentModificationException.

Ex: ArrayList, HashMap

Whereas, on the other hand, FailSafe iterators allow changes or modifications to be done on the Java Collections. It is possible, as the FailSafe iterators usually operate on the cloned copy of the collection. Hence, they do not throw any specific exception.

Ex: CopyOnWriteArrayList

111. How do we reverse a string?

The string can be reversed by using the following program.

package simplilearnJava;

public class StringReverse {

public static void main(String args[]) {

String str = "Simplilearn";

String reverse = new StringBuffer(str).reverse().toString();

System.out.printf("Actual Word: %s, Word after reversing %s", str, reverse);

public static String reverse(String source) {

if (source == null || source.isEmpty()) {

return source;

String reverse = "";

for (int i = source.length() - 1; i >= 0; i--) {

reverse = reverse + source.charAt(i);

return reverse;

Expected Output:

Actual Word: Simplilearn, Word after reversing nraelilpmiS

112. Write a program to find the square root of a number.

The Square root of a number can be found by using the following program.

import java.util.Scanner;

public class SRoot {

try (Scanner sc = new Scanner(System.in)) {

System.out.println("Input a number to find square root: ");

double square = sc.nextDouble();

double squareRoot = Math.sqrt(square);

System.out.printf("The square root is: %f ", squareRoot);

Input a number to find square root: 

The square root is: 5

113. Write a program that detects the duplicate characters in a string.

The program that finds the duplicate elements in a string is written below:

import java.util.HashMap;

import java.util.Map;

import java.util.Set;

public class FindDuplicate {

printDuplicateCharacters("Simplilearn");

public static void printDuplicateCharacters(String word) {

char[] characters = word.toCharArray();

Map<Character, Integer> charMap = new HashMap<Character, Integer>();

for (Character ch : characters) {

if (charMap.containsKey(ch)) {

charMap.put(ch, charMap.get(ch) + 1);

charMap.put(ch, 1);

Set<Map.Entry<Character, Integer>> entrySet = charMap.entrySet();

System.out.printf("List of duplicate characters in String '%s' %n", word);

for (Map.Entry<Character, Integer> entry : entrySet) {

if (entry.getValue() > 1) {

System.out.printf("%s: %d %n", entry.getKey(), entry.getValue());

Expected output:

List of duplicate characters in String 'Simplilearn.' 

114. Write a Program to remove duplicates in an ArrayList.

The following program can be implemented to remove duplicate elements in an ArrayList

import java.util.ArrayList;

import java.util.LinkedHashSet;

import java.util.List;

public class ArrayDuplicate {

List<Integer> num = new ArrayList<Integer>();

num.add(1);

num.add(2);

num.add(3);

num.add(4);

num.add(5);

num.add(6);

System.out.println("Your list of elements in ArrayList : " + num);

Set<Integer> primesWithoutDuplicates = new LinkedHashSet<Integer>(num);

num.clear();

num.addAll(primesWithoutDuplicates);

System.out.println("list of original numbers without duplication: " + num);

Your list of elements in ArrayList : [1, 2, 3, 4, 5, 6, 3, 4, 5, 6]

list of original numbers without duplication: [1, 2, 3, 4, 5, 6]

115. Find the word count in a string using HashMap Collection.

The following program can be used for word count.

public class WordCount {

public static void main(String[] args) {

String str = "Hello World, Welcome to Simplilearn";

String[] split = str.split(" ");

HashMap<String, Integer> map = new HashMap<String, Integer>();

for (int i = 0; i < split.length; i++) {

if (map.containsKey(split[i])) {

int count = map.get(split[i]);

map.put(split[i], count + 1);

map.put(split[i], 1);

System.out.println(map);

{Hello=1, Simplilearn=1, Welcome=1, to=1, World,=1}

116. Write a program to find the Second Highest number in an ArrayList

The following program can be used to find the second biggest number in an array list.

public class NextHighest {

public static void main(String[] args)

        int array[] = { 1, 2, 3, 4, 11, 12, 13, 14, 21, 22, 23, 24, 31, 32};

        int high = 0;

        int nextHigh = 0;

        System.out.println("The given array is:");

        for (int i = 0; i < array.length; i++)

            System.out.print(array[i] + "\t");

            if (array[i] > high)

            {

                nextHigh = high;

                high = array[i];

            }

            else if (array[i] > nextHigh)

                nextHigh = array[i];

        System.out.println("Second Highest is:" + nextHigh);

        System.out.println("Highest Number is: "  +high);

The given array is:

1 2 3 4 11 12 13 14 21 22 23 24 31 32

Second Highest is:31

The highest number is: 32

117. What is the difference between System.out, System.err, and System.in?

System.out and System.err represent the monitor by default and thus can be used to send data or results to the monitor. System.out is used to display normal messages and results. System.eerr is used to display error messages. System.in represents InputStream object which by default represents standard input device, i.e., keyboard.

118. Could you provide some implementation of a Dictionary having a large number of words?

The simplest implementation that can be given is that of a List wherein one can place ordered words and perform a Binary search. The other implementation with a better search performance is HashMap where the key is used as the first character of the word and the value as a LinkedList.

Up another level, there are HashMaps like:

a (key) -> hashmap (key-aa , value (hashmap(key-aaa,value)

b (key) -> hashmap (key-ba , value (hashmap(key-baa,value)

z (key) -> hashmap (key-za , value (hashmap(key-zaa,value)

Up to n levels where n is the average size of the word in the dictionary.

119. How would you tackle it if you might have to encounter pattern programs in Java?

Solution - Top 25 Most Frequently asked Pattern Programs in Java

With this, we have come to the end of this Java Interview Questions article. Moving ahead, we will look into the next crucial steps that you could pursue, to master Java.

120. What do you understand by an instance variable and a local variable?

Generally, instance variables are declared in a class but outside methods whereas a local variable is declared within the blocks of code.

//Local Variable

import Java.io.*;

class Main {

int var = 145;

System.out.println("Local Variable: " + var);

//Instance variable

public int value = 12;

Main va = new Main();

System.out.println("My value is: " + va.value);

121. Can the main method be overloaded?

Yes, the main method can be overloaded as many times as we want. Nevertheless, JVM prefers to call the main method with the help of its predefined calling method. 

    public static void main(String args[]) {

        System.out.println(" Main Method");

    public static void main(int[] args){

        System.out.println("Overloaded Integer array Main Method");

    public static void main(char[] args){

        System.out.println("Overloaded Character array Main Method");

    public static int main(double[] args){

        System.out.println("Overloaded Double array Main Method");

    public static void main(float args){

        System.out.println("Overloaded float Main Method");

122. Comment on method overloading and overriding by citing relevant examples.

Method overloading occurs during the compile time, whereas method overriding occurs during the run time. Static binding is used during overloading, whereas dynamic binding is used during methods overriding.

//Function overloading

void addPodium(int a, int b)

System.out.println(a + b);

float addPodium(float a, float b, float c)

System.out.println(a + b + c);

//Function overriding

class Parent {

    void show()

        System.out.println("I am Parent");

class Child extends Parent {

        System.out.println("I am Child");

    public static void main(String[] args)

        Parent obja = new Parent();

        obja.show();

        Parent objb = new Child();

        objb.show();

123. A single try block and multiple catch blocks can co-exist in a Java Program. Explain.

One or more catch blocks can follow a try block. Each catch block must have a unique exception handler. So, if you want to perform multiple tasks in response to various exceptions, use the Java multi-catch block.

124. Do final, finally and finalize keywords have the same function?

No, final, finally and finalize keywords have different functionalities.

Final is used to restrict classes, variables, or methods, the final keyword.

Finally is used to execute the code written inside the block without handling any exceptions.

Finalize is used to call the function of the implementation of cleaning the garbage collection of an object. 

125. When can you use the "super" keyword?

Basically, the super keyword is used to refer to the parent class. When there are the same fields in both parent and child classes, then one can use a super keyword to access data members of the parent class.

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

In the case of a shallow copy, primitive data types are copied, whereas in the case of a deep copy along with primitive data types the object references are also copied.

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

An abstract class can have a combination of both abstract and non-abstract methods, whereas an interface has only abstract methods in it.

128. What are the different ways of thread usage? 

There are two ways to define and implement a thread in Java. They are by implementing the runnable interface and extending the thread class.

Extending the Thread class

class InterviewBitThreadExample extends Thread{  

   public void run(){  

       System.out.println("Thread runs...");  

   public static void main(String args[]){  

       InterviewBitThreadExample ib = new InterviewBitThreadExample();  

       ib.start();  

Implementing the Runnable interface

class InterviewBitThreadExample implements Runnable{  

       Thread ib = new Thread(new InterviewBitThreadExample()); 

Implementing a thread using the method of Runnable interface is more preferred and advantageous as Java does not have support for multiple inheritances of classes.

start() method is used for creating a separate call stack for the thread execution. Once the call stack is created, JVM calls the run() method for executing the thread in that call stack.

129. What is the difference between the ‘throw' and ‘throws' keyword in Java?

The throw keyword is often used to explicitly throw an exception. It can only throw one exception at a time whereas throws can be used to declare multiple exceptions.

130. Identify the output of the below Java program and Justify your answer.

        Scaler s = new Scaler(5);

class InterviewBit{

    InterviewBit(){

        System.out.println(" Welcome to InterviewBit ");

class Scaler extends InterviewBit{

    Scaler(){

        System.out.println(" Welcome to Scaler Academy ");

    Scaler(int x){

        this();

        super();

        System.out.println(" Welcome to Scaler Academy 2");

The above code will throw the compilation error. It is because the super() is used to call the parent class constructor. But there is the condition that super() must be the first statement in the block. Now in this case, if we replace this() with super() then also it will throw the compilation error. Because this() also has to be the first statement in the block. So in conclusion, we can say that we cannot use this() and super() keywords in the same block.

131. Java works as a “pass by value” or “pass by reference” phenomenon?

Java works as a “pass by value” phenomenon, because “pass by reference” needs the help of pointers. But there are no pointers in Java.

132. How to not allow serialization of attributes of a class in Java?

One approach to not allow serialization of attributes of a class in Java is by using writeObject() and readObject() methods in the subclass and throwing a not Serializable exception.

133. What are the default values assigned to variables and instances in Java?

By default, for a numerical value it is 0, for the boolean value it is false and for objects it is NULL.

134. What do you mean by data encapsulation?

Data encapsulation is one of the properties of OOPS concepts, where all the data such as variables and methods are enclosed together as a single unit.

135. Can you tell the difference between equals() method and equality operator (==) in Java?

Equality operator (==) is used to check the equality condition between two variables. But the equals() method is used to check the equality condition between two objects.

136. How is an infinite loop declared in Java?

An infinite loop can be declared in Java by breaking the logic in the instruction block.  For example,

for(int i = 1; i > 0; i++)

//statements

The above code forms an infinite loop in Java.

137. Briefly explain the concept of constructor overloading

The concept of constructor overloading refers to having multiple methods in a class with their name being the same as the class name. The difference lies in the set of parameters passed to the functions.

138. Explain the use of the final keyword in variable, method and class.

In Java, one can apply the final keyword to a variable, methods, and class. With the help of the final keyword, the variable turns out to be a constant, the method cannot be inherited and the class cannot be overridden.

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

Yes, there is a possibility that the ‘finally’ block cannot get executed. Here are some of the cases where the above situation occurs.

  • During the time of fatal errors such as memory exhaustion, memory access error, etc.
  • During the time of using System.exit()

140. Difference between static methods, static variables, and static classes in Java.

A variable, method, or class can be made static by using the static keyword. A static class cannot be instantiated. When both objects or instances of a class share the same variables, this is referred to as static variables. Static methods are simply methods that refer to the class in which they are written.

141. What is the main objective of garbage collection?

The main goal of using garbage collection is to free the heap memory by eliminating unnecessary objects.

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

Because of security, synchronization, concurrency, caching, and class loading, the String is immutable in Java. The reason for making string final would be to destroy its immutability and help stop others from trying to extend it. String objects are cached in the String pool, making them immutable.

143. Which of the below generates a compile-time error? State the reason.

int[] n1 = new int[0];

boolean[] n2 = new boolean[-200];

double[] n3 = new double[2241423798];

char[] ch = new char[20];

We get a compile-time error in line 3. The error we will get in Line 3 is - the integer number too large. It is because the array requires size as an integer.  And Integer takes 4 Bytes in the memory. And the number (2241423798) is beyond the capacity of the integer. The maximum array size we can declare is - (2147483647).

Because the array requires the size in integer, none of the lines (1, 2, and 4) will give a compile-time error. The program will compile fine. But we get the runtime exception in line 2. The exception is - NegativeArraySizeException. 

Here what will happen is - At the time when JVM will allocate the required memory during runtime then it will find that the size is negative. And the array size can’t be negative. So the JVM will throw the exception.

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

The string class is immutable but the other two are mutable in nature. StringBuffer is synchronous whereas the StringBuilder is asynchronous. String uses string pool as memory storage whereas the other two use heap memory for storage purposes.

145. What is a Comparator in Java?

A comparator is an interface, which is used to sort the objects. 

146. In Java, static as well as private method overriding is possible. Comment on the statement.

In Java, you could indeed override a private or static method. If you create a similar method in a child class with the same return type and method arguments, it will hide the super class method; this is known as method hiding. Similarly, you cannot override a private method in a subclass because it is not accessible from that.

147. What makes a HashSet different from a TreeSet?

In a HashSet, the elements are unsorted and work faster than a Tree set.  It is implemented using a hash table.

148. Why is the character array preferred over string for storing confidential information?

Because Strings are immutable, any change will result in the creation of a new String, whereas char[] allows you to set all of the elements to blank or zero. So storing a password in a character array clearly reduces the security risk of password theft.

149. What are the differences between HashMap and HashTable in Java?

150. what is the importance of reflection in java.

Reflection is a property of Java, enabling the Java code to inspect itself. A Java class, for example, can get the names of all its members and showcase them.

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

There are different types of thread properties in Java. They are MIN_PRIORITY, MAX_PRIORITY, and NORM_PRIORITY. By default, the thread is assigned NORM_PRIORITY.

152. What is the ‘IS-A ‘ relationship in OOPs Java?

‘IS-A’ relationship is related to the Inheritance property of OOPs Java. It is a kind of parent-child relationship that is established between two classes.

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

It is not a pure object-oriented language because it supports primitive data types like int, double, and char, which are not objects, and it supports static methods and variables.

154. Can static methods be overridden?

No, static methods cannot be overridden in Java.

155. What are the different ways of thread usage?

Two ways to use threads in Java one is by extending the Thread class or by implementing the Runnable interface. Another way to use threads in Java is by using the Executor framework, which provides a higher level of abstraction for managing threads. 

156. How do you achieve Object Cloning in Java?

Creating a new object with the same state as an existing object called Object Cloning in Java. This can be achieved by implementing the Cloneable interface and overriding the clone() method in the class. 

157. What is a Java Virtual Machine?

It is an abstract machine that provides a runtime environment for Java programs to run. The JVM interprets the compiled Java code and executes it on the underlying operating System.

158. What gives Java its 'write once and run anywhere' nature?

Java's 'write once and run anywhere' nature is achieved by using Java Virtual Machine (JVM) and bytecode. Java code is compiled into bytecode, which can be executed on any platform that has a JVM installed. 

159. What are the advantages of Packages in Java?

Packages in Java provide a way to organize classes and interfaces into namespaces. This helps to avoid naming conflicts and makes it easier to manage large codebases. Packages provide a way to create reusable code through the use of libraries.

160. Explain static variables with examples and a diagram.

A static variable in Java is a variable that is associated with the class rather than an instance of the class. This means that all instances of the class share the same static variable. They are declared using the static keyword.

public class Example {

    static int count = 0;

    public Example() {

        count++;

Diagram - The diagram below illustrates the relationship between the class and the static variable:

          +----------+

Example | count=0 |

          | |

Instance1 | |

Instance2 | |

161. Explain static block

A static block in Java is a block of code that is executed when the class is loaded into memory. Static blocks are enclosed in curly braces and are marked with the static keyword. 

162. Difference between static (class) method and instance method

The main difference between a static method and an instance method in Java is that a static method is associated with the class, while an instance method is associated with an instance of the class. 

163. How can constructor chaining be done using this keyword?

It is the process of calling one constructor from another constructor in the same class. This can be achieved using this keyword.

164. Which class is the superclass for all the classes?

The Object class is the only superclass for all classes in Java.

165. Why are multiple inheritances not supported in Java?

Multiple inheritances are not supported in Java because it can lead to several problems, including the diamond problem and name conflicts. 

166. Why is method overloading not possible by changing the return type in Java?

It is not possible by changing the return type in Java because the return type of a method is not part of its signature.

167. What is method overloading with type promotion?

Method overloading with type promotion in Java is the process of defining multiple methods in the same class with the same name but different parameter types.

168. Can we change the scope of the overridden method in the subclass?

No, we cannot change the scope of the overridden method in the subclass.

169. Can you have virtual functions in Java?

I n Java, all non-static methods are virtual functions by default.

170. What is the covariant return type?

The covariant return type is a feature introduced in Java 5 that allows a subclass method to return a type that is a subclass of the return type of the overridden method in the superclass.

171. What is the final variable?

A final variable in Java is a variable that cannot be changed once it is initialized.

172. What is the final method?

A final method in Java is a method that cannot be overridden in a subclass. 

173. What is the final class?

A final class in Java is a class that cannot be subclassed.

174. What is the final blank variable?

The final blank variable in Java is a final variable that is not initialized when it is declared.

175. Difference between the final method and the abstract method

The main difference between a final method and an abstract method in Java is that a final method cannot be overridden in a subclass, while an abstract method must be overridden in a subclass.

176. Differences between Heap and Stack Memory in Java

Heap and Stack are two types of memory in Java used for storing data. Heap memory is used for storing objects, while Stack memory is used for storing local variables and method calls. One of the main differences between Heap and Stack memory is their allocation and deallocation. Heap memory is allocated when an object is created and deallocated when there are no more references to that object. Stack memory, on the other hand, is allocated when a method is called and deallocated when the method returns.

Another difference between Heap and Stack memory is their size. Heap memory is larger than Stack memory because it is used for storing objects. Stack memory is smaller because it is used for storing local variables and method calls only. 

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

Instance variables and local variables are two types of variables in Java. Instance variables are declared inside a class but outside any method. They are used to store data that is specific to an object. Local variables, on the other hand, are declared inside a method and are used to store temporary data that is required only within that method.

One of the main differences between instance variables and local variables is their scope. Instance variables have a larger scope than local variables. The second difference between instance variables and local variables is their initialization. Instance variables are initialized automatically by default values if not initialized explicitly, while local variables must be initialized explicitly before they can be used. 

 178. What is a JIT Compiler?

JIT (Just-In-Time) compiler is a part of the Java Virtual Machine (JVM) that compiles Java bytecode into native machine code at run time.

179. Can you tell the difference between the equals() method and equality operator (==) in Java?

Equals() method and equality operator (==) are used for comparing objects in Java. However, they differ in their functionality. Equals() method is used to compare the contents of two objects, while the equality operator (==) is used to compare the references of two objects.

When we use the equality operator (==) to compare two objects, it checks if both objects refer to the same memory location. On the other hand, when we use the Equals() method, it checks if the contents of the two objects are equal.

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

Shallow copy and deep copy are two types of object copying in Java. SC creates a new object with the same values as the original object, while deep copy creates a new object with new values.

181. Does Java work as a "pass by value" or "pass by reference" phenomenon?

Java works as a "pass-by-value" phenomenon. This means that when we pass an object to a method, a copy of the reference to that object is passed, not the actual object.

For example, let's consider the following code:

public void changeValue(int x) {

int num = 10;

changeValue(num);

System.out.println(num);

In this code, we pass the value of num to the changeValue() method. However, when we change the value of x inside the method, it does not affect the value of num outside the method. This is because Java passes a copy of the value of num, not the actual object. 

182. Why Does Java Array Index Start with 0?

In Java, array indexing starts with 0. This is because an array is a contiguous block of memory where each element occupies a fixed amount of space. It is the offset from the start of the array.

Consider the following code:

int[] arr = new int[5];

arr[0] = 10;

arr[1] = 20;

arr[2] = 30;

arr[3] = 40;

arr[4] = 50;

In this code, we declare an array of size five and assign values to each element. The index of the first element is coming 0, and the last element index is coming 4, which is the size of the array minus 1. 

183. Can you explain the Java thread lifecycle?

Java thread life cycle consists of several states, including New, Runnable, Blocked, Waiting, Timed Waiting, and Terminated. 

The New State represents a thread that has been created but not started yet. The Runnable state represents a thread that is ready to run but may not be scheduled to run by the operating System. The Blocked state represents a thread that is waiting for a monitor lock to be released. The Waiting state represents a thread that is waiting for another thread to perform a specific action. The Timed Waiting state represents a thread that is waiting for a specific amount of time to elapse. The Terminated state represents a thread that has completed its execution. 

184. What are the possible ways of making objects eligible for garbage collection (GC) in Java? 

In Java, objects are automatically garbage collected when they are no longer referenced. However, we can also make objects eligible for garbage collection manually using the System.gc() method or by setting the object reference to null.

MyObject obj = new MyObject();

obj = null;

System.gc();

In this code, we create an object of the MyObject class and then set the object reference to null. We then call the System.gc() method to request the garbage collector to run. 

185. What are the different categories of Java Design patterns?

Java Design Patterns can be categorized into three categories: Creational, Structural, and Behavioral.

Creational patterns are used for creating objects. Some examples of Creational patterns are Singleton, Factory, and Abstract Factory.

Structural patterns are used for assembling objects and creating relationships between them. Some examples of Structural patterns are Adapters, bridges, and Composites.

Behavioral patterns are used for managing algorithms, relationships, and responsibilities between objects. Some examples of Behavioral patterns are Observer, Strategy, and Template Methods. 

186. List the features of the Java Programming language.

Java is a popular programming language that is widely used for developing applications. Some of the features of Java programming language are:

  • Platform Independence: Java code can run on any platform that has a JVM installed.
  • Object-Oriented: Java is an object-oriented programming language that supports encapsulation, inheritance, and polymorphism.
  • Memory Management: Java has automatic memory management, which means that it manages memory allocation and deallocation automatically.
  • Multithreading: Java supports multithreading, which allows multiple threads to run concurrently.
  • Security: Java has built-in security features that protect the System from malicious attacks.
  • Exception Handling: Java has a robust exception-handling mechanism that allows developers to handle errors and exceptions effectively.
  • Garbage Collection: Java has automatic garbage collection, which means that it automatically frees the memory.

Choose The Right Software Development Program

This table compares various courses offered by Simplilearn, based on several key features and details. The table provides an overview of the courses' duration, skills you will learn, additional benefits, among other important factors, to help learners make an informed decision about which course best suits their needs.

Program Name Full Stack Java Developer Career Bootcamp Automation Testing Masters Program Post Graduate Program in Full Stack Web Development Geo IN All Non-US University Simplilearn Simplilearn Caltech Course Duration 11 Months 11 Months 9 Months Coding Experience Required Basic Knowledge Basic Knowledge Basic Knowledge Skills You Will Learn 15+ Skills Including Core Java, SQL, AWS, ReactJS, etc. Java, AWS, API Testing, TDD, etc. Java, DevOps, AWS, HTML5, CSS3, etc. Additional Benefits Interview Preparation Exclusive Job Portal 200+ Hiring Partners Structured Guidance Learn From Experts Hands-on Training Caltech CTME Circle Membership Learn 30+ Tools and Skills 25 CEUs from Caltech CTME Cost $$ $$ $$$ Explore Program Explore Program Explore Program

Java Interview Questions are really important to go through before attending an interview. It helps you to put yourself on the safer side by getting you ready to be able to answer the questions asked in your interview. Now, the next step is to learn How to Become a Software Developer .

You can also explore and get familiar with interview questions and answers related to other backend languages like PHP, Python and Node.js Interview Questions.

If you're looking for more in-depth knowledge about the Java programming language and information on how to get certified as a web development professional developer , explore our Java training and certification programs, which Simplilearn’s experienced industry experts offer in real-time. In particular, check out our Full Stack Java Developer Career Bootcamp . This program can help you hone the right skills and make you career-ready in no time.

If you have any questions about this “Java Interview Questions” article, please leave them in the comments section, and our experts will answer them for you, at the earliest!

Find our Full Stack Java Developer Online Bootcamp in top cities:

About the author.

Ravikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

Recommended Resources

Top 60 C++ Interview Questions and Answers for 2024

Top 60 C++ Interview Questions and Answers for 2024

Kubernetes Interview Guide

Kubernetes Interview Guide

Top Java Collection Interview Questions and Answers for 2024

Top Java Collection Interview Questions and Answers for 2024

Top 150 Python Interview Questions and Answers for 2024

Top 150 Python Interview Questions and Answers for 2024

Top 80+ JavaScript Interview Questions and Answers for 2024

Top 80+ JavaScript Interview Questions and Answers for 2024

Cloud Computing Interview Guide

Cloud Computing Interview Guide

  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Ace the top 15 Java algorithm questions for coding interviews

Java Algorithm Questions for Coding Interviews

Finally, we add all lines’ time complexity, drop the leading constants and lower order terms, and find our Big O Complexity.

Almost ever interviewer will ask a question which calls for at least one type of searching or sorting, if not more. To help you prepare for these questions, we’ve included the following overview section to build foundational search/sort algorithm proficiency.

Note: It’s unlikely you’ll be prompted to use a certain algorithm in an interview. Instead, you must learn to recognize which algorithm to use based on keywords in the problem statement. As you practice, try to pinpoint which part of the problem statement would lead you to use the indicated algorithm.

2: Quicksort

Given an unsorted array of numbers, find K th smallest number in it.

Please note that it is the K th smallest number in the sorted order, not the K th distinct element.

Time Complexity: average O ( N ) O(N) O ( N ) or worst case O ( N 2 ) O(N^2) O ( N 2 )

We use Quicksort’s partitioning scheme to find the Kth smallest number. We recursively partition the input array and if, after partitioning, our pivot is at the K-1 index we have found our required number. If not, we choose one the following options:

  • If pivot’s position is larger than K-1, we recursively partition the array on numbers lower than the pivot.
  • If pivot’s position is smaller than K-1, we recursively partition the array on numbers greater than the pivot.

3: Binary Search

We are given a 2D array where all elements in any individual row or column are sorted. In such a matrix, we have to search or find the position of, a given key.

Time Complexity: O ( m + n ) O(m + n) O ( m + n )

We start from the upper right corner of the matrix and compare its value with the key. If they are equal, we have found the position of the key.

If the key is smaller than the current element, we move to the left one position. If the key is larger than the current element, we move right one position.

As the matrix is sorted, moving left always results in lower values than the current while moving down always results higher values. We continue this process until either we find the element or go out of the boundary of the matrix (which indicates that the key does not exist).

4. Merge Sort

Given the head pointer of a linked sort, sort the linked list in ascending order using merge sort, and return the new head pointer of the sorted linked list.

Time Complexity: O ( n l o g n ) O(nlogn) O ( n l o g n )

In the dividing step, we split our input linked list into two halves and keep doing so until there is a linked list of size 1 or 0. Linked lists of size 1 and 0 are always sorted. In the combining step, we merge sorted lists and keep doing so until we have a completely sorted list.

At each step, we divide our problem into two sub-problems. The size of each sub-problem is n 2 \frac n2 2 n ​ and the total cost of combining steps (merging sorted lists) is n n n .

5. Insertion Sort

Given the head pointer of a linked list, sort the linked list in ascending order using insertion sort. Return the new head pointer of the sorted linked list.

Time Complexity: O ( n 2 ) O(n^2) O ( n 2 )

While the original list is not empty:

Remove an element (say ‘X’) from the original list.

Insert ‘X’ at the correct sorted position in the sorted list.

To insert a node into the sorted linked list, we may need to scan the entire sorted list depending upon the node being inserted.

Using a HashMap, implement a function that takes an array arr , a number value , and the size of the array as an input and returns two numbers that add up to value .

Time Complexity: O ( n ) O(n) O ( n )

For all the elements in the arr array, we store the difference n - arr[i] in hmap .

Then with another iteration over arr , we check if any element of arr exists in the hmap , which means the difference of n and the number found ( n - arr[i] ) are also present.

Therefore, an array of size 2 called result is created to store the pair that sums up to n . If hmap contains an array element, result[] is updated, or else it is returned containing the default value.

Implement an isSubset() function to take two arrays as input and check whether an array is a subset of another given array.

Time Complexity: O ( m + n ) O(m+n) O ( m + n )

First, we iterate over arr2 and arr3 to see whether their elements can be found in arr1 .

At the back end, the values are checked against their hashed indices in arr1 .

Dynamic Programming: Memoization and Tabulation

Dynamic Programming is a central algorithm technique for the modern developer, as it focuses on breaking a problem into simpler sub-problems to achieve optimization. The more optimal the solution to sub-problems, the more optimal the overall solution is.

This is the foundation of recursive problem-solving and therefore will be asked by any good interviewer.

Dynamic Programming questions can either be solved from a Top-Down approach or a Bottom-Up approach, using either Memoization or Tabulation , respectively. Interviewers may ask for one or may leave it to your decision.

Below we’ll see an example of each so you’re prepared for any alternative.

8. The Knapsack Problem:

Imagine that you’re an adventurer with a knapsack looking over a dragon’s hoard.

Given two integer arrays that represent the weights and profits of N items, implement a function knapSack() that finds a subset of these items that will give us the maximum profit without their cumulative weight exceeding a given number capacity . Each item may only be selected once, which means when we get to it we can either skip it or put it in the knapsack.

Use the top-down approach with memoization.

Time Complexity: O ( N ∗ C ) O(N*C) O ( N ∗ C )

The function knapSack makes a lookupTable within the function that stores the maximum value that can be attained with maximum capacity (lines 29-35). This function calls the helper function knapsackRecursive (line 36). It returns the maximum value that can be attained using only the first i items, i.e., items at the currentIndex while keeping their total weight no more than weights.

We have two varying values ( capacity and currentIndex ), so we can use a two-dimensional array to store the results of all the solved subproblems in our recursive function knapsackRecursive .

We need to store results for every subarray, i.e., for every possible index and for every possible capacity. If the lookupTable[currentIndex][capacity] is already computed before (line 10), this value is immediately returned (line 11).

Otherwise, we call the function recursively:

With the item, saving the result in profit1 (line 17).

Without the item, saving the result in the variable, profit2 (line 21).

Out of the two, we return the result that is greater (as done on lines 23-24).

9. Staircase Problem

A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a function to count the number of possible ways that the child can run up the stairs.

Try to solve this one using a Bottom-Up approach with Tabulation.

We know that:

The total number of ways to reach the zero-step is 1 (line 6).

The total number of ways to reach the first step is 1 (line 7).

The total number of ways to reach the second step is 2 (line 8).

Hence, we fill up the lookupTable with these three values (lines 6-8).

We know that the total number of ways to reach any n th stair is by taking 1, 2, or 3 steps. Hence, the total number of ways to reach an n th stair would be equal to the sum of the total number of ways to reach [n-1] th step, number of ways to reach [n-2] th step, and the number of ways to reach the [n-3] th step.

So, the rest of the values of the lookupTable are filled by calculating the total number of ways to reach an nth step by summing the ways to reach the previous three steps (line 11).

The required value is then returned from the lookupTable (line 13).

Greedy Algorithms: Local Maximization

Greedy is an algorithmic technique where the solution is built one piece at a time, prioritizing immediate, obvious benefits at each choice. In other words, it seeks to maximize profit (the positive) and minimizes the cost (the negative).

This technique works on the idea that the locally optimal choice will contribute to the globally optimal solution. Below we’ll see a few interview questions to help you use this technique when required.

10: Change Machine Problem

You have to make such a change machine that only returns the change in the form of coins.

You are supplied with an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents), and pennies (1 cent). The user will enter any amount. For each amount, you have to return the minimum number of coins possible!

Line 3: A public array is given containing the set of coins available.

Line 6: The function getMinCoins() is defined; it has ArrayList as its return type and int amount as its parameter.

Line 9: The ArrayList of type Integer is allocated to store the change.

Lines 10-17: A for loop traverses the int[]coins array from beginning to end (given in descending order).

Line 12: Since the first index of coins has the maximum element, compare in the while condition whether this amount is greater than the max coin.

Line 14: If yes, subtract the max value coin from the amount given.

Line 15: Add this coin to the change list.

Line 17: When the largest coin becomes greater than the remaining amount, the while loop breaks and the value of i is incremented to move to the next (lesser value) coin.

Keep iterating this for loop, until the remaining amount can no longer be subdivided by the available coins.

11: Find the Egyptian Fraction

Every positive fraction can be represented as the sum of its unique unit fractions. A fraction is a unit fraction if the numerator is 1 and the denominator is a positive integer. For example, 1 3 \frac 13 3 1 ​ is a unit fraction. Such a representation is called Egyptian fraction.

Time Complexity: O ( l o g 3 ) O(log_3) O ( l o g 3 ​ )

For a given number of the form n d \frac nd d n ​ , where d > n, first find the greatest possible unit fraction, and then perform recursion for the remaining part.

For example, consider 6 14 \frac 6{14} 14 6 ​ . We first find the ceiling of 14 6 \frac {14}6 6 14 ​ , i.e., 3, so the first unit fraction becomes 1 3 \frac 13 3 1 ​ . Now subtract 1 3 \frac 13 3 1 ​ out of 6 14 \frac 6{14} 14 6 ​ and recur for 6 14 \frac 6{14} 14 6 ​ – 1 3 \frac 13 3 1 ​ .

We use the greedy algorithm because we want to reduce the fraction to a form where the denominator is greater than the numerator and the numerator doesn’t divide the denominator.

The method is to find the biggest unit fraction we can and subtract it from the remaining fraction. Doing subtractions always decreases this group of unit fractions, but it never repeats a fraction and eventually will stop, which is why we call this approach greedy.

Divide and Conquer:

Similar to Dynamic Programming, Divide and Conquer algorithms work by breaking down a problem into sub-problems. Where they differ is that Divide and Conquer algorithms solve each sub-problem then combine the results to form the ultimate solution whereas the sub-problems in Dynamic Programming are fully separate.

This is another staple type of algorithm that will be tested in your coding interview.

12: Euclidean Algorithm Problem

Given two integers a and b , calculate the largest number (GCD) that divides both of them without leaving a remainder.

Time Complexity: O ( l o g m i n ( a , b ) ) O(log min(a,b)) O ( l o g min ( a , b ))

  • Line 5: The algorithm starts by checking if the first number ( a , which was obtained by b \%ab%a in recursive calls) is 0.
  • Line 6: If that is the case, then return b .
  • Line 7: Otherwise, we make the next recursive call GCD(b % a, a) .

13: Missing number in Sorted Array

Given an array of contiguous integers starting from x , with one missing integer in between, and the size of the array, find the missing number!

Time Complexity: O ( l o g n ) O(log_n) O ( l o g n ​ )

Line 38: The driver program calls the function missingNumber() with int [] arr and int size as its parameters.

Line 6: Initialize the right and left limits.

Lines 9-10: Handles corner case 1. Return 1 if array’s 1st element is not equal to 1.

Line 12-18: Begin by finding the middle index of the array, if the element at middle is not equal to middle + 1 , and this is the first missing element, middle + 1 is the missing element.

Lines 21-26: If this is not the first missing element and arr[middle] is not equal to middle+1 , search in the right half. Otherwise, search in the left half of the array.

Line 28: Handles corner case 2. Return -1 if you end up traversing the whole array and no element is missing.

Graphs Algorithms:

For our final section we’ll look at problems to build proficiency with common graph-related questions. These questions are becoming increasingly popular in interviews due to their prevalence in social-media mapping, meaning now more than ever it’s key to come prepared with this practice.

14: Calculate the Number of Nodes in a Given Graph Level

Implement a function that returns the number of nodes at a given level of an undirected graph.

Time Complexity: O ( V + E ) O(V + E) O ( V + E )

The solution above modifies the visited array to store the level of each node. Later, it counts the nodes with the same level (lines 32-35).

In this code, while visiting each node, the level of the visited node is set with an increment in the level of its parent node, i.e.,

This is how the level of each node is determined (line 26).

15: Transpose a Graph

Implement a function that takes a directed graph as input and print its transpose.

First, you make another graph and start reversing it. Traverse the adjacency list of the given graph. When the program finds a vertex v in the adjacency list of vertex u (i.e., an edge from u to v in the given graph), add an edge from v to u in the transposedGraph , adding u in the adjacency list of vertex v of the new graph) (lines 9-13).

In line 19, the printGraph() function prints the graph to console. You can find its implementation in Graph.java file (lines 29-36).

More coding interview questions to ace algorithms:

  • Search in a rotated array
  • Find the median of two sorted arrays
  • Find duplicates in an array
  • The Dutch National Flag Problem
  • Find the longest common substring in a string
  • The Egg Drop Problem
  • Find the longest palindromic subsequence of a string
  • The Edit Distance Problem
  • Connect n pipes with the minimum cost
  • The Train Station Platform Problem
  • The Fractional Knapsack Problem
  • Find Kruskal’s minimum spanning tree
  • Find the peak element in an array
  • Shuffle the integers of an array
  • Search a graph breadth-first
  • Search a graph depth-first
  • Count the paths between two nodes
  • Print all connected components in a graph
  • Remove an edge of a graph
  • Implement topological sorting of a graph
  • Check if a graph is strongly connected
  • Check if a graph is Bipartite
  • Find the floor and ceiling of a number
  • Find the closest number in an array
  • Collect coins in the least steps
  • Find the maximum sum of two subarrays
  • The Coin Change Problem
  • The Partition Problem
  • Count element occurrence
  • The Sparse Search Problem

Where to go from here

Great work! Hopefully, you can already feel that pre-interview anxiety starting to melt away. While this was a deep dive into 15 of the most common algorithm questions, there are many more possibilities that may come up during your interview. Varied practice is essential to success in any coding interview.

If you want to practice your Java coding skills, then Educative-99 or Educative-77 in Java are the perfect places to go. Educative-99 is curated by expert developers for beginner developers in order to help them ace their Java coding and algorithm skills.

To master the underlying patterns behind coding interview problems, check out our course, Grokking Coding Interview Patterns in Java .

Interview roadmap

If you’re unsure where the road to your dream front-end dev job leads next, take a look at our free interview roadmap to help you get quickly.

Keep reading about interview prep

  • 5 tried and true techniques to prepare for a coding interview
  • Cracking the top Amazon coding interview questions

Learn in-demand tech skills in half the time

Skill Paths

Assessments

Learn to Code

Tech Interview Prep

Generative AI

Data Science

Machine Learning

GitHub Students Scholarship

Early Access Courses

For Individuals

Try for Free

Become an Author

Become an Affiliate

Earn Referral Credits

Frequently Asked Questions

Privacy Policy

Cookie Policy

Terms of Service

Business Terms of Service

Data Processing Agreement

Copyright © 2024 Educative, Inc. All rights reserved.

Javarevisited

Learn Java, Programming, Spring, Hibernate throw tutorials, examples, and interview questions

Topics and Categories

  • collections
  • multithreading
  • design patterns
  • interview questions
  • data structure
  • Java Certifications
  • jsp-servlet
  • online resources
  • jvm-internals

Monday, September 25, 2023

  • Top 50 Java Programs from Coding Interviews

Java Programming Interview Questions for 2 to 3 years

Review these 50 questions to crack your Java programming interview

by javinpaul

A list of frequently asked Java questions from programming job interviews.

cA9-wkkWif9KjVOo09g1D5s5OiE8KskLLfa-

Hello, everybody! Over the past few years, I have been sharing a lot of Java Interview questions and discussion individually. Many of my readers have requested that I bring them together so that they can have them in the same spot. This post is the result of that.

This article contains more than 50 Java Interview questions covering all important topics like Core Java fundamentals, Java Collection Framework , Java Multithreading and Concurrency , Java IO , JDBC , JVM Internals , Coding Problems , Object-Oriented programming , etc.

The questions are also picked up from various interviews and they are, by no means, very difficult. You might have seen them already in your phone or face-to-face round of interviews.

The questions are also very useful to review important topics like multithreading and collections. I have also shared some useful resources for further learning and improvement like The Complete Java MasterClass to brush up and fill gaps in your Java skills.

So what are we waiting for? Here is the list of some of the most frequently asked Java questions in interviews for both beginner and experienced Java developers.

50+ Java Interview Questions for 2 to 3 years Experienced Programmers

So, without wasting any more of your time, here is my list of some of the frequently asked Core Java Interview Question s for beginner programmers. This list focuses on beginners and less experienced devs, like someone with 2 to 3 years of experience in Java.

1) How does Java achieve platform independence? ( answer ) hint: bytecode and Java Virtual Machine

2) What is ClassLoader in Java? ( answer ) hint: part of JVM that loads bytecodes for classes. You can write your own.

3) Write a Java program to check if a number is Even or Odd? ( answer ) hint: you can use bitwise operator, like bitwise AND, remember, even the number has zero at the end in binary format and an odd number has 1 in the end.

4) Difference between ArrayList and HashSet in Java? ( answer ) hint: all differences between List and Set are applicable here, e.g. ordering, duplicates, random search, etc. See Java Fundamentals: Collections by Richard Warburton to learn more about ArrayList, HashSet and other important Collections in Java.

ueOwMAd5GBdw4blCOpEBpOdMOtcs-et6nPYA

5) What is double checked locking in Singleton? ( answer ) hint: two-time check whether instances is initialized or not, first without locking and second with locking.

6) How do you create thread-safe Singleton in Java? ( answer ) hint: many ways, like using Enum or by using double-checked locking pattern or using a nested static class.

7) When to use the volatile variable in Java? ( answer ) hint: when you need to instruct the JVM that a variable can be modified by multiple threads and give hint to JVM that does not cache its value.

8) When to use a transient variable in Java? ( answer ) hint: when you want to make a variable non-serializable in a class, which implements the Serializable interface. In other words, you can use it for a variable whose value you don’t want to save. See The Complete Java MasterClass to learn about transient variables in Java.

9) Difference between the transient and volatile variable in Java? ( answer ) hint: totally different, one used in the context of serialization while the other is used in concurrency.

10) Difference between Serializable and Externalizable in Java? ( answer ) hint: Externalizable gives you more control over the Serialization process.

11) Can we override the private method in Java? ( answer ) hint: No, because it’s not visible in the subclass, a primary requirement for overriding a method in Java.

12) Difference between Hashtable and HashMap in Java? ( answer ) hint: several but most important is Hashtable , which is synchronized, while HashMap is not. It's also legacy and slow as compared to HashMap .

13) Difference between List and Set in Java? ( answer ) hint: List is ordered and allows duplicate. Set is unordered and doesn't allow duplicate elements.

14) Difference between ArrayList and Vector in Java ( answer ) hint: Many, but most important is that ArrayList is non-synchronized and fast while Vector is synchronized and slow. It's also legacy class like Hashtable .

15) Difference between Hashtable and ConcurrentHashMap in Java? ( answer ) hint: more scalable. See Java Fundamentals: Collections by Richard Warburton to learn more.

16) How does ConcurrentHashMap achieve scalability? ( answer ) hint: by dividing the map into segments and only locking during the write operation.

17) Which two methods you will override for an Object to be used as Key in HashMap ? ( answer ) hint: equals and hashcode

18) Difference between wait and sleep in Java? ( answer ) hint: The wait() method releases the lock or monitor, while sleep doesn't.

19) Difference between notify and notifyAll in Java? ( answer ) hint: notify notifies one random thread is waiting for that lock while notifyAll inform to all threads waiting for a monitor. If you are certain that only one thread is waiting then use notify , or else notifyAll is better. See Threading Essentials Mini-Course by Java Champion Heinz Kabutz to learn more about threading basics.

20) Why you override hashcode, along with equals() in Java? ( answer ) hint: to be compliant with equals and hashcode contract, which is required if you are planning to store your object into collection classes, e.g. HashMap or ArrayList .

21) What is the load factor of HashMap means? ( answer ) hint: The threshold that triggers the re-sizing of HashMap is generally 0.75, which means HashMap resize itself if it's 75 percent full.

22) Difference between ArrayList and LinkedList in Java? ( answer ) hint: same as an array and linked list, one allows random search while other doesn't. Insertion and deletion easy on the linked list but a search is easy on an array. See Java Fundamentals: Collections , Richard Warburton’s course on Pluralsight, to learn more about essential Collection data structure in Java.

23) Difference between CountDownLatch and CyclicBarrier in Java? ( answer ) hint: You can reuse CyclicBarrier after the barrier is broken but you cannot reuse CountDownLatch after the count reaches to zero.

24) When do you use Runnable vs Thread in Java? ( answer ) hint: always

25) What is the meaning of Enum being type-safe in Java? ( answer ) hint: It means you cannot assign an instance of different Enum type to an Enum variable. e.g. if you have a variable like DayOfWeek day then you cannot assign it value from DayOfMonth enum.

26) How does Autoboxing of Integer work in Java? ( answer ) hint: By using the valueOf() method in Java.

27) Difference between PATH and Classpath in Java? ( answer ) hint: PATH is used by the operating system while Classpath is used by JVM to locate Java binary, e.g. JAR files or Class files. See Java Fundamentals: The Core Platform to learn more about PATH , Classpath , and other Java environment variable.

io-lPE67oMG1oBh204LvPm61t7kAcLFvp-B6

28) Difference between method overloading and overriding in Java? ( answer ) hint: Overriding happens at subclass while overloading happens in the same class. Also, overriding is a runtime activity while overloading is resolved at compile time.

29) How do you prevent a class from being sub-classed in Java? ( answer ) hint: just make its constructor private

30) How do you restrict your class from being used by your client? ( answer ) hint: make the constructor private or throw an exception from the constructor

31) Difference between StringBuilder and StringBuffer in Java? ( answer ) hint: StringBuilder is not synchronized while StringBuffer is synchronized.

32) Difference between Polymorphism and Inheritance in Java? ( answer ) hint: Inheritance allows code reuse and builds the relationship between class, which is required by Polymorphism, which provides dynamic behavior. See Java Fundamentals: Object-Oriented Design to learn more about OOP features.

33) Can we override static method in Java? ( answer ) hint: No, because overriding resolves at runtime while static method call is resolved at compile time.

34) Can we access the private method in Java? ( answer ) hint: yes, in the same class but not outside the class

35) Difference between interface and abstract class in Java? ( answer ) hint: from Java 8 , the difference is blurred. However, a Java class can still implement multiple interfaces but can only extend one class.

36) Difference between DOM and SAX parser in Java? ( answer ) hint: DOM loads whole XML File in memory while SAX doesn’t. It is an event-based parser and can be used to parse a large file, but DOM is fast and should be preferred for small files.

37) Difference between throw and throws keyword in Java? ( answer ) hint: throws declare what exception a method can throw in case of error but throw keyword actually throws an exception. See Java Fundamentals: Exception Handling to learn more about Exception handling in Java.

QSqKD-b97Dr36kViV1eTdvqNVNgdZRp52D7n

38) Difference between fail-safe and fail-fast iterators in Java? ( answer ) hint: fail-safe doesn’t throw ConcurrentModificationException while fail-fast does whenever they detect an outside change on the underlying collection while iterating over it.

39) Difference between Iterator and Enumeration in Java? ( answer ) hint: Iterator also gives you the ability to remove an element while iterating while Enumeration doesn’t allow that.

40) What is IdentityHashMap in Java? ( answer ) hint: A Map , which uses the == equality operator to check equality instead of the equals() method.

41) What is the String pool in Java? ( answer ) hint: A pool of String literals. Remember it's moved to heap from perm gen space in JDK 7.

42) Can a Serializable class contains a non-serializable field in Java? ( answer ) hint: Yes, but you need to make it either static or transient.

43) Difference between this and super in Java? ( answer ) hint: this refers to the current instance while super refers to an instance of the superclass.

44) Difference between Comparator and Comparable in Java? ( answer ) hint: Comparator defines custom ordering while Comparable defines the natural order of objects, e.g. the alphabetic order for String . See The Complete Java MasterClass to learn more about sorting in Java.

DOCGFtdTMhjj3faRAiQ69ZSTxf2pffyroFfv

45) Difference between java.util.Date and java.sql.Date in Java? ( answer ) hint: former contains both date and time while later contains only date part.

46) Why wait and notify method are declared in Object class in Java? ( answer ) hint: because they require lock which is only available to an object.

47) Why Java doesn’t support multiple inheritances? ( answer ) hint: It doesn’t support because of a bad experience with C++, but with Java 8, it does in some sense — only multiple inheritances of Type are not supported in Java now.

48) Difference between checked and unchecked Exception in Java? ( answer ) hint: In case of checked, you must handle exception using catch block, while in case of unchecked, it’s up to you; compile will not bother you.

49) Difference between Error and Exception in Java? ( answer ) hint: I am tired of typing please check the answer

50) Difference between Race condition and Deadlock in Java? ( answer ) hint: both are errors that occur in a concurrent application, one occurs because of thread scheduling while others occur because of poor coding. See Multithreading and Parallel Computing in Java to learn more about deadlock, Race Conditions, and other multithreading issues.

Closing Notes

Thanks, You made it to the end of the article … Good luck with your programming interview! It’s certainly not going to be easy, but by following this roadmap and guide, you are one step closer to becoming a DevOps engineer .

If you like this article, then please share with your friends and colleagues, and don’t forget to follow javinpaul on Twitter!

Additional Resources

  • Java Interview Guide: 200+ Interview Questions and Answers
  • Spring Framework Interview Guide — 200+ Questions & Answers
  • Preparing For a Job Interview By John Sonmez
  • Java Programming Interview Exposed by Markham
  • Cracking the Coding Interview — 189 Questions and Answers
  • Data Structure and Algorithms Analysis for Job Interviews
  • 130+ Java Interview Questions of Last 5 Years
P.S. — If you need some FREE resources to learn Java, you can check out this list of free Java courses to start your preparation. P. S. S. — I have not provided the answer to the interview questions shared in the image “ How many String objects are created in the code?” can you guess and explain?

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

See our features in action

How skills-based hiring works

Explore all of our integrations

Assess coding skills

Discover what drives candidates

Test thinking and problem-solving

Evaluate language proficiency

Hire industry-leading tech talent

High-volume hiring done right

Find skilled candidates fast

Our customer success stories

Expert talent assessment articles

Insights into candidate potential

Why it works and how to adopt it

core java problem solving questions

Learn how TestGorilla uses industry-leading science to create skills-based hiring solutions.

49 Core Java interview questions for experienced programmers

Forty nine core java interview questions for experienced programmer featured image

Hiring a Core Java developer can be tricky if you aren’t an experienced developer yourself, as you must effectively analyze candidates’ soft and hard skills and consider whether their experience level matches your expectations.

With a Java skill test and related programming skills tests, you can evaluate multiple skills with minimal stress and effort. All that’s required is for you to invite candidates to complete an assessment.

If you’re having problems building your Core Java interview questions list, there’s no need to worry. Here are 49 questions you can ask experienced candidates to evaluate their abilities and knowledge.

Table of contents

19 core java interview questions for experienced talent about technical knowledge, 5 core java interview questions for experienced programmers with sample answers, 10 core java interview questions for experienced talent about technical processes, 5 technical core java interview questions for experienced talent with sample answers, 10 core java interview questions for experienced talent about operators, 5 operator-related core java interview questions for experienced talent and sample answers, 10 skill-related core java interview questions for experienced programmers, 5 skill-related core java interview questions for experienced talent with sample answers, when should you use core java interview questions for experienced talent, hire skilled programmers using core java interview questions for experienced talent.

For the technical part of the interview, these 19 Core Java interview questions for experienced talent are ideal for testing their knowledge. Ask them some of these questions to assess your candidates’ expertise.

1. Could you explain why inheritance isn’t as beneficial as composition?

2. What do you understand about the term composition?

3. What do you understand about the term aggregation?

4. Could you tell us how composition is different from aggregation?

5. Do you know what a constructor is in Core Java?

6. Could you tell us how many constructors exist in Core Java?

7. What do you understand about default constructors?

8. Can you tell us whether constructors are inherited? Explain your answer.

9. Can programs exceed a memory limit even if they have a garbage collector?

10. What do you know about synchronization? Can you tell us why it’s necessary?

11. Do you know what the varargs feature is? Which symbol would you use for this?

12. Name one advantage of using an ordered array in Core Java.

13. Name one disadvantage of using an ordered array in Core Java.

14. Have you used marker interfaces in your projects? Can you explain what they are?

15. What do you know about double brace initialization in Core Java?

16. Could you tell us how to make an object garbage-collection eligible?

17. Can you name a few examples of Java design pattern categories?

18. How have your soft skills helped you complete Core Java programming duties?

19. Is it true that the length() method in the String class doesn’t provide accurate results?

When reviewing your candidates’ technical interview question responses, have these sample answers ready so you can quickly check the depth of their knowledge.

1. How have your soft skills helped you complete Core Java programming responsibilities?

Java developers should have hard and soft skills to complete Core Java programming responsibilities. Although technical skills may seem more important, soft skills such as time management, communication, and motivation are equally crucial, helping applicants to:

Efficiently prioritize tasks and projects

Take feedback on board

Stay productive when completing tasks

For example, developers must be motivated and organized when developing an application to finish the work within a specific time. Since project delays can harm your company’s relationship with its clients, it’s best to review these soft skills before you hire someone.

But what’s the best way to assess your candidates’ soft skills? It’s easy with our Time Management , Communication , and Motivation skill tests . Use them to check who among your candidates has these abilities.

2. Could you tell us why inheritance isn’t as beneficial as composition?

Senior applicants will know why inheritance is less beneficial than composition in Core Java and respond based on their experience. 

Candidates should know that Core Java doesn’t allow multiple inheritances and that composition is ideal for preventing encapsulation breakage.

Candidates might have a couple of other insights when responding to this question. 

They may mention that composition’s loosely coupled nature is more advantageous than inheritance’s tightly coupled state and that developers can complete unit testing with composition – which isn’t possible with inheritance.

3. Can programs exceed a memory limit even with a garbage collector?

The simple answer to this question is that programs can run out of memory despite having a garbage collector. However, applicants can provide more detail. They should explain that although the garbage collector eliminates objects the program doesn’t require, some might remain in the scope.

Since a few objects may still exist, they can consume memory, which requires developers to dereference objects when they have completed their work.

4. What do you know about synchronization? Can you tell us why it’s necessary?

Synchronization is a process that makes concurrent process execution possible in Java. It’s particularly useful when several threads share one resource. 

Listen out for responses that elaborate on the advantage of synchronization and explain that the process facilitates reliable communication from one thread to another.

5. Do you understand what the varargs feature is? Which symbol would you use for this?

To show their knowledge of Core Java’s essential features, candidates should know that varargs mean variable arguments. But to provide more information, they might explain that engineers introduced the feature in Java 5, which enables developers to:

Assign multiple arguments

Support parameters of one type

Skilled and experienced candidates should explain that the ellipsis symbol […] represents the varargs feature.

Processes and methods for coding an application in Core Java are fundamental – assess your applicants’ knowledge of some essential technical techniques and strategies with some of these questions.

1. How would you print messages on the console? Which method would you use?

2. Which method should developers use to complete dependency injection?

3. Which method would you use to set up the spring bean scope?

4. Is it possible to release a lock on a thread with the sleep() method? 

5. How different is creating a string with new() from forming a literal one?

6. Can you tell us if making a constructor final is possible? Explain your answer.

7. How much do you know about the Java thread lifecycle? Name each step.

8. Do you understand what a memory leak means? Can you tell us what causes it?

9. Can developers import the same package two times in Java?

10. Can developers import only the main package if it has several sub-packages?

Here are five sample answers to the Core Java interview questions about technical processes to help you review your candidates’ knowledge.

1. Which method should developers use to complete dependency injection?

Although there’s no obligatory way to complete dependency injection, there is a recommended method. Candidates should know that developers should use setters if they’re completing optional dependency injection and constructor arguments for mandatory injection.

Knowing why these methods are recommended is important – check if candidates can explain this. For example, they might know that constructors make injecting values into immutable fields easy and enable the program to read them more easily.

2. Which method would you use to set up the spring bean scope?

One of the straightforward ways to set up the spring bean scope is to use a specific annotation or attribute. Applicants with advanced knowledge can specify that the @Scope annotation or attribute can facilitate this process, giving developers more control over bean instances creation.

If your applicants are eager to impress, they will explain that developers can use the annotation and attributes in XML configuration files.

3. Do you understand what a memory leak means? Can you tell us what causes it?

Although this question is similar to the Core Java interview question about garbage collection, applicants should be able to add more detail when responding. 

A memory leak happens when the garbage collector cannot remove – and the system cannot reference –  unused objects. If the garbage collector doesn’t free this memory, this creates a memory leak. 

However, a few other memory leak causes exist, such as:

Unbounded caches

Too much page swapping

Failure to delete custom objects before inserting them

Using the garbage collector correctly is crucial, as it can run 17% slower with three times as much memory. Check if your candidates understand the link between memory and garbage collectors to ensure their applications run efficiently.

4. How much do you know about the Java thread lifecycle? Name each stage.

If your candidates have a deep, technical understanding of the Java thread lifecycle, they may be ideal for a second interview process . Their answer should mention that there are five stages in the process, including:

Five stages of the java thread lifecycle graphic

New : at this stage, developers have not invoked the start() method but have created the thread.

Runnable : this stage occurs after the developer invokes the start() method but before the Java virtual machine invokes the run() method

Running : at this stage, the Java virtual machine invokes the run() method, and the thread begins to execute

Non-Runnable : this stage occurs when the thread cannot run when it is blocked or in a waiting state

Terminated: at this stage, the Java virtual machine has completed the run() method execution

5. Can developers import the same package two times in Java?

Although developers can import the same package twice, the action is usually redundant. Candidates should know that the Java virtual machine typically loads packages and classes once, no matter how many times they import them. So even though this process won’t cause any problems, it can waste time. 

If you want to discover more about your applicants’ operator knowledge, ask them a few of these 10 Core Java interview questions for experienced talent.

1. Do you understand how the >>> operator is different from the >> operator?

2. Could you explain the new() operator’s function in Java?

3. Could you explain the newInstance() operator’s function in Java?

4. Do you know how Java’s new() and newInstance() operators differ?

5. Can you explain how the equals() method differs from the equality operator?

6. Can you explain what a unary operator is in Java?

7. What does the ! operator mean in Core Java?

8. What does the != operator mean in Core Java?

9. What does the ?: operator mean in Core Java?

10. Can you explain what a conditional operator is in Java?

To review your candidates’ operator-related responses, check the sample answers to these five fundamental Core Java interview questions for experienced talent.

The key to assessing responses to this Core Java interview question is to consider if applicants can provide one main difference between the two operators. 

Candidates should know that >> is a bitwise right shift operator that moves each bit to the right and retains the signed bit. They should then explain that >>> is a bitwise right shift operator that provides a trailing zero.

Adding more details to their response will help candidates prove their expertise. If applicants know that the >>> operator does not retain the signed bit, they likely have a good knowledge of operators in Core Java.

2. Could you explain what the new() operator’s function is in Java?

Developers use the new() operator to create objects in Java. It works through class instantiation, helping programmers to allocate memory for new objects. The operator also returns a specific reference to the allocated memory.

If you want to assess your candidates’ knowledge more deeply, ask them questions to see if they know how the new() operator relates to the object constructor. They should know that this operator functions by invoking the constructor. 

What’s important when assessing your applicants’ responses to this question is to check if they know when developers should use the newInstance() operator. Expert programmers will know this operator is ideal when developers don’t know the class name required to create an object. 

They’ll also understand that it functions well when developers need to retrieve the class name from a database, file, or command line argument.

4. Do you know how Java’s new() and newInstance() operators are different?

Even though the new() and newInstance() operators create objects, one key difference exists between them. Developers should use the new() operator if they already know the name of the class when creating the object and the newInstance() operator when they don’t.

Give top marks to candidates who understand that newInstance() is a dynamic method that can help developers load classes from remote sources.

Applicants should know that the equals() method enables developers to compare two objects based on the content of those objects. They should then explain that the equality operator in Java helps developers compare primitive types of data and objects based on their memory location.

If they want to provide more detail, candidates will mention that the equality operator also checks if the two objects point to the same memory locations. 

Core Java skills are critical for Core Java developers. Ensure you review their abilities by asking them some of these 10 Core Java interview questions for experienced programmers.

1. Do you have a good knowledge of object-oriented programming?

2. Why are Java skills important for Core Java developers?

3. Tell us about your application programming interface knowledge.

4. How are Spring Boot skills linked to Core Java? Why are they important?

5. Do you understand what the Java virtual machine is?

6. Explain how good communication helps developers collaborate on projects.

7. Why is problem-solving a fundamental skill for Java developers?

8. Why are critical-thinking skills crucial for Core Java developers?

9. Do you understand why attention to detail is crucial for Core Java developers?

10. Are you familiar with DevOps? Why are DevOps skills necessary for Core Java developers?

Check out the answers to these five skill-related Core Java interview questions to review your candidates’ responses and quickly assess their abilities.

1. Are you familiar with DevOps? Why are DevOps skills necessary for Core Java developers?

Applicants should know that the DevOps model enables teams to implement development, testing, deployment, and application operation. With sufficient DevOps skills, applicants can easily complete continuous integration, Java development automation, and quick feedback implementation. 

Looking for a quick method to assess your interviewees’ DevOps skills before the interview? Use our DevOps skill test to review four essential DevOps subskills.

2. How are Spring Boot skills linked to Core Java? Why are they important?

The great thing about Spring Boot skills is that they facilitate the web application and microservices development process for Java developers. Programmers with this skill can use this open-source framework without integrating special tools. With the right skills, they can use any text editor or integrated development environment to complete their projects.

Therefore, it’s a good idea to assess your candidates’ Spring Boot knowledge with a data-driven skill test, such as our Spring test . This process will help you learn if their abilities are ideal for your company. 

3. Why is problem-solving a fundamental skill for Java developers?

The entire development lifecycle relies on problem-solving skills, which developers should hone for their projects. It’s a critical skill because developers must notice problems and develop strategies to solve issues before delivering software or applications.

After code reviews and software testing, developers must also make changes to the code in line with the feedback, which problem-solving can help with. 63% of developers spend 30 minutes working on projects that require problem-solving, but it’s still vital to assess their abilities and determine if they match your role.

With this in mind, it’s worth asking candidates to complete a Problem Solving skill test before you hire someone to evaluate this essential skill. Our test will reveal the programmers with the most advanced problem-solving skills and experience.

4. Why are critical-thinking skills crucial for Core Java developers?

With critical-thinking skills, Core Java developers can think of unique and viable strategies to handle errors. Without it, they will struggle to select the best methods to resolve problems in their code or application.

For instance, if testing reveals a bug that affects the user experience, candidates can solve this using critical-thinking skills and make the user experience smoother.

Many applicants might complete hackathons or work on projects to develop their critical-thinking skills, but if you need a more quantitative way to assess this, use our Critical Thinking skill test .  

5. Do you understand why attention to detail is crucial for Core Java developers?

Attention to detail is vital for most tasks Core Java developers complete. It can help programmers notice the tiniest errors in their code, which would otherwise ruin the entire program. 

This skill also has other positive consequences for software development. It ensures systems can read and understand the code thanks to the correct syntax and makes code modification easier.

One way to assess applicants’ attention to detail is to use our Attention to Detail test . Integrate it into your candidates’ Core Java assessment for easy candidate evaluation.

You’ve now got a list of interview questions, but it’s important to consider when to use them during the hiring process – which should happen after candidates complete assessments. 

You can remove unskilled candidates immediately based on their lack of skills when you ask applicants to complete the five tests in your assessment.

With this strategy, no unsuitable candidates will enter the interview stage, saving you time, effort, and extra administration work. And combined, these methods give you statistical and qualitative information to help you assess candidates thoroughly.

There isn’t an easier way to assess applicants than to use Core Java interview questions for experienced talent and skill testing, which is why we recommend this easy strategy.

The optimum thing about these methods is the time you’ll save by avoiding resume screening methods because skill testing is the perfect replacement for resume screening.

But what are your next actions? We suggest you sign up to TestGorilla for free or register for a demonstration to learn more about custom questions, branding, and the best way to send candidates invitations.

TestGorilla is making hiring easy for companies like Sony and Revolut. Find out more about it at TestGorilla.

Related posts

How to attract and assess virtuoso ISTP candidates featured image

How to attract and assess Virtuoso (ISTP) candidates

Compensation-management-softwar-A-guide-for-efficiency-driven-HR-professionals featured image

How to write a Snowflake developer job description

How to write a program management job description featured image

How to write a program management job description

Hire the best candidates with testgorilla..

Create pre-employment assessments in minutes to screen candidates, save time, and hire the best talent.

core java problem solving questions

Latest posts

food and beverage manager job description featured image

The best advice in pre-employment testing, in your inbox.

No spam. Unsubscribe at any time.

Hire the best. No bias. No stress.

Our screening tests identify the best candidates and make your hiring decisions faster, easier, and bias-free.

Free resources

core java problem solving questions

Anti-cheating checklist

This checklist covers key features you should look for when choosing a skills testing platform

core java problem solving questions

Onboarding checklist

This resource will help you develop an onboarding checklist for new hires.

core java problem solving questions

How to find candidates with strong attention to detail

How to assess your candidates' attention to detail.

core java problem solving questions

How to get HR certified

Learn how to get human resources certified through HRCI or SHRM.

core java problem solving questions

Improve quality of hire

Learn how you can improve the level of talent at your company.

core java problem solving questions

Case study: How CapitalT reduces hiring bias

Learn how CapitalT reduced hiring bias with online skills assessments.

core java problem solving questions

Resume screening guide

Learn how to make the resume process more efficient and more effective.

core java problem solving questions

Important recruitment metrics

Improve your hiring strategy with these 7 critical recruitment metrics.

core java problem solving questions

Case study: How Sukhi reduces shortlisting time

Learn how Sukhi decreased time spent reviewing resumes by 83%!

core java problem solving questions

12 pre-employment testing hacks

Hire more efficiently with these hacks that 99% of recruiters aren't using.

core java problem solving questions

The benefits of diversity

Make a business case for diversity and inclusion initiatives with this data.

core java problem solving questions

Javatpoint Logo

All Interview

Company interview, technical interview, web interview, php interview, .net interview, java interview, database interview, 3) list the features of java programming language..

There are the following features in Java Programming Language.

  • Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to write the program in it.
  • Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as the combination of different type of objects that incorporates both data and behavior.
  • Portable: Java supports read-once-write-anywhere approach. We can execute the Java program on every machine. Java program (.java) is converted to bytecode (.class) which can be easily run on every machine.
  • Platform Independent: Java is a platform independent programming language. It is different from other programming languages like C and C++ which needs a platform to be executed. Java comes with its platform on which its code is executed. Java doesn't depend upon the operating system to be executed.
  • Secured: Java is secured because it doesn't use explicit pointers. Java also provides the concept of ByteCode and Exception handling which makes it more secured.
  • Robust: Java is a strong programming language as it uses strong memory management. The concepts like Automatic garbage collection, Exception handling, etc. make it more robust.
  • Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C, the size of data types may vary according to the architecture (32 bit or 64 bit) which doesn't exist in Java.
  • Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program execution.
  • High Performance: Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++).
  • Multithreaded: We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc.
  • Distributed: Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet.
  • Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++.

4) What do you understand by Java virtual machine?

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

5) What is the difference between JDK, JRE, and JVM?

JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the runtime environment in which Java bytecode can be executed. It is a specification which specifies the working of Java Virtual Machine. Its implementation has been provided by Oracle and other companies. Its implementation is known as JRE.

JVMs are available for many hardware and software platforms (so JVM is platform dependent). It is a runtime instance which is created when we run the Java class. There are three notions of the JVM: specification, implementation, and instance.

JRE stands for Java Runtime Environment. It is the implementation of JVM. The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.

JDK is an acronym for Java Development Kit. It is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools. JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

  • Standard Edition Java Platform
  • Enterprise Edition Java Platform
  • Micro Edition Java Platform

6) How many types of memory areas are allocated by JVM?

Many types:

  • Class(Method) Area: Class Area stores per-class structures such as the runtime constant pool, field, method data, and the code for methods.
  • Heap: It is the runtime data area in which the memory is allocated to the objects
  • Stack: Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as the thread. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
  • Program Counter Register: PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.
  • Native Method Stack: It contains all the native methods used in the application.

7) What is JIT compiler?

Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the bytecode that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

8) What is the platform?

A platform is the hardware or software environment in which a piece of software is executed. There are two types of platforms, software-based and hardware-based. Java provides the software-based platform.

9) What are the main differences between the Java platform and other platforms?

There are the following differences between the Java platform and other platforms.

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

10) What gives Java its 'write once and run anywhere' nature?

The bytecode. Java compiler converts the Java programs into the class file (Byte Code) which is the intermediate language between source code and machine code. This bytecode is not platform specific and can be executed on any computer.

11) What is classloader?

Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java.

  • Bootstrap ClassLoader : This is the first classloader which is the superclass of Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes, etc.
  • Extension ClassLoader : This is the child classloader of Bootstrap and parent classloader of System classloader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
  • System/Application ClassLoader : This is the child classloader of Extension classloader. It loads the class files from the classpath. By default, the classpath is set to the current directory. You can change the classpath using "-cp" or "-classpath" switch. It is also known as Application classloader.

12) Is Empty .java file name a valid source file name?

Yes, Java allows to save our java file by .java only, we need to compile it by javac .java and run by java classname Let's take a simple example:

compile it by javac .java

run it by java A

13) Is delete, next, main, exit or null keyword in java?

14) if i don't provide any arguments on the command line, then what will the value stored in the string array passed into the main() method, empty or null.

It is empty, but not null.

15) What if I write static public void instead of public static void?

The program compiles and runs correctly because the order of specifiers doesn't matter in Java.

16) What is the default value of the local variables?

The local variables are not initialized to any default value, neither primitives nor object references.

17) What are the various access specifiers in Java?

In Java, access specifiers are the keywords which are used to define the access scope of the method, class, or a variable. In Java, there are four access specifiers given below.

  • Public The classes, methods, or variables which are defined as public, can be accessed by any class or method.
  • Protected Protected can be accessed by the class of the same package, or by the sub-class of this class, or within the same class.
  • Default Default are accessible within the package only. By default, all the classes, methods, and variables are of default scope.
  • Private The private class, methods, or variables defined as private can be accessed within the class only.

18) What is the purpose of static methods and variables?

The methods or variables defined as static are shared among all the objects of the class. The static is the part of the class and not of the object. The static variables are stored in the class area, and we do not need to create the object to access such variables. Therefore, static is used in the case, where we need to define variables or methods which are common to all the objects of the class.

For example, In the class simulating the collection of the students in a college, the name of the college is the common attribute to all the students. Therefore, the college name will be defined as static .

19) What are the advantages of Packages in Java?

There are various advantages of defining packages in Java.

  • Packages avoid the name clashes.
  • The Package provides easier access control.
  • We can also have the hidden classes that are not visible outside and used by the package.
  • It is easier to locate the related classes.

20) What is the output of the following Java program?

The output of the above code will be

Explanation

In the first case, 10 and 20 are treated as numbers and added to be 30. Now, their sum 30 is treated as the string and concatenated with the string Javatpoint . Therefore, the output will be 30Javatpoint .

In the second case, the string Javatpoint is concatenated with 10 to be the string Javatpoint10 which will then be concatenated with 20 to be Javatpoint1020 .

21) What is the output of the following Java program?

In the first case, The numbers 10 and 20 will be multiplied first and then the result 200 is treated as the string and concatenated with the string Javatpoint to produce the output 200Javatpoint .

In the second case, The numbers 10 and 20 will be multiplied first to be 200 because the precedence of the multiplication is higher than addition. The result 200 will be treated as the string and concatenated with the string Javatpoint to produce the output as Javatpoint200 .

22) What is the output of the following Java program?

The above code will give the compile-time error because the for loop demands a boolean value in the second part and we are providing an integer value, i.e., 0.

Core Java - OOPs Concepts: Initial OOPs Interview Questions

There is given more than 50 OOPs (Object-Oriented Programming and System) interview questions. However, they have been categorized in many sections such as constructor interview questions, static interview questions, Inheritance Interview questions, Abstraction interview question, Polymorphism interview questions, etc. for better understanding.

23) What is object-oriented paradigm?

It is a programming paradigm based on objects having data and methods defined in the class to which it belongs. Object-oriented paradigm aims to incorporate the advantages of modularity and reusability. Objects are the instances of classes which interacts with one another to design applications and programs. There are the following features of the object-oriented paradigm.

  • Follows the bottom-up approach in program design.
  • Focus on data with methods to operate upon the object's data
  • Includes the concept like Encapsulation and abstraction which hides the complexities from the user and show only functionality.
  • Implements the real-time approach like inheritance, abstraction, etc.
  • The examples of the object-oriented paradigm are C++, Simula, Smalltalk, Python, C#, etc.

24) What is an object?

The Object is the real-time entity having some state and behavior. In Java, Object is an instance of the class having the instance variables as the state of the object and the methods as the behavior of the object. The object of a class can be created by using the new keyword.

25) What is the difference between an object-oriented programming language and object-based programming language?

There are the following basic differences between the object-oriented language and object-based language.

  • Object-oriented languages follow all the concepts of OOPs whereas, the object-based language doesn't follow all the concepts of OOPs like inheritance and polymorphism.
  • Object-oriented languages do not have the inbuilt objects whereas Object-based languages have the inbuilt objects, for example, JavaScript has window object.
  • Examples of object-oriented programming are Java, C#, Smalltalk, etc. whereas the examples of object-based languages are JavaScript, VBScript, etc.

26) What will be the initial value of an object reference which is defined as an instance variable?

All object references are initialized to null in Java.

Core Java - OOPs Concepts: Constructor Interview Questions

27) what is the constructor.

The constructor can be defined as the special type of method that is used to initialize the state of an object. It is invoked when the class is instantiated, and the memory is allocated for the object. Every time, an object is created using the new keyword, the default constructor of the class is called. The name of the constructor must be similar to the class name. The constructor must not have an explicit return type.

28) How many types of constructors are used in Java?

Based on the parameters passed in the constructors, there are two types of constructors in Java.

  • Default Constructor: default constructor is the one which does not accept any value. The default constructor is mainly used to initialize the instance variable with the default values. It can also be used for performing some useful task on object creation. A default constructor is invoked implicitly by the compiler if there is no constructor defined in the class.
  • Parameterized Constructor: The parameterized constructor is the one which can initialize the instance variables with the given values. In other words, we can say that the constructors which can accept the arguments are called parameterized constructors.

Java Constructors

29) What is the purpose of a default constructor?

The purpose of the default constructor is to assign the default value to the objects. The java compiler creates a default constructor implicitly if there is no constructor in the class.

Explanation: In the above class, you are not creating any constructor, so compiler provides you a default constructor. Here 0 and null values are provided by default constructor.

Java default constructor

30) Does constructor return any value?

Ans: yes, The constructor implicitly returns the current instance of the class (You can't use an explicit return type with the constructor). More Details.

31)Is constructor inherited?

No, The constructor is not inherited.

32) Can you make a constructor final?

No, the constructor can't be final.

33) Can we overload the constructors?

Yes, the constructors can be overloaded by changing the number of arguments accepted by the constructor or by changing the data type of the parameters. Consider the following example.

In the above program, The constructor Test is overloaded with another constructor. In the first call to the constructor, The constructor with one argument is called, and i will be initialized with the value 10. However, In the second call to the constructor, The constructor with the 2 arguments is called, and i will be initialized with the value 15.

34) What do you understand by copy constructor in Java?

There is no copy constructor in java. However, we can copy the values from one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

  • By constructor
  • By assigning the values of one object into another
  • By clone() method of Object class

In this example, we are going to copy the values of one object into another using java constructor.

35) What are the differences between the constructors and methods?

There are many differences between constructors and methods. They are given below.

Java Constructors vs Methods

36) What is the output of the following Java program?

The output of the following program is:

Here, the data type of the variables a and b, i.e., byte gets promoted to int, and the first parameterized constructor with the two integer parameters is called.

37) What is the output of the following Java program?

The output of the program is 0 because the variable i is initialized to 0 internally. As we know that a default constructor is invoked implicitly if there is no constructor in the class, the variable i is initialized to 0 since there is no constructor in the class.

38) What is the output of the following Java program?

There is a compiler error in the program because there is a call to the default constructor in the main method which is not present in the class. However, there is only one parameterized constructor in the class Test. Therefore, no default constructor is invoked by the constructor implicitly.

Core Java - OOPs Concepts: static keyword Interview Questions

39) what is the static variable.

The static variable is used to refer to the common property of all objects (that is not unique for each object), e.g., The company name of employees, college name of students, etc. Static variable gets memory only once in the class area at the time of class loading. Using a static variable makes your program more memory efficient (it saves memory). Static variable belongs to the class rather than the object.

Static Variable

40) What is the static method?

  • A static method belongs to the class rather than the object.
  • There is no need to create the object to call the static methods.
  • A static method can access and change the value of the static variable.

41) What are the restrictions that are applied to the Java static methods?

Two main restrictions are applied to the static methods.

  • The static method can not use non-static data member or call the non-static method directly.
  • this and super cannot be used in static context as they are non-static.

42) Why is the main method static?

Because the object is not required to call the static method. If we make the main method non-static, JVM will have to create its object first and then call main() method which will lead to the extra memory allocation. More Details.

43) Can we override the static methods?

44) what is the static block.

Static block is used to initialize the static data member. It is executed before the main method, at the time of classloading.

45) Can we execute a program without main() method?

Ans) No, It was possible before JDK 1.7 using the static block. Since JDK 1.7, it is not possible. More Details.

46) What if the static modifier is removed from the signature of the main method?

Program compiles. However, at runtime, It throws an error "NoSuchMethodError."

47) What is the difference between static (class) method and instance method?

48) can we make constructors static.

As we know that the static context (method, block, or variable) belongs to the class, not the object. Since Constructors are invoked only when the object is created, there is no sense to make the constructors static. However, if you try to do so, the compiler will show the compiler error.

49) Can we make the abstract methods static in Java?

In Java, if we make the abstract methods static, It will become the part of the class, and we can directly call it which is unnecessary. Calling an undefined method is completely useless therefore it is not allowed.

50) Can we declare the static variables and methods in an abstract class?

Yes, we can declare static variables and methods in an abstract method. As we know that there is no requirement to make the object to access the static context, therefore, we can access the static context declared inside the abstract class by using the name of the abstract class. Consider the following example.

Core Java - OOPs Concepts: Inheritance Interview Questions

51) what is this keyword in java.

The this keyword is a reference variable that refers to the current object. There are the various uses of this keyword in Java. It can be used to refer to current class properties such as instance methods, variable, constructors, etc. It can also be passed as an argument into the methods or constructors. It can also be returned from the method as the current class instance.

java this keyword

52) What are the main uses of this keyword?

There are the following uses of this keyword.

  • this can be used to refer to the current class instance variable.
  • this can be used to invoke current class method (implicitly)
  • this() can be used to invoke the current class constructor.
  • this can be passed as an argument in the method call.
  • this can be passed as an argument in the constructor call.
  • this can be used to return the current class instance from the method.

53) Can we assign the reference to this variable?

No, this cannot be assigned to any value because it always points to the current class object and this is the final reference in Java. However, if we try to do so, the compiler error will be shown. Consider the following example.

54) Can this keyword be used to refer static members?

Yes, It is possible to use this keyword to refer static members because this is just a reference variable which refers to the current class object. However, as we know that, it is unnecessary to access static variables through objects, therefore, it is not the best practice to use this to refer static members. Consider the following example.

55) How can constructor chaining be done using this keyword?

Constructor chaining enables us to call one constructor from another constructor of the class with respect to the current class object. We can use this keyword to perform constructor chaining within the same class. Consider the following example which illustrates how can we use this keyword to achieve constructor chaining.

56) What are the advantages of passing this into a method instead of the current class object itself?

As we know, that this refers to the current class object, therefore, it must be similar to the current class object. However, there can be two main advantages of passing this into a method instead of the current class object.

  • this is a final variable. Therefore, this cannot be assigned to any new value whereas the current class object might not be final and can be changed.
  • this can be used in the synchronized block.

57) What is the Inheritance?

Inheritance is a mechanism by which one object acquires all the properties and behavior of another object of another class. It is used for Code Reusability and Method Overriding. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

There are five types of inheritance in Java.

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

Multiple inheritance is not supported in Java through class.

58) Why is Inheritance used in Java?

There are various advantages of using inheritance in Java that is given below.

  • Inheritance provides code reusability. The derived class does not need to redefine the method of base class unless it needs to provide the specific implementation of the method.
  • Runtime polymorphism cannot be achieved without using inheritance.
  • We can simulate the inheritance of classes with the real-time objects which makes OOPs more realistic.
  • Inheritance provides data hiding. The base class can hide some data from the derived class by making it private.
  • Method overriding cannot be achieved without inheritance. By method overriding, we can give a specific implementation of some basic method contained by the base class.

59) Which class is the superclass for all the classes?

The object class is the superclass of all other classes in Java.

60) Why is multiple inheritance not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.

Since the compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have the same method or different, there will be a compile time error.

61) What is aggregation?

Aggregation can be defined as the relationship between two classes where the aggregate class contains a reference to the class it owns. Aggregation is best described as a has-a relationship. For example, The aggregate class Employee having various fields such as age, name, and salary also contains an object of Address class having various fields such as Address-Line 1, City, State, and pin-code. In other words, we can say that Employee (class) has an object of Address class. Consider the following example.

Address.java

Employee.java

62) What is composition?

Holding the reference of a class within some other class is known as composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. In other words, we can say that composition is the particular case of aggregation which represents a stronger relationship between two objects. Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

63) What is the difference between aggregation and composition?

Aggregation represents the weak relationship whereas composition represents the strong relationship. For example, the bike has an indicator (aggregation), but the bike has an engine (composition).

64) Why does Java not support pointers?

The pointer is a variable that refers to the memory address. They are not used in Java because they are unsafe(unsecured) and complex to understand.

65) What is super in java?

The super keyword in Java is a reference variable that is used to refer to the immediate parent class object. Whenever you create the instance of the subclass, an instance of the parent class is created implicitly which is referred by super reference variable. The super() is called in the class constructor implicitly by the compiler if there is no super or this.

66) How can constructor chaining be done by using the super keyword?

67) what are the main uses of the super keyword.

There are the following uses of super keyword.

  • super can be used to refer to the immediate parent class instance variable.
  • super can be used to invoke the immediate parent class method.
  • super() can be used to invoke immediate parent class constructor.

68) What are the differences between this and super keyword?

There are the following differences between this and super keyword.

  • The super keyword always points to the parent class contexts whereas this keyword always points to the current class context.
  • The super keyword is primarily used for initializing the base class variables within the derived class constructor whereas this keyword primarily used to differentiate between local and instance variables when passed in the class constructor.
  • The super and this must be the first statement inside constructor otherwise the compiler will throw an error.

69) What is the output of the following Java program?

The super() is implicitly invoked by the compiler if no super() or this() is included explicitly within the derived class constructor. Therefore, in this case, The Person class constructor is called first and then the Employee class constructor is called.

70) Can you use this() and super() both in a constructor?

No, because this() and super() must be the first statement in the class constructor.

71)What is object cloning?

The object cloning is used to create the exact copy of an object. The clone() method of the Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.

Core Java - OOPs Concepts: Method Overloading Interview Questions

72) what is method overloading.

Method overloading is the polymorphism technique which allows us to create multiple methods with the same name but different signature. We can achieve method overloading in two ways.

  • By Changing the number of arguments
  • By Changing the data type of arguments

Method overloading increases the readability of the program. Method overloading is performed to figure out the program quickly.

73) Why is method overloading not possible by changing the return type in java?

In Java, method overloading is not possible by changing the return type of the program due to avoid the ambiguity.

74) Can we overload the methods by making them static?

No, We cannot overload the methods by just applying the static keyword to them(number of parameters and types are the same). Consider the following example.

75) Can we overload the main() method?

Yes, we can have any number of main methods in a Java program by using method overloading.

76) What is method overloading with type promotion?

By Type promotion is method overloading, we mean that one data type can be promoted to another implicitly if no exact matching is found.

Java Method Overloading with Type Promotion

As displayed in the above diagram, the byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int, long, float or double. The char datatype can be promoted to int, long, float or double and so on. Consider the following example.

77) What is the output of the following Java program?

There are two methods defined with the same name, i.e., sum. The first method accepts the integer and long type whereas the second method accepts long and the integer type. The parameter passed that are a = 20, b = 20. We can not tell that which method will be called as there is no clear differentiation mentioned between integer literal and long literal. This is the case of ambiguity. Therefore, the compiler will throw an error.

Core Java - OOPs Concepts: Method Overriding Interview Questions

78) what is method overriding:.

If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to implement the interface methods.

Rules for Method overriding

  • The method must have the same name as in the parent class.
  • The method must have the same signature as in the parent class.
  • Two classes must have an IS-A relationship between them.

79) Can we override the static method?

No, you can't override the static method because they are the part of the class, not the object.

80) Why can we not override static method?

It is because the static method is the part of the class, and it is bound with class whereas instance method is bound with the object, and static gets memory in class area, and instance gets memory in a heap.

81) Can we override the overloaded method?

82) difference between method overloading and overriding., 83) can we override the private methods.

No, we cannot override the private methods because the scope of private methods is limited to the class and we cannot access them outside of the class.

84) Can we change the scope of the overridden method in the subclass?

Yes, we can change the scope of the overridden method in the subclass. However, we must notice that we cannot decrease the accessibility of the method. The following point must be taken care of while changing the accessibility of the method.

  • The private can be changed to protected, public, or default.
  • The protected can be changed to public or default.
  • The default can be changed to public.
  • The public will always remain public.

85) Can we modify the throws clause of the superclass method while overriding it in the subclass?

Yes, we can modify the throws clause of the superclass method while overriding it in the subclass. However, there are some rules which are to be followed while overriding in case of exception handling.

  • If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception, but it can declare the unchecked exception.
  • If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

86) What is the output of the following Java program?

87) can you have virtual functions in java.

Yes, all functions in Java are virtual by default.

88) What is covariant return type?

Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type. The covariant return type specifies that the return type may vary in the same direction as the subclass.

89) What is the output of the following Java program?

The method of Base class, i.e., baseMethod() is overridden in Derived class. In Test class, the reference variable b (of type Base class) refers to the instance of the Derived class. Here, Runtime polymorphism is achieved between class Base and Derived. At compile time, the presence of method baseMethod checked in Base class, If it presence then the program compiled otherwise the compiler error will be shown. In this case, baseMethod is present in Base class; therefore, it is compiled successfully. However, at runtime, It checks whether the baseMethod has been overridden by Derived class, if so then the Derived class method is called otherwise Base class method is called. In this case, the Derived class overrides the baseMethod; therefore, the Derived class method is called.

Core Java - OOPs Concepts: final keyword Interview Questions

90) what is the final variable.

In Java, the final variable is used to restrict the user from updating it. If we initialize the final variable, we can't change its value. In other words, we can say that the final variable once assigned to a value, can never be changed after that. The final variable which is not assigned to any value can only be assigned through the class constructor.

final keyword in java

91) What is the final method?

If we change any method to a final method, we can't override it. More Details.

92) What is the final class?

If we make any class final, we can't inherit it into any of the subclasses.

93) What is the final blank variable?

A final variable, not initialized at the time of declaration, is known as the final blank variable. We can't initialize the final blank variable directly. Instead, we have to initialize it by using the class constructor. It is useful in the case when the user has some data which must not be changed by others, for example, PAN Number. Consider the following example:

94) Can we initialize the final blank variable?

Yes, if it is not static, we can initialize it in the constructor. If it is static blank final variable, it can be initialized only in the static block. More Details.

95) Can you declare the main method as final?

Yes, We can declare the main method as public static final void main(String[] args){}.

96) What is the output of the following Java program?

Since i is the blank final variable. It can be initialized only once. We have initialized it to 20. Therefore, 20 will be printed.

97) What is the output of the following Java program?

The getDetails() method is final; therefore it can not be overridden in the subclass.

98) Can we declare a constructor as final?

The constructor can never be declared as final because it is never inherited. Constructors are not ordinary methods; therefore, there is no sense to declare constructors as final. However, if you try to do so, The compiler will throw an error.

99) Can we declare an interface as final?

No, we cannot declare an interface as final because the interface must be implemented by some class to provide its definition. Therefore, there is no sense to make an interface final. However, if you try to do so, the compiler will show an error.

100) What is the difference between the final method and abstract method?

The main difference between the final method and abstract method is that the abstract method cannot be final as we need to override them in the subclass to give its definition.

You may also like:

  • Java Interview Questions
  • SQL Interview Questions
  • Python Interview Questions
  • JavaScript Interview Questions
  • Angular Interview Questions
  • Selenium Interview Questions
  • Spring Boot Interview Questions
  • HR Interview Questions
  • C Programming Interview Questions
  • C++ Interview Questions
  • Data Structure Interview Questions
  • DBMS Interview Questions
  • HTML Interview Questions
  • IAS Interview Questions
  • Manual Testing Interview Questions
  • OOPs Interview Questions
  • .Net Interview Questions
  • C# Interview Questions
  • ReactJS Interview Questions
  • Networking Interview Questions
  • PHP Interview Questions
  • CSS Interview Questions
  • Node.js Interview Questions
  • Spring Interview Questions
  • Hibernate Interview Questions
  • AWS Interview Questions
  • Accounting Interview Questions

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence Tutorial

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking Tutorial

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering Tutorial

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

Download Interview guide PDF

  • Java Interview Questions

Download PDF

Do you have what it takes to ace a Java Interview? We are here to help you in consolidating your knowledge and concepts in Java . Before we begin, let's understand what Java is all about.

What is Java? 

Java is a high-level programming language that was developed by James Gosling in the year 1982. It is based on the principles of object-oriented programming and can be used to develop large-scale applications. 

The following article will cover all the popular Core Java interview questions, String Handling interview questions, Java 8 interview questions, Java multithreading interview questions, Java OOPs interview questions, Java exception handling interview questions, collections interview questions, and some frequently asked Java coding interview questions.

Go through all the important questions to enhance your chances of performing well in the Java Interviews. The questions will revolve around the basic, core & advanced fundamentals of Java.

So, let’s dive deep into the plethora of useful Java Technical Interview Questions and Answers categorised into the following sections:

  • Java interview questions for Freshers

Java Intermediate Interview Questions

Java interview questions for experienced, java programming interview questions.

Join our community and share your recent Java interview experiences.

Java Interview Questions for Freshers

1. why is java a platform independent language.

Java language was developed so that it does not depend on any hardware or software because the compiler compiles the code and then converts it to platform-independent byte code which can be run on multiple systems.

  • The only condition to run that byte code is for the machine to have a runtime environment (JRE) installed in it

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

Java supports primitive data types - byte, boolean, char, short, int, float, long, and double and hence it is not a pure object oriented language .

3. Difference between Heap and Stack Memory in java. And how java utilizes this.

Stack memory is the portion of memory that was assigned to every individual program. And it was fixed. On the other hand, Heap memory is the portion that was not allocated to the java program but it will be available for use by the java program when it is required, mostly during the runtime of the program.

Java Utilizes this memory as - 

  • When we write a java program then all the variables, methods, etc are stored in the stack memory.
  • And when we create any object in the java program then that object was created in the heap memory. And it was referenced from the stack memory.

Example- Consider the below java program :

For this java program. The stack and heap memory occupied by java is -

core java problem solving questions

Main and PrintArray is the method that will be available in the stack area and as well as the variables declared that will also be in the stack area. 

And the Object (Integer Array of size 10) we have created, will be available in the Heap area because that space will be allocated to the program during runtime. 

4. Can java be said to be the complete object-oriented programming language?

It is not wrong if we claim that Java is the complete object-oriented programming language because everything in Java is under the classes and we can access them by creating the objects.

But we can even say that Java is not a completely object-oriented programming language because it has the support of primitive data types like int, float, char, boolean, double, etc.

Now for the question: Is Java a completely object-oriented programming language? We can say that - Java is not a pure object-oriented programming language, because it has direct access to primitive data types. And these primitive data types don't directly belong to the Integer classes.

5. How is Java different from C++?

  • C++ is only a  compiled language, whereas Java is compiled as well as an interpreted language.
  • Java programs are machine-independent whereas a c++ program can run only in the machine in which it is compiled. 
  • C++ allows users to use pointers in the program. Whereas java doesn’t allow it. Java internally uses pointers. 
  • C++ supports the concept of Multiple inheritances whereas Java doesn't support this. And it is due to avoiding the complexity of name ambiguity that causes the diamond problem.

Learn via our Video Courses

6. pointers are used in c/ c++. why does java not make use of pointers.

Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on code simplicity, and the usage of pointers can make it challenging. Pointer utilization can also cause potential errors. Moreover, security is also compromised if pointers are used because the users can directly access memory with the help of pointers.

Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover, the usage of pointers can make the procedure of garbage collection quite slow and erroneous. Java makes use of references as these cannot be manipulated, unlike pointers.

7. What do you understand by an instance variable and a local variable?

Instance variables are those variables that are accessible by all the methods in the class. They are declared outside the methods and inside the class. These variables describe the properties of an object and remain bound to it at any cost.

All the objects of the class will have their copy of the variables for utilization. If any modification is done on these variables, then only that instance will be impacted by it, and all other class instances continue to remain unaffected.

Local variables are those variables present within a block, function, or constructor and can be accessed only inside them. The utilization of the variable is restricted to the block scope. Whenever a local variable is declared inside a method, the other class methods don’t have any knowledge about the local variable.

core java problem solving questions

8. What are the default values assigned to variables and instances in java?

  • There are no default values assigned to the variables in java. We need to initialize the value before using it. Otherwise, it will throw a compilation error of ( Variable might not be initialized ). 
  • But for instance, if we create the object, then the default value will be initialized by the default constructor depending on the data type. 
  • If it is a reference, then it will be assigned to null. 
  • If it is numeric, then it will assign to 0.
  • If it is a boolean, then it will be assigned to false. Etc.

9. What do you mean by data encapsulation?

  • Data Encapsulation is an Object-Oriented Programming concept of hiding the data attributes and their behaviours in a single unit.
  • It helps developers to follow modularity while developing software by ensuring that each object is independent of other objects by having its own methods, attributes, and functionalities.
  • It is used for the security of the private properties of an object and hence serves the purpose of data hiding.

core java problem solving questions

10. Tell us something about JIT compiler.

  • JIT stands for Just-In-Time and it is used for improving the performance during run time. It does the task of compiling parts of byte code having similar functionality at the same time thereby reducing the amount of compilation time for the code to run.
  • First, the Java source code (.java) conversion to byte code (.class) occurs with the help of the javac compiler.
  • Then, the .class files are loaded at run time by JVM and with the help of an interpreter, these are converted to machine understandable code.
  • JIT compiler is a part of JVM. When the JIT compiler is enabled, the JVM analyzes the method calls in the .class files and compiles them to get more efficient and native code. It also ensures that the prioritized method calls are optimized.
  • Once the above step is done, the JVM executes the optimized code directly instead of interpreting the code again. This increases the performance and speed of the execution.

core java problem solving questions

11. Can you tell the difference between equals() method and equality operator (==) in Java?

We are already aware of the (==) equals operator. That we have used this to compare the equality of the values. But when we talk about the terms of object-oriented programming, we deal with the values in the form of objects. And this object may contain multiple types of data. So using the (==) operator does not work in this case. So we need to go with the . equals() method.

Both [(==) and .equals()] primary functionalities are to compare the values, but the secondary functionality is different. 

So in order to understand this better, let’s consider this with the example -

This code will print true. We know that both strings are equals so it will print true. But here (==) Operators don’t compare each character in this case. It compares the memory location. And because the string uses the constant pool for storing the values in the memory, both str1 and str2 are stored at the same memory location. See the detailed Explanation in Question no 73: Link .

core java problem solving questions

Now, if we modify the program a little bit with -

core java problem solving questions

Then in this case, it will print false. Because here no longer the constant pool concepts are used. Here, new memory is allocated. So here the memory address is different, therefore ( == ) Operator returns false. But the twist is that the values are the same in both strings. So how to compare the values? Here the .equals() method is used.

.equals() method compares the values and returns the result accordingly.  If we modify the above code with - 

Then it returns true.

  • In the cases where the equals method is not overridden in a class, then the class uses the default implementation of the equals method that is closest to the parent class.
  • Object class is considered as the parent class of all the java classes. The implementation of the equals method in the Object class uses the == operator to compare two objects. This default implementation can be overridden as per the business logic.

12. How is an infinite loop declared in Java?

Infinite loops are those loops that run infinitely without any breaking conditions. Some examples of consciously declaring infinite loop is:

  • Using For Loop:
  • Using while loop:
  • Using do-while loop:

13. Briefly explain the concept of constructor overloading

Constructor overloading is the process of creating multiple constructors in the class consisting of the same name with a difference in the constructor parameters. Depending upon the number of parameters and their corresponding types, distinguishing of the different types of constructors is done by the compiler.

core java problem solving questions

Three constructors are defined here but they differ on the basis of parameter type and their numbers.

14. Define Copy constructor in java.

Copy Constructor is the constructor used when we want to initialize the value to the new object from the old object of the same class. 

Here we are initializing the new object value from the old object value in the constructor. Although, this can also be achieved with the help of object cloning.

15. Can the main method be Overloaded?

Yes, It is possible to overload the main method. We can create as many overloaded main methods we want. However, JVM has a predefined calling method that JVM will only call the main method with the definition of - 

Consider the below code snippets: 

16. Comment on method overloading and overriding by citing relevant examples.

In Java, method overloading is made possible by introducing different methods in the same class consisting of the same name. Still, all the functions differ in the number or type of parameters. It takes place inside a class and enhances program readability.

The only difference in the return type of the method does not promote method overloading. The following example will furnish you with a clear picture of it.

core java problem solving questions

Both the functions have the same name but differ in the number of arguments. The first method calculates the area of the rectangle, whereas the second method calculates the area of a cuboid.

Method overriding is the concept in which two methods having the same method signature are present in two different classes in which an inheritance relationship is present. A particular method implementation (already present in the base class) is possible for the derived class by using method overriding. Let’s give a look at this example:

core java problem solving questions

Both class methods have the name walk and the same parameters, distance, and time. If the derived class method is called, then the base class method walk gets overridden by that of the derived class.

17. A single try block and multiple catch blocks can co-exist in a Java Program. Explain.

Yes, multiple catch blocks can exist but specific approaches should come prior to the general approach because only the first catch block satisfying the catch condition is executed. The given code illustrates the same:

Here, the second catch block will be executed because of division by 0 (i / x). In case x was greater than 0 then the first catch block will execute because for loop runs till i = n and array index are till n-1.

18. Explain the use of final keyword in variable, method and class.

In Java, the final keyword is used as defining something as constant /final and represents the non-access modifier.

  • When a variable is declared as final in Java, the value can’t be modified once it has been assigned.
  • If any value has not been assigned to that variable, then it can be assigned only by the constructor of the class.
  • A method declared as final cannot be overridden by its children's classes.
  • A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn't make sense. Java throws compilation error saying - modifier final not allowed here
  • No classes can be inherited from the class declared as final. But that final class can extend other classes for its usage.

19. Do final, finally and finalize keywords have the same function?

All three keywords have their own utility while programming.

Final: If any restriction is required for classes, variables, or methods, the final keyword comes in handy. Inheritance of a final class and overriding of a final method is restricted by the use of the final keyword. The variable value becomes fixed after incorporating the final keyword. Example:

The second statement will throw an error.

Finally: It is the block present in a program where all the codes written inside it get executed irrespective of handling of exceptions. Example:

Finalize: Prior to the garbage collection of an object, the finalize method is called so that the clean-up activity is implemented. Example:

20. Is it possible that the ‘finally’ block will not be executed? If yes then list the case.

 Yes. It is possible that the ‘finally’ block will not be executed. The cases are-

  • Suppose we use System.exit() in the above statement.
  • If there are fatal errors like Stack overflow, Memory access error, etc.

21. Identify the output of the java program and state the reason.

The above code will generate a compile-time error at Line 7 saying - [error: variable i might already have been initialized] . It is because variable ‘i’ is the final variable. And final variables are allowed to be initialized only once, and that was already done on line no 5.

22. When can you use super keyword?

  • The super keyword is used to access hidden fields and overridden methods or attributes of the parent class.
  • Accessing data members of parent class when the member names of the class and its child subclasses are same.
  • To call the default and parameterized constructor of the parent class inside the child class.
  • Accessing the parent class methods when the child classes have overridden them.
  • The following example demonstrates all 3 cases when a super keyword is used.

23. Can the static methods be overloaded?

Yes! There can be two or more static methods in a class with the same name but differing input parameters.

24. Why is the main method static in Java?

The main method is always static because static members are those methods that belong to the classes, not to an individual object. So if the main method will not be static then for every object, It is available. And that is not acceptable by JVM. JVM calls the main method based on the class name itself. Not by creating the object.

Because there must be only 1 main method in the java program as the execution starts from the main method. So for this reason the main method is static. 

25. Can the static methods be overridden?

  • No! Declaration of static methods having the same signature can be done in the subclass but run time polymorphism can not take place in such cases.
  • Overriding or dynamic polymorphism occurs during the runtime, but the static methods are loaded and looked up at the compile time statically. Hence, these methods cant be overridden.

26. Difference between static methods, static variables, and static classes in java.

  • For example - We have used mathematical functions in the java program like - max(), min(), sqrt(), pow(), etc. And if we notice that, then we will find that we call it directly with the class name. Like - Math.max(), Math.min(), etc. So that is a static method.  And Similarly static variables we have used like (length) for the array to get the length. So that is the static method.
  • Static classes - A class in the java program cannot be static except if it is the inner class. If it is an inner static class, then it exactly works like other static members of the class.

27. What is the main objective of garbage collection?

The main objective of this process is to free up the memory space occupied by the unnecessary and unreachable objects during the Java program execution by deleting those unreachable objects.

  • This ensures that the memory resource is used efficiently, but it provides no guarantee that there would be sufficient memory for the program execution.

28. What is a ClassLoader?

  • Java Classloader is the program that belongs to JRE (Java Runtime Environment). The task of ClassLoader is to load the required classes and interfaces to the JVM when required. 
  • Example- To get input from the console, we require the scanner class. And the Scanner class is loaded by the ClassLoader.

29. What part of memory - Stack or Heap - is cleaned in garbage collection process?

30. what are shallow copy and deep copy in java.

To copy the object's data, we have several methods like deep copy and shallow copy. 

Object for this Rectangle class - Rectangle obj1 = new Rectangle();

  • Shallow copy - The shallow copy only creates a new reference and points to the same object. Example - For Shallow copy, we can do this by -

Now by doing this what will happen is the new reference is created with the name obj2 and that will point to the same memory location.

  • Deep Copy - In a deep copy, we create a new object and copy the old object value to the new object. Example -

Both these objects will point to the memory location as stated below -

core java problem solving questions

Now, if we change the values in shallow copy then they affect the other reference as well. Let's see with the help of an example - 

We can see that in the above code, if we change the values of object1, then the object2 values also get changed. It is because of the reference.

Now, if we change the code to deep copy, then there will be no effect on object2 if it is of type deep copy. Consider some snippets to be added in the above code.

The above snippet will not affect the object2 values. It has its separate values. The output will be

Now we see that we need to write the number of codes for this deep copy. So to reduce this, In java, there is a method called clone().  

The clone() will do this deep copy internally and return a new object. And to do this we need to write only 1 line of code. That is - Rectangle obj2 = obj1.clone();

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

A String is made immutable due to the following reasons:

  • String Pool: Designers of Java were aware of the fact that String data type is going to be majorly used by the programmers and developers. Thus, they wanted optimization from the beginning. They came up with the notion of using the String pool (a storage area in Java heap) to store the String literals. They intended to decrease the temporary String object with the help of sharing. An immutable class is needed to facilitate sharing. The sharing of the mutable structures between two unknown parties is not possible. Thus, immutable Java String helps in executing the concept of String Pool.

core java problem solving questions

  • Multithreading : The safety of threads regarding the String objects is an important aspect in Java. No external synchronization is required if the String objects are immutable. Thus, a cleaner code can be written for sharing the String objects across different threads. The complex process of concurrency is facilitated by this method.
  • Collections : In the case of Hashtables and HashMaps, keys are String objects. If the String objects are not immutable, then it can get modified during the period when it resides in the HashMaps. Consequently, the retrieval of the desired data is not possible. Such changing states pose a lot of risks. Therefore, it is quite safe to make the string immutable.

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

Singleton classes are those classes, whose objects are created only once. And with only that object the class members can be accessed. 

Understand this with the help of an example-:

Consider the water jug in the office and if every employee wants that water then they will not create a new water jug for drinking water. They will use the existing one with their own reference as a glass. So programmatically it should be implemented as -

In the above class, the Constructor is private so we cannot create the object of the class. But we can get the object by calling the method getInstance() . And the getInstance is static so it can be called without creating the object. And it returns the object. Now with that object, we can call getWater() to get the water.

We can get the single object using this getInstance(). And it is static, so it is a thread-safe singleton class. Although there are many ways to create a thread-safe singleton class. So thread-safe classes can also be:

  • When singletons are written with double-checked locking, they can be thread-safe.
  • We can use static singletons that are initialized during class loading. Like we did in the above example.
  • But the most straightforward way to create a thread-safe singleton is to use Java enums.

3. Which of the below generates a compile-time error? State the reason.

  • int[] n1 = new int[0];
  • boolean[] n2 = new boolean[-200];
  • double[] n3 = new double[2241423798];
  • char[] ch = new char[20];

We get a compile-time error in line 3. The error we will get in Line 3 is - integer number too large . It is because the array requires size as an integer. And Integer takes 4 Bytes in the memory. And the number ( 2241423798 ) is beyond the capacity of the integer. The maximum array size we can declare is - ( 2147483647 ).

Because the array requires the size in integer, none of the lines (1, 2, and 4) will give a compile-time error. The program will compile fine. But we get the runtime exception in line 2. The exception is - NegativeArraySizeException . 

Here what will happen is - At the time when JVM will allocate the required memory during runtime then it will find that the size is negative. And the array size can’t be negative. So the JVM will throw the exception.

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

  • Storage area: In string, the String pool serves as the storage area. For StringBuilder and StringBuffer, heap memory is the storage area.
  • Mutability: A String is immutable, whereas both the StringBuilder and StringBuffer are mutable.
  • Efficiency: It is quite slow to work with a String. However, StringBuilder is the fastest in performing operations. The speed of a StringBuffer is more than a String and less than a StringBuilder. (For example appending a character is fastest in StringBuilder and very slow in String because a new memory is required for the new String with appended character.)
  • Thread-safe: In the case of a threaded environment, StringBuilder and StringBuffer are used whereas a String is not used. However, StringBuilder is suitable for an environment with a single thread, and a StringBuffer is suitable for multiple threads. Syntax:

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

  • Availability of methods: Only abstract methods are available in interfaces, whereas non-abstract methods can be present along with abstract methods in abstract classes.
  • Variable types : Static and final variables can only be declared in the case of interfaces, whereas abstract classes can also have non-static and non-final variables.
  • Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract classes do not promote multiple inheritances.
  • Data member accessibility: By default, the class data members of interfaces are of the public- type. Conversely, the class members for an abstract class can be protected or private also.
  • Implementation: With the help of an abstract class, the implementation of an interface is easily possible. However, the converse is not true;

Abstract class example:

Interface example:

6. Is this program giving a compile-time error? If Yes then state the reason and number of errors it will give. If not then state the reason.

The above program will give a compile-time error. The compiler will throw 2 errors in this.

  • [Illegal Combination of modifiers: abstract and final] at line 1.
  • [Cannot inherit from final ‘InterviewBit’] at line 4.

It is because abstract classes are incomplete classes that need to be inherited for making their concrete classes. And on the other hand, the final keywords in class are used for avoiding inheritance. So these combinations are not allowed in java.

7. What is a Comparator in java?

Consider the example where we have an ArrayList of employees like( EId, Ename, Salary), etc. Now if we want to sort this list of employees based on the names of employees. Then that is not possible to sort using the Collections.sort() method. We need to provide something to the sort() function depending on what values we have to perform sorting. Then in that case a comparator is used.

Comparator is the interface in java that contains the compare method. And by overloading the compare method, we can define that on what basis we need to compare the values. 

8. In Java, static as well as private method overriding is possible. Comment on the statement.

The statement in the context is completely False. The static methods have no relevance with the objects, and these methods are of the class level. In the case of a child class, a static method with a method signature exactly like that of the parent class can exist without even throwing any compilation error.

The phenomenon mentioned here is popularly known as method hiding, and overriding is certainly not possible. Private method overriding is unimaginable because the visibility of the private method is restricted to the parent class only. As a result, only hiding can be facilitated and not overriding.

9. What makes a HashSet different from a TreeSet?

Although both HashSet and TreeSet are not synchronized and ensure that duplicates are not present, there are certain properties that distinguish a HashSet from a TreeSet.

  • Implementation: For a HashSet, the hash table is utilized for storing the elements in an unordered manner. However, TreeSet makes use of the red-black tree to store the elements in a sorted manner.
  • Complexity/ Performance: For adding, retrieving, and deleting elements, the time amortized complexity is O(1) for a HashSet. The time complexity for performing the same operations is a bit higher for TreeSet and is equal to O(log n). Overall, the performance of HashSet is faster in comparison to TreeSet.
  • Methods: hashCode() and equals() are the methods utilized by HashSet for making comparisons between the objects. Conversely, compareTo() and compare() methods are utilized by TreeSet to facilitate object comparisons.
  • Objects type: Heterogeneous and null objects can be stored with the help of HashSet. In the case of a TreeSet, runtime exception occurs while inserting heterogeneous objects or null objects.

10. Why is the character array preferred over string for storing confidential information?

In Java, a string is basically immutable i.e. it cannot be modified. After its declaration, it continues to stay in the string pool as long as it is not removed in the form of garbage. In other words, a string resides in the heap section of the memory for an unregulated and unspecified time interval after string value processing is executed.

As a result, vital information can be stolen for pursuing harmful activities by hackers if a memory dump is illegally accessed by them. Such risks can be eliminated by using mutable objects or structures like character arrays for storing any variable. After the work of the character array variable is done, the variable can be configured to blank at the same instant. Consequently, it helps in saving heap memory and also gives no chance to the hackers to extract vital data.

11. What do we get in the JDK file?

  • JDK - For making java programs, we need some tools that are provided by JDK (Java Development Kit). JDK is the package that contains various tools, Compiler, Java Runtime Environment, etc.
  • JRE -  To execute the java program we need an environment. (Java Runtime Environment) JRE contains a library of Java classes +  JVM. What are JAVA Classes?  It contains some predefined methods that help Java programs to use that feature, build and execute. For example - there is a system class in java that contains the print-stream method, and with the help of this, we can print something on the console.
  • JVM - (Java Virtual Machine) JVM  is a part of JRE that executes the Java program at the end.  Actually, it is part of JRE, but it is software that converts bytecode into machine-executable code to execute on hardware.

core java problem solving questions

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

13. what are the differences between hashmap and hashtable in java, 14. what is the importance of reflection in java.

  • The term reflection is used for describing the inspection capability of a code on other code either of itself or of its system and modify it during runtime.
  • Consider an example where we have an object of unknown type and we have a method ‘fooBar()’ which we need to call on the object. The static typing system of Java doesn't allow this method invocation unless the type of the object is known beforehand. This can be achieved using reflection which allows the code to scan the object and identify if it has any method called “fooBar()” and only then call the method if needed.
  • Speed — Method invocations due to reflection are about three times slower than the direct method calls.
  • Type safety — When a method is invoked via its reference wrongly using reflection, invocation fails at runtime as it is not detected at compile/load time.
  • Traceability — Whenever a reflective method fails, it is very difficult to find the root cause of this failure due to a huge stack trace. One has to deep dive into the invoke() and proxy() method logs to identify the root cause.
  • Hence, it is advisable to follow solutions that don't involve reflection and use this method as a last resort.

15. What are the different ways of threads usage?

  • Extending the Thread class
  • Implementing the Runnable interface
  • Implementing a thread using the method of Runnable interface is more preferred and advantageous as Java does not have support for multiple inheritances of classes.
  • start() method is used for creating a separate call stack for the thread execution. Once the call stack is created, JVM calls the run() method for executing the thread in that call stack.

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

There are a total of 3 different types of priority available in Java. 

MIN_PRIORITY: It has an integer value assigned with 1. MAX_PRIORITY: It has an integer value assigned with 10. NORM_PRIORITY: It has an integer value assigned with 5.

In Java, Thread with MAX_PRIORITY gets the first chance to execute. But the default priority for any thread is NORM_PRIORITY assigned by JVM. 

17. What is the difference between the program and the process?

  • A program can be defined as a line of code written in order to accomplish a particular task. Whereas the process can be defined as the programs which are under execution. 
  • A program doesn't execute directly by the CPU. First, the resources are allocated to the program and when it is ready for execution then it is a process.

18. What is the difference between the ‘throw’ and ‘throws’ keyword in java?

  • The ‘ throw ’ keyword is used to manually throw the exception to the calling method.
  • And the ‘ throws ’ keyword is used in the function definition to inform the calling method that this method throws the exception. So if you are calling, then you have to handle the exception.

Here in the above snippet, the method testExceptionDivide throws an exception. So if the main method is calling it then it must have handled the exception. Otherwise, the main method can also throw the exception to JVM.

And the method testExceptionDivide 'throws’ the exception based on the condition.

19. What are the differences between constructor and method of a class in Java?

20. identify the output of the below java program and justify your answer..

The above code will throw the compilation error. It is because the super() is used to call the parent class constructor. But there is the condition that super() must be the first statement in the block. Now in this case, if we replace this() with super() then also it will throw the compilation error. Because this() also has to be the first statement in the block. So in conclusion, we can say that we cannot use this() and super() keywords in the same block.

21. Java works as “pass by value” or “pass by reference” phenomenon?

Java always works as a “pass by value”. There is nothing called a “pass by reference” in Java. However, when the object is passed in any method, the address of the value is passed due to the nature of object handling in Java. When an object is passed, a copy of the reference is created by Java and that is passed to the method. The objects point to the same memory location. 2 cases might happen inside the method:

  • Case 1: When the object is pointed to another location: In this case, the changes made to that object do not get reflected the original object before it was passed to the method as the reference points to another location.

For example:

  • Case 2: When object references are not modified: In this case, since we have the copy of reference the main object pointing to the same memory location, any changes in the content of the object get reflected in the original object.

22. What is the ‘IS-A ‘ relationship in OOPs java?

‘IS-A’ relationship is another name for inheritance. When we inherit the base class from the derived class, then it forms a relationship between the classes. So that relationship is termed an ‘IS-A’ Relationship.

Example - Consider a Television (Typical CRT TV). Now another Smart TV  that is inherited from television class. So we can say that the Smart iv is also a TV. Because CRT TV things can also be done in the Smart TV.

core java problem solving questions

So here ‘IS-A’ Relationship formed. [ SmartTV ‘IS-A’ TV ] .

23. Which among String or String Buffer should be preferred when there are lot of updates required to be done in the data?

StringBuffer is mutable and dynamic in nature whereas String is immutable. Every updation / modification of String creates a new String thereby overloading the string pool with unnecessary objects. Hence, in the cases of a lot of updates, it is always preferred to use StringBuffer as it will reduce the overhead of the creation of multiple String objects in the string pool.

24. How to not allow serialization of attributes of a class in Java?

  • In order to achieve this, the attribute can be declared along with the usage of transient keyword as shown below:
  • In the above example, all the fields except someInfo can be serialized.

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

There wouldn't be any compilation error. But then the program is run, since the JVM cant map the main method signature, the code throws “NoSuchMethodError” error at the runtime.

26. Consider the below program, identify the output, and also state the reason for that.

The output of the above program will be Hello. Main Method . This is because JVM will always call the main method based on the definition it already has. Doesn't matter how many main methods we overload it will only execute one main method based on its declaration in JVM.

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

In java multithreading, the main() threads are always non-daemon threads. And there is no way we can change the nature of the non-daemon thread to the daemon thread.

28. What happens if there are multiple main methods inside one class in Java?

The program can't compile as the compiler says that the method has been already defined inside the class.

29. What do you understand by Object Cloning and how do you achieve it in Java?

  • It is the process of creating an exact copy of any object. In order to support this, a java class has to implement the Cloneable interface of java.lang package and override the clone() method provided by the Object class the syntax of which is:
  • In case the Cloneable interface is not implemented and just the method is overridden, it results in CloneNotSupportedException in Java.

30. How does an exception propagate in the code?

When an exception occurs, first it searches to locate the matching catch block. In case, the matching catch block is located, then that block would be executed. Else, the exception propagates through the method call stack and goes into the caller method where the process of matching the catch block is performed. This propagation happens until the matching catch block is found. If the match is not found, then the program gets terminated in the main method.

core java problem solving questions

31. How do exceptions affect the program if it doesn't handle them?

Exceptions are runtime errors. Suppose we are making an android application with java. And it all works fine but there is an exceptional case when the application tries to get the file from storage and the file doesn’t exist (This is the case of exception in java). And if this case is not handled properly then the application will crash. This will be a bad experience for users.  This is the type of error that cannot be controlled by the programmer. But programmers can take some steps to avoid this so that the application won’t crash. The proper action can be taken at this step.

32. Is it mandatory for a catch block to be followed after a try block?

No, it is not necessary for a catch block to be present after a try block. - A try block should be followed either by a catch block or by a finally block. If the exceptions likelihood is more, then they should be declared using the throws clause of the method.

33. Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below?

finally block will be executed irrespective of the exception or not. The only case where finally block is not executed is when it encounters ‘System.exit()’ method anywhere in try/catch block.

34. Can you call a constructor of a class inside the another constructor?

Yes, the concept can be termed as constructor chaining and can be achieved using this() .

core java problem solving questions

35. Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList. Explain.

In the case of ArrayList, data storing in the form of primitive data types (like int, float, etc.) is not possible. The data members/objects present in the ArrayList have references to the objects which are located at various sites in the memory. Thus, storing of actual objects or non-primitive data types (like Integer, Double, etc.) takes place in various memory locations.

core java problem solving questions

However, the same does not apply to the arrays. Object or primitive type values can be stored in arrays in contiguous memory locations, hence every element does not require any reference to the next element.

core java problem solving questions

36. Why does the java array index start with 0?

It is because the 0 index array avoids the extra arithmetic operation to calculate the memory address.

Example - Consider the array and assume each element takes 4-byte memory space. Then the address will be like this -

core java problem solving questions

Now if we want to access index 4. Then internally java calculates the address using the formula-

[Base Address + (index * no_of_bytes)] . So according to this. The starting address of the index 4 will be - [100 + (4*4)] = 116 . And exactly that's what the address is calculated.  Now consider the same with 1 index Array -

core java problem solving questions

Now if we apply the same formula here. Then we get - 116 as the starting address of the 4th index. Which is wrong. Then we need to apply formula - [ Base Address + ((index-1) * no_of_bytes)] .

And for calculating this, an extra arithmetic operation has to be performed. And consider the case where millions of addresses need to be calculated, this causes complexity. So to avoid this, ) the index array is supported by java.

37. Why is the remove method faster in the linked list than in an array?

In the linked list, we only need to adjust the references when we want to delete the element from either end or the front of the linked list. But in the array, indexes are used. So to manage proper indexing, we need to adjust the values from the array So this adjustment of value is costlier than the adjustment of references.

Example - To Delete from the front of the linked list, internally the references adjustments happened like this.

core java problem solving questions

The only thing that will change is that the head pointer will point to the head’s next node. And delete the previous node. That is the constant time operation.

Whereas in the ArrayList, internally it should work like this-

core java problem solving questions

For deletion of the first element, all the next element has to move to one place ahead. So this copying value takes time. So that is the reason why removing in ArrayList is slower than LinkedList.

38. How many overloaded add() and addAll() methods are available in the List interface? Describe the need and uses.

There are a total of 4 overloaded methods for add() and addAll() methods available in List Interface. The below table states the description of all.

39. How does the size of ArrayList grow dynamically? And also state how it is implemented internally.

ArrayList is implemented in such a way that it can grow dynamically. We don't need to specify the size of ArrayList. For adding the values in it, the methodology it uses is -

1. Consider initially that there are 2 elements in the ArrayList. [2, 3] .

core java problem solving questions

2. If we need to add the element into this. Then internally what will happen is-

  • ArrayList will allocate the new ArrayList of Size (current size + half of the current size). And add the old elements into the new. Old - [2, 3],    New - [2, 3, null].

core java problem solving questions

  • Then the new value will be inserted into it. [2, 3, 4, null]. And for the next time, the extra space will be available for the value to be inserted.

core java problem solving questions

3. This process continues and the time taken to perform all of these is considered as the amortized constant time. 

This is how the ArrayList grows dynamically. And when we delete any entry from the ArrayList then the following steps are performed -

1. It searches for the element index in the array. Searching takes some time. Typically it’s O(n) because it needs to search for the element in the entire array.

core java problem solving questions

2. After searching the element, it needs to shift the element from the right side to fill the index.

core java problem solving questions

So this is how the elements are deleted from the ArrayList internally. Similarly, the search operations are also implemented internally as defined in removing elements from the list (searching for elements to delete).

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

Inheritance lags behind composition in the following scenarios:

  • Multiple-inheritance is not possible in Java. Classes can only extend from one superclass. In cases where multiple functionalities are required, for example - to read and write information into the file, the pattern of composition is preferred. The writer, as well as reader functionalities, can be made use of by considering them as the private members.
  • Composition assists in attaining high flexibility and prevents breaking of encapsulation.
  • Unit testing is possible with composition and not inheritance. When a developer wants to test a class composing a different class, then Mock Object can be created for signifying the composed class to facilitate testing. This technique is not possible with the help of inheritance as the derived class cannot be tested without the help of the superclass in inheritance.
  • The loosely coupled nature of composition is preferable over the tightly coupled nature of inheritance.

Let’s take an example:

In the above example, inheritance is followed. Now, some modifications are done to the Top class like this:

If the new implementation of the Top class is followed, a compile-time error is bound to occur in the Bottom class. Incompatible return type is there for the Top.stop() function. Changes have to be made to either the Top or the Bottom class to ensure compatibility. However, the composition technique can be utilized to solve the given problem:

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

These 2 are the bitwise right shift operators. Although both operators look similar. But there is a minimal difference between these two right shift operators.

  • ‘>>’ Bitwise Right Shift Operator - This operator shifts each bit to its right position. And this maintains the signed bit.
  • ‘>>>’ Bitwise Right Shift Operator with trailing zero - This operator also shifts each bit to its right. But this doesn’t maintain the signed bit. This operator makes the Most significant bit to 0.

Example- Num1 = 8, Num2 = -8.

So the binary form of these numbers are - 

Num1 = 00000000 00000000 00000000 00001000  Num2 = 11111111 11111111 11111111  11111000

‘>>’ Operator : 8 >> 1 (Shift by one bit) : 

Num1 = 00000000 00000000 00000000 00000100 Num2 = 11111111 11111111 11111111  11111100

‘>>>’ Operator : 8 >>> 1 (Shift by one bit) = 

Num1 = 00000000 00000000 00000000 00000100 Num2 = 01111111 11111111 11111111 11111100

3. What are Composition and Aggregation? State the difference.

Composition, and Aggregation help to build (Has - A - Relationship) between classes and objects. But both are not the same in the end. Let’s understand with the help of an example. 

  • Consider the University as a class that has some departments in it. So the university will be the container object. And departments in it will contain objects. Now in this case, if the container object destroys then the contained objects will also get destroyed automatically.  So here we can say that there is a strong association between the objects. So this Strong Association is called Composition .
  • Now consider one more example. Suppose we have a class department and there are several professors' objects there in the department. Now if the department class is destroyed then the professor's object will become free to bind with other objects. Because container objects (Department) only hold the references of contained objects (Professor’s). So here is the weak association between the objects. And this weak association is called Aggregation .

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

When a String is formed as a literal with the assistance of an assignment operator, it makes its way into the String constant pool so that String Interning can take place. This same object in the heap will be referenced by a different String if the content is the same for both of them.

The checking() function will return true as the same content is referenced by both the variables.

core java problem solving questions

Conversely, when a String formation takes place with the help of a new() operator, interning does not take place. The object gets created in the heap memory even if the same content object is present.

The checking() function will return false as the same content is not referenced by both the variables.

core java problem solving questions

5. How is the ‘new’ operator different from the ‘newInstance()’ operator in java?

Both ‘ new ’ and ‘ newInstance() ’ operators are used to creating objects. The difference is- that when we already know the class name for which we have to create the object then we use a new operator. But suppose we don’t know the class name for which we need to create the object, Or we get the class name from the command line argument, or the database, or the file. Then in that case we use the ‘ newInstance() ’ operator.

The ‘ newInstance() ’ keyword throws an exception that we need to handle. It is because there are chances that the class definition doesn’t exist, and we get the class name from runtime. So it will throw an exception.

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

Yes, it is possible for the program to go out of memory in spite of the presence of a garbage collector. Garbage collection assists in recognizing and eliminating those objects which are not required in the program anymore, in order to free up the resources used by them.

In a program, if an object is unreachable, then the execution of garbage collection takes place with respect to that object. If the amount of memory required for creating a new object is not sufficient, then memory is released for those objects which are no longer in the scope with the help of a garbage collector. The memory limit is exceeded for the program when the memory released is not enough for creating new objects.

Moreover, exhaustion of the heap memory takes place if objects are created in such a manner that they remain in the scope and consume memory. The developer should make sure to dereference the object after its work is accomplished. Although the garbage collector endeavors its level best to reclaim memory as much as possible, memory limits can still be exceeded.

Let’s take a look at the following example:

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

Concurrent execution of different processes is made possible by synchronization. When a particular resource is shared between many threads, situations may arise in which multiple threads require the same shared resource.

Synchronization assists in resolving the issue and the resource is shared by a single thread at a time. Let’s take an example to understand it more clearly. For example, you have a URL and you have to find out the number of requests made to it. Two simultaneous requests can make the count erratic.

No synchronization:

core java problem solving questions

If a thread Thread1 views the count as 10, it will be increased by 1 to 11. Simultaneously, if another thread Thread2 views the count as 10, it will be increased by 1 to 11. Thus, inconsistency in count values takes place because the expected final value is 12 but the actual final value we get will be 11.

Now, the function increase() is made synchronized so that simultaneous accessing cannot take place.

With synchronization:

core java problem solving questions

If a thread Thread1 views the count as 10, it will be increased by 1 to 11, then the thread Thread2 will view the count as 11, it will be increased by 1 to 12. Thus, consistency in count values takes place.

8. In the given code below, what is the significance of ... ?

  • Ability to provide ... is a feature called varargs (variable arguments) which was introduced as part of Java 5.
  • The function having ... in the above example indicates that it can receive multiple arguments of the datatype String.
  • For example, the fooBarMethod can be called in multiple ways and we can still have one method to process the data as shown below:

9. What will be the output of the below java program and define the steps of Execution of the java program with the help of the below code?

The Output we get by executing this program will be

Static Block 1. Value of j = 0 Static method.  Static Block 2. Value of j = 10 Instance Block 1. Value of i = 0 Instance Block 2. Value of i = 5 Instance method.  Welcome to InterviewBit

This is a java tricky interview question frequently asked in java interviews for the experienced. The output will be like this because, when the java program is compiled and gets executed, then there are various steps followed for execution. And the steps are - 

  • Identification of Static Members from top to bottom.
  • Execution of Static variable assignment and a Static block from top to bottom.
  • Execution of the main method.
  • Identification of Instance Members from top to bottom.
  • Execution of Instance variable assignment and Instance block from top to bottom.
  • Execution of Constructor.

In above steps from 4 to 6, will be executed for every object creation. If we create multiple objects then for every object these steps will be performed.

Now from the above code, the execution will happen like this - 

1. In the step of identification of static members. It is found that -

  • static int j.
  • static block.
  • main method.
  • static method_2.

During identification, the JVM will assign the default value in the static int j variable. Then it is currently in the state of reading and indirectly writing. Because the original value is not assigned.

2. In the next step, it will execute the static block and assign the value in static variables.

  • First static block it will print and because execution from top to bottom and original value in j is not assigned. So it will print the default value of 0.
  • After executing static block 1. It will execute the static method_1 because it is called from the static block 1.
  • Then it will assign the original value of 5 in the j variable. And executes the remaining static block.

3. Now it will execute the main method. In which it will create an object for the class InterviewBit. And then the execution of instances will happen.

4. Identify the instance variables and blocks from top to bottom. 

  • Instance block 1.
  • Instance method_1.

Like a static variable, the instance variable also has been initialized with the default value 0 and will be in the state of reading and writing indirectly.

5. It will execute the instance methods and assign the original value to the instance variable.

  • Prints the Instance block 1. And the current value of i is not assigned till now, so it will print 0.
  • Assign the original value to i. Then print instance block 2. And after that instance method will be called and printed because it is being called in the instance block.

6. And at the last step, the constructor will be invoked and the lines will be executed in the constructor.

This is how the java program gets executed.

10. Define System.out.println().

System.out.println() is used to print the message on the console. System - It is a class present in java.lang package . Out is the static variable of type PrintStream class present in the System class. println() is the method present in the PrintStream class.

So if we justify the statement, then we can say that if we want to print anything on the console then we need to call the println() method that was present in PrintStream class. And we can call this using the output object that is present in the System class.

11. Can you explain the Java thread lifecycle?

Java thread life cycle is as follows:

  • New – When the instance of the thread is created and the start() method has not been invoked, the thread is considered to be alive and hence in the NEW state.
  • Runnable – Once the start() method is invoked, before the run() method is called by JVM, the thread is said to be in RUNNABLE (ready to run) state. This state can also be entered from the Waiting or Sleeping state of the thread.
  • Running – When the run() method has been invoked and the thread starts its execution, the thread is said to be in a RUNNING state.
  • A thread is said to be in a Blocked state if it wants to enter synchronized code but it is unable to as another thread is operating in that synchronized block on the same object. The first thread has to wait until the other thread exits the synchronized block.
  • A thread is said to be in a Waiting state if it is waiting for the signal to execute from another thread, i.e it waits for work until the signal is received.
  • Terminated – Once the run() method execution is completed, the thread is said to enter the TERMINATED step and is considered to not be alive.

The following flowchart clearly explains the lifecycle of the thread in Java.

core java problem solving questions

12. What could be the tradeoff between the usage of an unordered array versus the usage of an ordered array?

  • The main advantage of having an ordered array is the reduced search time complexity of O(log n) whereas the time complexity in an unordered array is O(n) .
  • The main drawback of the ordered array is its increased insertion time which is O(n) due to the fact that its element has to reordered to maintain the order of array during every insertion whereas the time complexity in the unordered array is only O(1).
  • Considering the above 2 key points and depending on what kind of scenario a developer requires, the appropriate data structure can be used for implementation.

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

It is possible to import a class or package more than once, however, it is redundant because the JVM internally loads the package or class only once.

14. In case a package has sub packages, will it suffice to import only the main package? e.g. Does importing of com.myMainPackage.* also import com.myMainPackage.mySubPackage.*?

This is a big NO. We need to understand that the importing of the sub-packages of a package needs to be done explicitly. Importing the parent package only results in the import of the classes within it and not the contents of its child/sub-packages.

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

NO. The control of the program post System.exit(0) is immediately gone and the program gets terminated which is why the finally block never gets executed.

16. What do you understand by marker interfaces in Java?

Marker interfaces, also known as tagging interfaces are those interfaces that have no methods and constants defined in them. They are there for helping the compiler and JVM to get run time-related information regarding the objects.

17. Explain the term “Double Brace Initialisation” in Java?

This is a convenient means of initializing any collections in Java. Consider the below example.

In the above example, we see that the stringSets were initialized by using double braces.

  • The first brace does the task of creating an anonymous inner class that has the capability of accessing the parent class’s behavior. In our example, we are creating the subclass of HashSet so that it can use the add() method of HashSet.
  • The second braces do the task of initializing the instances.

Care should be taken while initializing through this method as the method involves the creation of anonymous inner classes which can cause problems during the garbage collection or serialization processes and may also result in memory leaks.

18. Why is it said that the length() method of String class doesn't return accurate results?

  • The length method returns the number of Unicode units of the String. Let's understand what Unicode units are and what is the confusion below.
  • Code Point: This represents an integer denoting a character in the code space.
  • Code Unit: This is a bit sequence used for encoding the code points. In order to do this, one or more units might be required for representing a code point.
  • The code points from the first plane are encoded using one 16-bit code unit
  • The code points from the remaining planes are encoded using two code units.

Now if a string contained supplementary characters, the length function would count that as 2 units and the result of the length() function would not be as per what is expected.

In other words, if there is 1 supplementary character of 2 units, the length of that SINGLE character is considered to be TWO - Notice the inaccuracy here? As per the java documentation, it is expected, but as per the real logic, it is inaccurate.

19. What is the output of the below code and why?

“bit” would have been the result printed if the letters were used in double-quotes (or the string literals). But the question has the character literals (single quotes) being used which is why concatenation wouldn't occur. The corresponding ASCII values of each character would be added and the result of that sum would be printed. The ASCII values of ‘b’, ‘i’, ‘t’ are:

98 + 105 + 116 = 319

Hence 319 would be printed.

20. What are the possible ways of making object eligible for garbage collection (GC) in Java?

First Approach: Set the object references to null once the object creation purpose is served.

Second Approach: Point the reference variable to another object. Doing this, the object which the reference variable was referencing before becomes eligible for GC.

Third Approach: Island of Isolation Approach: When 2 reference variables pointing to instances of the same class, and these variables refer to only each other and the objects pointed by these 2 variables don't have any other references, then it is said to have formed an “Island of Isolation” and these 2 objects are eligible for GC.

21. In the below Java Program, how many objects are eligible for garbage collection?

In the above program, a total of 7 objects will be eligible for garbage collection. Let’s visually understand what's happening in the code.

core java problem solving questions

In the above figure on line 3, we can see that on each array index we are declaring a new array so the reference will be of that new array on all the 3 indexes. So the old array will be pointed to by none. So these three are eligible for garbage collection. And on line 4, we are creating a new array object on the older reference. So that will point to a new array and older multidimensional objects will become eligible for garbage collection.

22. What is the best way to inject dependency? Also, state the reason.

There is no boundation for using a particular dependency injection. But the recommended approach is - 

Setters are mostly recommended for optional dependencies injection, and constructor arguments are recommended for mandatory ones. This is because constructor injection enables the injection of values into immutable fields and enables reading them more easily.

23. How we can set the spring bean scope. And what supported scopes does it have?

A scope can be set by an annotation such as the @Scope annotation or the "scope" attribute in an XML configuration file. Spring Bean supports the following five scopes:

  • Global-session

24. What are the different categories of Java Design patterns?

Java Design patterns are categorized into the following different types. And those are also further categorized as 

Structural patterns:

Behavioral patterns:

  • Interpreter
  • Template method/ pattern
  • Chain of responsibility
  • Command pattern
  • Iterator pattern
  • Strategy pattern
  • Visitor pattern

J2EE patterns:

  • MVC Pattern
  • Data Access Object pattern
  • Front controller pattern
  • Intercepting filter pattern
  • Transfer object pattern

Creational patterns:

  • Factory method/Template
  • Abstract Factory

25. What is a Memory Leak? Discuss some common causes of it.

The Java Garbage Collector (GC) typically removes unused objects when they are no longer required, but when they are still referenced, the unused objects cannot be removed. So this causes the memory leak problem. Example - Consider a linked list like the structure below -

core java problem solving questions

In the above image, there are unused objects that are not referenced. But then also Garbage collection will not free it. Because it is referencing some existing referenced object. So this can be the situation of memory leak.

Some common causes of Memory leaks are - 

  • When there are Unbounded caches.
  • Excessive page swapping is done by the operating system.
  • Improper written custom data structures.
  • Inserting into a collection object without first deleting it. etc.

26. Assume a thread has a lock on it, calling the sleep() method on that thread will release the lock?

A thread that has a lock won't be released even after it calls sleep(). Despite the thread sleeping for a specified period of time, the lock will not be released.

1. Check if a given string is palindrome using recursion.

/* * Java program to check if a given inputted string is palindrome or not using recursion. */ import java.util.*; public class InterviewBit { public static void main (String args[]) { Scanner s = new Scanner(System.in); String word = s.nextLine(); System.out.println( "Is " +word+ " palindrome? - " +isWordPalindrome(word)); } public static boolean isWordPalindrome (String word) { String reverseWord = getReverseWord(word); //if word equals its reverse, then it is a palindrome if (word.equals(reverseWord)){ return true ; } return false ; } public static String getReverseWord (String word) { if (word == null || word.isEmpty()){ return word; } return word.charAt(word.length()- 1 ) + getReverseWord(word.substring( 0 , word.length() - 1 )); } }

2. Write a Java Program to print Fibonacci Series using Recursion.

In the above code, we are printing the base 2 Fibonacci values 0 and 1. And then based on the length of Fibonacci to be printed, we are using the helper function to print that.

3. Write a Java program to check if the two strings are anagrams.

The main idea is to validate the length of strings and then if found equal, convert the string to char array and then sort the arrays and check if both are equal.

4. Write a Java Program to find the factorial of a given number.

public class FindFactorial { public static void main (String[] args) { int num = 10 ; long factorialResult = 1l ; for ( int i = 1 ; i <= num; ++i) { factorialResult *= i; } System.out.println( "Factorial: " +factorialResult); } }

5. Given an array of non-duplicating numbers from 1 to n where one number is missing, write an efficient java program to find that missing number.

Idea is to find the sum of n natural numbers using the formula and then finding the sum of numbers in the given array. Subtracting these two sums results in the number that is the actual missing number. This results in O(n) time complexity and O(1) space complexity.

6. Write a Java Program to check if any number is a magic number or not. A number is said to be a magic number if after doing sum of digits in each step and inturn doing sum of digits of that sum, the ultimate result (when there is only one digit left) is 1.

Example, consider the number:

  • Step 1: 163 => 1+6+3 = 10
  • Step 2: 10 => 1+0 = 1 => Hence 163 is a magic number

7. Write a Java program to create and throw custom exceptions.

We have created the exception class named with CustomException and called the base exception constructor with the error message that we want to print. And to avoid handling exceptions in the main method, we have used the throws keyword in the method declaration.

8. Write a Java program to reverse a string.

In the above code, we are storing the last character from the string to the first and the first value to the last in the output character array. And doing the same thing in the loop for the remaining 2nd to n-1 characters. This is how the string will be reversed.

9. Write a Java program to rotate arrays 90 degree clockwise by taking matrices from user input.

In the above code, for rotating the matrix to  90 degrees we are first transposing the matrix so the row becomes the column. And after that, we are reversing each row in the matrix. So this is how the matrix got rotated.

10. Write a java program to check if any number given as input is the sum of 2 prime numbers.

18 = 13 + 5 18 = 11 + 7

In the above code, for any number n , we find all the 2 pairs of numbers that are added together resulting in n . And each checking number if it is prime. If it is prime then we are printing that.

11. Write a Java program for solving the Tower of Hanoi Problem.

In the above code we are first moving the n-1 disk from Tower A to Tower B , then moving that nth disk from Tower A to Tower C , and finally, the remaining n-1 disk from Tower B to Tower C . And we are doing this recursively for the n-1 disk.

12. Implement Binary Search in Java using recursion.

In the above code, we are finding the middle element each time and checking if the element is in the middle or not. If it is not, then we check on which side from the middle it exists. And Recursively searching on the particular subarray. So this way we are reducing the search space by 2 every time. So the search time is very low.

1. Conclusion

Java is one of the simple high-level languages that provides powerful tools and impressive standards required for application development. It was also one of the first languages to provide amazing threading support for tackling concurrency-based problems. The easy-to-use syntax and the built-in features of Java combined with the stability it provides to applications are the main reasons for this language has ever-growing usage in the software community.

Interview Preparation Resources

  • How to Become a Java Developer?
  • How much does a Java Developer earn in India?
  • Java Projects
  • Java Programming Questions for Interview
  • Java 8 Interview Questions
  • Java String Interview Questions
  • Spring Interview Questions
  • Hibernate Interview Questions
  • Java Collections Interview Questions
  • Array Interview Questions
  • Design Patterns Interview Questions
  • Multithreading Interview Questions
  • Java Tutorial
  • Advance Java MCQ
  • Difference Between C++ and Java
  • Difference Between C and Java
  • Difference Between Java and Javascript
  • Hashmap vs Hashtable in Java
  • Kotlin Vs Java
  • Java Vs Python
  • Features of Java 9
  • Java 8 Features
  • Java Frameworks
  • Java Developer Skills
  • Java 11 Features
  • Additional Technical Interview Questions
  • JAVA SE Download

Coding Problems

What is the component used for compiling, debugging, and executing java programs?

What component does the task of bytecode to machine code conversion?

Which of the following is the functionality of the java interpreter?

When an object has its own lifecycle and its child object cant belong to another parent object, what is it called?

What is the output of the below piece of code?

What is the output of the following code?

Which of the following happens when the garbage collection process kicks off during the execution of the thread?

What is the output of the below code?

What is the functionality of Class.getInstance() ?

  • Privacy Policy

instagram-icon

  • Practice Questions
  • Programming
  • System Design
  • Fast Track Courses
  • Online Interviewbit Compilers
  • Online C Compiler
  • Online C++ Compiler
  • Online Java Compiler
  • Online Javascript Compiler
  • Online Python Compiler
  • Interview Preparation
  • Sql Interview Questions
  • Python Interview Questions
  • Javascript Interview Questions
  • Angular Interview Questions
  • Networking Interview Questions
  • Selenium Interview Questions
  • Data Structure Interview Questions
  • Data Science Interview Questions
  • System Design Interview Questions
  • Hr Interview Questions
  • Html Interview Questions
  • C Interview Questions
  • Amazon Interview Questions
  • Facebook Interview Questions
  • Google Interview Questions
  • Tcs Interview Questions
  • Accenture Interview Questions
  • Infosys Interview Questions
  • Capgemini Interview Questions
  • Wipro Interview Questions
  • Cognizant Interview Questions
  • Deloitte Interview Questions
  • Zoho Interview Questions
  • Hcl Interview Questions
  • Highest Paying Jobs In India
  • Exciting C Projects Ideas With Source Code
  • Top Java 8 Features
  • Angular Vs React
  • 10 Best Data Structures And Algorithms Books
  • Best Full Stack Developer Courses
  • Best Data Science Courses
  • Python Commands List
  • Data Scientist Salary
  • Maximum Subarray Sum Kadane’s Algorithm
  • Python Cheat Sheet
  • C++ Cheat Sheet
  • Javascript Cheat Sheet
  • Git Cheat Sheet
  • Java Cheat Sheet
  • Data Structure Mcq
  • C Programming Mcq
  • Javascript Mcq

1 Million +

Java Inheritance I Easy Java (Basic) Max Score: 5 Success Rate: 98.20%

Java inheritance ii easy java (basic) max score: 10 success rate: 97.68%, java abstract class easy java (basic) max score: 10 success rate: 98.58%, java interface easy java (basic) max score: 10 success rate: 98.16%, java method overriding easy java (basic) max score: 10 success rate: 98.87%, java method overriding 2 (super keyword) easy java (basic) max score: 10 success rate: 99.46%, java instanceof keyword easy java (basic) max score: 10 success rate: 97.89%, java iterator easy java (basic) max score: 15 success rate: 98.14%.

Java Interview Questions and Programming Examples

core java problem solving questions

This article have been designed to get you prepared with the questions you may encounter during a technical interview for the subject of Java Programming Language. Typical jobs descriptions requiring Java skills are Java Backend programmer and Java Fullstack programmer.

As per my experience, most of the questions are related to:

  • the programming language particularities (syntax, core API)
  • problem solving (algorithms, data structures)
  • application design / architecture (design patterns, object oriented programming, best practices…). 

You'll find below a summary of these question categories and some examples. I hope this will help for your next tech interview!

Java language questions are mainly about classes, methods, objects, syntax and APIs.

Java Books Library

Questions relating to the Java language check the developer’s ability to use functionalities that are well-known. Using the correct APIs and data structures determine the developer's level of experience in the practice of the Java programming language. This skill is particularly important for a developer who has to be quickly operational in a Java working environment. See below a list of the common questions which can be asked by technical recruiters:

  • What is the purpose of the method public static void main in a Java program?
  • What is the difference between System.out.println and System.err.println ?
  • What is an interface in Java?
  • When would you use an abstract class instead of an interface ?
  • What are the differences between a public method and a protected one?
  • What is a static variable?
  • What is an Exception in Java?
  • Is it a good practice to catch a RuntimeException ?
  • What is the keyword to use in a method signature to allow non-catching of an exception in this method?
  • What is the latest version of Java?
  • What is the purpose of a garbage collector?
  • What is the difference between a HashSet and a TreeSet ?
  • Which Thread method is called when a thread starts?
  • Is it possible to update a String object (without using introspection)?
  • What is the contract between the methods equals and hashcode ?
  • Who is James Gosling?

An example of very simple task consists in writing a method which takes a string str as parameter and returns true if it equals to "Hello World" , false otherwise.

Java Problem Solving Questions

Java Algorithms

This skill corresponds to the developer's ability to evaluate and resolve a problem by writing an efficient algorithm in Java. Any developers should be able to solve simple problems but advanced analytical skills and logical reasoning are essential when your are hiring Java R&D developers. Problem Solving exercises cover several topics like the graph theory, dynamic programming and the number theory. Most of the time problem solving questions require to write code or pseudo code directly in a code editor or, sometimes, in front of a white board. See below some questions:

  • What are time and space complexity?
  • What is the O-notation?
  • What is the time complexity of binary search?
  • Given a pointer to the head node of a linked list, reverse this linked list
  • Give the name of 3 sorting algorithms and explain their logic
  • What is the difference between DFS and BFS?
  • Implement a recursive and an iterative method to compute a given Fibonacci number

An example of a simple problem is:

From a given array of natural numbers, return the distance between the two closest numbers.

A basic solution consists in: for each number, compare it to all the other numbers. This solution takes a long time to process large data sets, its time complexity is O(n²) then this implementation can fail on big data sets. A more efficient solution consists in a two steps algorithm:

  • sort the array using a built-in function like Arrays.sort() which has a time complexity of O(n log n).
  • iterate through the sorted array and compare each number to the previous one to find the two closest.

See? This is much better!

Java Design Questions

Application architecture and design

Having a good understanding of the design patterns, OOP (object-oriented programming) and unit tests give an indication of the developer's ability to implement standard solutions to common problems. A developer with a good level of proficiency in this skill will contribute to increase the maintainability and the extensibility of applications. This skill is particularly important for senior Java developers who will have to work on the architecture of applications to design long-term solutions.

This is a simple question example:

A general rule of thumb is to prefer interface over implementation, it improves code maintenance, testability and code portability. Map getTable() is the expected answer.

Java Readability Questions

Code readability

This metric focus on the developer’s ability to follow the Java guidelines and best practices. A high score means that the code is easily understandable by other programmers, easier to maintain and to debug. For example, private String Name; will impact the readability score because it does not respect the Java naming convention: Name should be written name .

Java Reliability Questions

Fixing bugs in practice

Remember str.equals("Hello World") upper? What happens if str is null ? 🧐 This kind of error is like a mine silently waiting in a program.

Reliability refers to the developer's ability to achieve solutions that address specific cases like corner and edge cases. The higher this skill, the higher the developer anticipates possible errors and minimizes those to build robust programs.

About Programming tests

Coding tests are one of the most efficient ways to screen developers before hiring.

The CodinGame Java online tests assess candidates' skills. They are perfect for pre-employment screening for developers. Most of the coding interview tools focus only on the candidates' ability to write efficient algorithms but algorithms are a tiny part of software development, mastering them is one skill among several other important skills. CodinGame Assessment provides tests covering a wide scope of technical characteristics to evaluate candidates' ability to write good Java programs.

They provide a proven model for identifying and hiring proficient developers. Candidates code their way through real, practical problems that they could encounter in a company (such as finding a bug in a defective piece of code or properly synchronizing a multi-threaded application), enabling recruiters to measure their coding skills objectively and efficiently.

Tech recruiters to HR managers can set up coding tests using platforms like CodinGame, choosing to test applicants in one specific programming language or over multiple technologies (Java, Javascript, Python, React etc.).

Candidates’ code is automatically analyzed and recruiters are provided with performance metrics. Once completed, a test report is available to download and share to easily compare and shortlist candidates.

Coding Skills Assessment Tool

The Most Common Java Pitfalls

Kotlin basics, part 1, java behavior driven development, beginner java concepts.

The #1 tech hiring platform

Learn Java and Programming through articles, code examples, and tutorials for developers of all levels.

  • online courses
  • certification
  • free resources

Thursday, January 12, 2023

Top 53 java programs for coding and programming interviews, 50+ java coding problems from programming job interviews.

Top 50 Java Programs from Coding and Programming Interviews

  • 10 Courses to Prepare for Programming Interviews
  • 10 Books to Prepare Technical Programming/Coding Job Interviews
  • 20+ String Algorithms Interview Questions
  • 25 Software Design Interview Questions for Programmers
  • 20+ array-based Problems for interviews
  • 40 Binary Tree Interview Questions for Java Programmers
  • 10 Dynamic Programming Questions from Coding Interviews
  • 25 Recursion Programs from Coding Interviews
  • Review these Java Interview Questions for Programmers
  • 7 Best Courses to learn Data Structure and Algorithms
  • 10 OOP Design Interview Questions with solution
  • Top 30 Object-Oriented Programming Questions
  • Top 5 Courses to learn Dynamic Programming for Interviews
  • 10 Algorithm Books Every Programmer Should Read
  • Top 5 Data Structure and Algorithm Books for Java Developers
  • 100+ Data Structure and Algorithm Questions with Solution
  • 75+ Coding Interview Questions for 2 to 5 years experience
  • 10 Programming and Coding Job interview courses for programmers

good questions, thanks

Feel free to comment, ask questions if you have any doubt.

IMAGES

  1. Java Solved Programs, Problems with Solutions

    core java problem solving questions

  2. Problem Solving Skills in Java Programming

    core java problem solving questions

  3. #3.B

    core java problem solving questions

  4. Java Problem Solving Tutorial: Left to Right Evaluation

    core java problem solving questions

  5. Core Java Assignment Questions with Solution

    core java problem solving questions

  6. Top 100+ Core Java Interview Questions

    core java problem solving questions

VIDEO

  1. Comment the reason for the output. #javaforbeginners #corejava

  2. #28 Java Interview| Core Java

  3. 6 Java Practice Problem abc302

  4. 2023 Java Training Session 39

  5. Reverse First K elements of Queue

  6. L2-Q2-Accepting User Inputs in Java

COMMENTS

  1. Java programming Exercises, Practice, Solution

    Numbers [ 28 Exercises with Solution ] Object Oriented Programming Java Inheritance Exercises [ 9 exercises with solution ] Java Abstract Classes Exercises [ 12 exercises with solution ] Java Interface Exercises [ 11 exercises with solution ] Java Encapsulation Exercises [ 7 exercises with solution ]

  2. Solve Java

    Solve Challenge Java Loops II EasyJava (Basic)Max Score: 10Success Rate: 97.33% Solve Challenge Java Datatypes EasyJava (Basic)Max Score: 10Success Rate: 93.67% Solve Challenge Java End-of-file EasyJava (Basic)Max Score: 10Success Rate: 97.92% Solve Challenge Java Static Initializer Block EasyJava (Basic)Max Score: 10Success Rate: 96.17%

  3. 200+ Core Java Interview Questions and Answers (2024)

    Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and performance. In this article, we will provide 200+ Core Java Interview Questions tailored for both freshers and experienced professionals with 3, 5, and 8 years of experience.

  4. Basic to Advanced Java Practice Set with Solutions

    Solving these Java exercise questions will help you to practice Java programming and become a better Java programmer. Table of Content for Java Exercises Pattern Questions in Java Array in Java String in Java Searching Algorithms in Java Sorting Algorithms Java Exercise Questions 1. Write Hello World Program in Java

  5. Top 50 Java Programming Interview Questions

    There are many ways to solve this problem. You can sort the array in natural ascending order and take the second last value. However, sorting is an expensive operation. ... This collection of 50 Java programming interview questions included questions from beginner to expert level, to help you prepare for your interview. Recommended Reading:

  6. Java Programs

    Whether you are a fresher preparing for job interviews or a beginner who has covered Java fundamentals and wants to practice Java concepts. then, This JAVA Programs article covers everything in an organized manner from Basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.

  7. Java 8 Interview Questions(+ Answers)

    1. Introduction In this tutorial, we're going to explore some of the JDK8-related questions that might pop up during an interview. Java 8 is a platform release packed with new language features and library classes.

  8. Java Coding Practice

    What kind of Java practice exercises are there? We've prepared a collection of Java exercises that will help you grasp the syntax of Java language and some core programming topics. In addition, you'll find useful links to articles that cover the theory of Java. Enjoy your Java practice online and enhance your theory knowledge here!

  9. Core Java Quiz

    Core Java Quiz. In this quiz, you will be tested on Core Java basics and OOPS concepts. There are some code snippets too to test your basic Java coding skills. Some of the questions have multiple answers. You can click on the " Reveal Answer " button for the correct answer and explanation. Give it a try and share it with others if you like ...

  10. 180 Core Java Interview Questions and Answers [2024]

    138. Explain the use of the final keyword in variable, method and class. In Java, one can apply the final keyword to a variable, methods, and class. With the help of the final keyword, the variable turns out to be a constant, the method cannot be inherited and the class cannot be overridden. 139.

  11. Ace the top 15 Java algorithm questions for coding interviews

    215 Quizzes Preview Measuring Complexity: Big O Notation Using Big O notation is a foundational skill that will be checked by Java interviewers. Before we jump into some more intensive examples, we'll first go through some questions that test your knowledge and understanding of Big O notation.

  12. Top 50 Java Programs from Coding Interviews

    As I said, it includes questions from problem-solving, linked list, array, string, matrix, bitwise operators and other miscellaneous parts of programming. Once you are gone through these questions, you can handle a good number of questions on real Job interviews. 1. Fibonacci series ( solution)

  13. Review these 50 questions to crack your Java programming interview

    Here is the list of some of the most frequently asked Java questions in interviews for both beginner and experienced Java developers. 50+ Java Interview Questions for 2 to 3 years Experienced Programmers. So, without wasting any more of your time, here is my list of some of the frequently asked Core Java Interview Questions for beginner ...

  14. 49 Core Java interview questions for experienced programmers

    5 Core Java interview questions for experienced programmers with sample answers. ... Why is problem-solving a fundamental skill for Java developers? The entire development lifecycle relies on problem-solving skills, which developers should hone for their projects. It's a critical skill because developers must notice problems and develop ...

  15. Technical Interview Practice with Java

    1 Algorithmic Complexity Learn about algorithmic complexity conceptually and in Java. 2 Technical Interview Skills Learn how to approach problem-solving for technical interviews. 3 Java Interview Problems Practice your Java data structures and algorithm skills with some concrete problems! The platform Hands-on learning

  16. 800+ Java Practice Challenges // Edabit

    Very Easy Return the Sum of Two Numbers Create a method that takes two integers as arguments and returns their sum. Examples SumOfTwoNumbers (3, 2) 5 SumOfTwoNumbers (-3, -6) -9 SumOfTwoNumbers (7, 3) 10 Notes Don't forget to return the result. If you get stuck on a challenge, find help in the Resources tab.

  17. 300 Core Java Interview Questions (2023)

    1 2 3 4 5 Core Java: Basics of Java Interview Questions 1) What is Java? Java is the high-level, object-oriented, robust, secure programming language, platform-independent, high performance, Multithreaded, and portable programming language. It was developed by James Gosling in June 1991.

  18. Core Java Interview Questions and Answers (2024)

    Write a Java program for solving the Tower of Hanoi Problem. 12. Implement Binary Search in Java using recursion. Conclusion 1. ... The following article will cover all the popular Core Java interview questions, String Handling interview questions, Java 8 interview questions, Java multithreading interview questions, Java OOPs interview ...

  19. Solve Java

    Join over 16 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews. ... Java Method Overriding 2 (Super Keyword) Easy Java (Basic) Max Score: 10 Success Rate ... Skills. Java (Basic) Java (Intermediate) Problem Solving (Intermediate) Difficulty. Easy. Medium. Hard. Subdomains ...

  20. Java Interview Questions and Programming Examples

    As per my experience, most of the questions are related to: the programming language particularities (syntax, core API) problem solving (algorithms, data structures) application design / architecture (design patterns, object oriented programming, best practices…). You'll find below a summary of these question categories and some examples.

  21. Top 20 Spring Framework and Spring Boot Scenario based Questions for

    20 Core Spring and Spring Boot Scenario Based Questions for Java Developers. Here is a list of scenario based, problem solving question based upon Spring Framework and Spring Boot for Java developers.

  22. Java Basic Programming Exercises

    Java Multithreading Java Lambda expression Object-Oriented Programming JavaFx Exercises JavaFx Exercises Home a. -5 + 8 * 6 b. (55+9) % 9 c. 20 + -3*5 / 8 d. 5 + 15 / 3 * 2 - 8 % 3 Write a Java program to print the area and perimeter of a circle. Click me to see the solution

  23. Top 53 Java Programs for Coding and Programming Interviews

    1. For a given array of integers (positive and negative) find the largest sum of a contiguous sequence. 2. Algorithm: Implement a queue using 2 stacks (solution) 3. Algorithm: Integer division without the division operator (/) (solution) 4. How to print All permutations of a Given String in Java ( solution) 5.