100+ Best Java Interview Questions & Answers in 2020
100+ Best Java Interview Questions & Answers in 2020
Share:
(https://twitter.com/intent/tweet?
text=Java+Interview+Questions+and+Answers+https%3A%2F%2Fhackr.io%2Fblog%2Fjava-interview-questions)
( https://www.linkedin.com/shareArticle?mini=true&url=https://hackr.io/blog/java-interview-questions)
(http://www.reddit.com/submit?url=https://hackr.io/blog/java-interview-questions)
(https://news.ycombinator.com/submitlink?u=https://hackr.io/blog/java-interview-questions)
(https://api.whatsapp.com/send?text=https%3A%2F%2Fhackr.io%2Fblog%2Fjava-interview-questions)
12 Comments
Table of Contents
https://hackr.io/blog/java-interview-questions 1/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
High Performance– Using a JIT (Just-In-Time) compiler allows high performance in Java. The
JIT compiler converts the Java bytecode into machine language code, which then gets
executed by the JVM
Multi-threading– A thread is a ow of execution. The JVM creates a thread which is called the
main thread. Java allows the creation of several threads using either extending the thread class
or implementing the Runnable interface
OOPS Concepts– Java follows various OOPS concepts (https://hackr.io/blog/object-oriented-
programming-oops-concepts-in-java-with-examples), namely abstraction, encapsulation,
https://hackr.io/blog/java-interview-questions 3/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
It provides a
It is a set of
runtime It is a software development
software tools used
Purpose environment to environment used to develop
for developing Java
execute Java Java applications.
applications.
bytecode.
It is a runtime
instance created
Existence It exists physically. It exists physically.
when we run a
Java class.
It is an implementation of any
one of the below given Java
Platforms released by Oracle
It is the Corporation:
Its implementation
Implementation implementation of
is known as JRE Standard Edition Java Platform
JVM
Enterprise Edition Java
Platform
Micro Edition Java Platform
https://hackr.io/blog/java-interview-questions 4/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
It's a no-brainer that Java is one of the leading programming options for bagging a lucrative job
(https://hackr.io/blog/which-programming-language-is-best-for-getting-a-job). After all, the class-
based, general-purpose, object-oriented programming language, is one of the most widely used
programming languages in the world.
The language was developed in 1995 and had constantly been upgrading its products to enable
users to develop and deploy Java solutions with ease and con dence. Java designers have
borrowed the best features of many existing languages such as C and C++ and added new
features to form simple, easy-to-learn object-oriented language.
-15% -19%
This article has been divided into di erent sections and categories for your organized preparation
for the interview into the following categories:
Answer: JIT compiler runs after the program is executed and compiles the code into a faster form,
hosting CPU's native instructing set. JIT can access dynamic runtime information, whereas a
standard compiler doesn't and can make better optimizations like inlining functions that are used
frequently.
It is of two types:
Implicit
Explicit
https://hackr.io/blog/java-interview-questions 5/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Implicit: Storing values from a smaller data type to the larger data type. It is automatically done
by the compiler.
Explicit: Storing the value of a larger data type into a smaller data type. This results in
information loss:
. Truncation
. Out of Range
int i = 10;
long l = i;
long l = 10,000;
int i = (int) l;
float f = 3.14f
int i = (int) f;
i=3;
long l = 123456789;
byte b = (byte) l;
Default
Private
Protected
Public
https://hackr.io/blog/java-interview-questions 6/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Answer: The local variables are not initialized to any default value, neither primitives nor object
references.
Abstraction– Representing essential features without the need to give out background details.
The technique is used for creating a new suitable data type for some speci c application
Aggregation– All objects have their separate lifecycle, but ownership is present. No child
object can belong to some other object except for the parent object
Association– The relationship between two objects, where each object has its separate
lifecycle. There is no ownership
Class– A group of similar entities
Composition– Also called the death relationship, it is a specialized form of aggregation. Child
objects don't have a lifecycle. As such, they automatically get deleted if the associated parent
object is deleted
Encapsulation– Refers to the wrapping up of data and code into a single entity. Allows the
variables of a class to be only accessible by the parent class and no other classes
Inheritance– When an object acquires the properties of some other object, it is called
inheritance. It results in the formation of a parent-child relationship amongst classes involved.
O ers a robust and natural mechanism of organizing and structuring software
Object– Denotes an instance of a class. Any class can have multiple instances. An object
contains the data as well as the method that will operate on the data
Polymorphism– refers to the ability of a method, object, or variable to assume several forms
Break Continue
Used with both loop and switch statement Used with only loop statements.
https://hackr.io/blog/java-interview-questions 7/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
It terminates the loop or switch block. It does not terminate but skips to the next iteration.
Syntax of a class:
class Sample{
member variables
methods()
}
Variables and methods can be created that are common to all objects and accessed without
using a particular object by declaring them static. Static members are also available to be used by
other classes and methods.
https://hackr.io/blog/java-interview-questions 8/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Answer: A constructor is a method that has the same name as that of the class to which it
belongs. As soon as a new object is created, a constructor corresponding to the class gets
invoked. Although the user can explicitly create a constructor, it is created on its own as soon as a
class is created. This is known as the default constructor. Constructors can be overloaded.
Unlike method overriding, method overloading requires two overloaded methods to have the
same name but di erent arguments. The overloaded functions may or may not have di erent
return types.
Question: What role does the nal keyword play in Java? What impact does it have
on a variable, method, and class?
https://hackr.io/blog/java-interview-questions 9/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Answer: The nal keyword in Java is a non-access modi er that applies only to a class, method,
or variable. It serves a di erent purpose based on the context where it is used.
With a class
When a class is declared as nal, then it is disabled from being subclassed i.e., no class can
extend the nal class.
With a method
Any method accompanying the nal keyword is restricted from being overridden by the subclass.
With a variable
A variable followed by the nal keyword is not able to change the value that it holds during the
program execution. So, it behaves like a constant.
Question: Please explain the di erence between String, String Builder, and String
Bu er.
Answer: String variables are stored in a constant string pool. With the change in the string
reference, it becomes impossible to delete the old value. For example, if a string has stored a
value "Old," then adding the new value "New" will not delete the old value. It will still be there,
however, in a dormant state. In a String Bu er, values are stored in a stack. With the change in the
string reference, the new value replaces the older value. The String Bu er is synchronized (and
https://hackr.io/blog/java-interview-questions 10/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
therefore, thread-safe) and o ers slower performance than the String Builder, which is also a
String Bu er but is not synchronized. Hence, performance is fast in String Builder than the String
Bu er.
A class that implements the interface must provide an implementation for all methods declared
in the interface
All methods in an interface are internally public abstract void
All variables in an interface are internally public static nal
Classes do not extend but implement interfaces
Constituents – An abstract class contains instance variables, whereas an interface can contain
only constants.
Constructor and Instantiation – While an interface has neither a constructor nor it can be
instantiated, an abstract class can have a default constructor that is called whenever the
concrete subclass is instantiated.
Implementation of Methods – All classes that implement the interface need to provide an
implementation for all the methods contained by it. A class that extends the abstract class,
however, doesn't require implementing all the methods contained in it. Only abstract methods
need to be implemented in the concrete subclass.
Type of Methods – Any abstract class has both abstract as well as non-abstract methods.
Interface, on the other hand, has only a single abstract method.
Question: Please explain what do you mean by an Abstract class and an Abstract
method?
https://hackr.io/blog/java-interview-questions 11/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Answer: An abstract class in Java is a class that can't be instantiated. Such a class is typically
used for providing a base for subclasses to extend as well as implementing the abstract methods
and overriding or using the implemented methods de ned in the abstract class. To create an
abstract class, it needs to be followed by the abstract keyword. Any abstract class can have both
abstract as well as non-abstract methods. A method in Java that only has the declaration and not
implementation is known as an abstract method. Also, an abstract method name is followed by
the abstract keyword. Any concrete subclass that extends the abstract class must provide an
implementation for abstract methods.
https://hackr.io/blog/java-interview-questions 12/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Extend the Thread Class – The thread is available in the java.lang.Thread class. To make a
thread, you need to extend a thread class and override the run method. For example,
A disadvantage of using the thread class is that it becomes impossible to extend any other
classes.
New – In the very rst state of the thread lifecycle, the thread instance is created, and the start()
method is yet to be invoked. The thread is considered alive now.
Runnable – After invoking the start() method, but before invoking the run() method, a thread is
in the runnable state. A thread can also return to the runnable state from waiting or sleeping
state.
https://hackr.io/blog/java-interview-questions 13/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Running – The thread enters the running state after the run() method is invoked. This is when
the thread begins execution.
Non-Runnable – Although the thread is alive, it is not able to run. Typically, it returns to the
runnable state after some time.
Terminated – The thread enters the terminated state once the run() method completes its
execution. It is not alive now.
Question: When is the Runnable interface preferred over thread class and vice-
versa?
Answer: In Java, it is possible to extend only one class. Hence, the thread class is only extended
when no other class needs to be extended. If it is required for a class to extend some other class
than the thread class, then we need to use the Runnable interface.
https://hackr.io/blog/java-interview-questions 14/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Answer: We use the join() method for joining one thread with the end of the currently running
thread. It is a non-static method and has an overloaded version. Consider the example below:
The main thread starts execution in the example mentioned above. As soon as the execution
reaches the code t.start(), then the thread t starts its stack for execution. The JVM switches
between the main thread and the thread there. Once the execution reaches the t.join(), then the
thread t alone is executed and allowed to complete its task. Afterward, the main thread resumes
execution.
Blocking – This method is used to put the thread in a blocked state. The execution resumes as
soon as the condition of the blocking is met. For instance, the ServerSocket.accept() is a
blocking method that listens for incoming socket connection and resumes the blocked thread
only when a connection is made.
Sleeping – This method is used for delaying the execution of the thread for some time. A
thread upon which the sleep() method is used is said to enter the sleep state. It enters the
runnable state as soon as it wakes up i.e., the sleep state is nished. The time for which the
thread needs to enter the sleep state is mentioned inside the braces of the sleep() method. It is
a static method.
Waiting – Although it can be called on any Java object, the wait() method can only be called
from a synchronized block.
https://hackr.io/blog/java-interview-questions 15/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Checked Exceptions – Classes that extend Throwable class, except Runtime exception and
Error, are called checked exceptions. Such exceptions are checked by the compiler during the
compile time. These types of exceptions must either have appropriate try/catch blocks or be
declared using the throws keyword. ClassNotFoundException is a checked exception.
Unchecked Exceptions – Such exceptions aren't checked by the compiler during the compile
time. As such, the compiler doesn't necessitate handling unchecked exceptions. Arithmetic
Exception and ArrayIndexOutOfBounds Exception are unchecked exceptions.
Declaring the throws keyword – We can declare the exception using throws keyword at the end
of the method. For example:
class ExceptionCheck{
public static void main(String[] args){
add();
}
public void add() throws Exception{
addition();
}
}
Using try/catch – Any code segment that is expected to yield an exception is surrounded by the
try block. Upon the occurrence of the exception, it is caught by the catch block that follows the try
block. For example,
https://hackr.io/blog/java-interview-questions 16/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
class ExceptionCheck{
public static void main (String[] args) {
add();
}
public void add(){
try{
addition();
}
catch(Exception e)
{
e.printStacktrace();
}
}
}
Question: Is it possible to write multiple catch blocks under a single try block?
https://hackr.io/blog/java-interview-questions 17/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Answer: Yes, it is possible to write several catch blocks under a single try block. However, the
approach needs to be from speci c to general. Following example demonstrates the same:
Question: How does the throw keyword di er from the throws keyword?
Answer: While the throws keyword allows declaring an exception, the throw keyword is used to
explicitly throw an exception. Checked exceptions can't be propagated with throw only, but
throws allow doing so without the need for anything else. The throws keyword is followed by a
class, whereas the throw keyword is followed by an instance. The throw keyword is used within
the method, but the throws keyword is used with the method signature. Furthermore, it is not
possible to throw multiple exceptions, but it is possible to declare multiple exceptions.
There is two crucial exception handling keywords in Java, followed by the third keyword nal,
which may or may not be used after handling exceptions.
try:
If and when a code segment has chances of having and abnormality or an error, it is placed within
a try block. When the exception is raised, it is handled and caught by the catch block.
Try block must have a catch() or a nal() or both blocks after it.
catch:
When an exception is raised in the try block, it is handled in the catch block.
https://hackr.io/blog/java-interview-questions 18/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
nal:
This block is executed regardless of the exception. It can be placed either after try{} or catch {}
block.
Example:
add()
addition()
main()
If an exception occurred in the add() method is not caught, then it moves to the method addition().
It is then moved to the main() method, where the ow of execution stops. It is called Exception
Propagation.
https://hackr.io/blog/java-interview-questions 19/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
To compile: javac.java
Deletion
Insertion
Manipulation
Searching
Sorting
values, HashMap uses iterator and HashTable uses enumerator. HashTable doesn't allow anything
that is null, while HashMap allows one null key and several null values. In terms of performance,
HashTable is slow. Comparatively, HashMap is faster.
HashMap - It is an unordered and unsorted map and hence, is a good choice when there is no
emphasis on the order. A HashMap allows one null key and multiple null values and doesn't
maintain any insertion order.
HashTable – Doesn't allow anything null and has methods that are synchronized. As it allows
for thread safety, the performance is slow.
LinkedHashMap – Slower than a HashMap but maintains insertion order and has a faster
iteration.
TreeMap – A sorted Map providing support for constructing a sort order using a constructor.
Question: What is Set in Java? Also, explain its types in a Java Collections.
Answer: In Java, a Set is a collection of unique objects. It uses the equals() method to determine
whether two objects are the same or not. Various types of Set in Java Collections are:
. Hash Set– An unordered and unsorted set that uses the hash code of the object for adding
values. Used when the order of the collection isn't important
. Linked Hash Set– This is an ordered version of the hash set that maintains a doubly-linked list
of all the elements. Used when iteration order is mandatory. Insertion order is the same as that
of how elements are added to the Set.
. Tree Set– One of the two sorted collections in Java, it uses Read-Black tree structure and
ensures that the elements are present in the ascending order.
https://hackr.io/blog/java-interview-questions 21/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
. Ordered
It means that values are stored in a collection in a speci c order, but the order is independent of
the value. Eg. List
. Sorted
It means the collection has an order which is dependent on the value of an element.
Eg. SortedSet
. Serial Garbage Collector– Using only a single thread for garbage collection, the serial garbage
collector works by holding all the application threads. It is designed especially for single-
threaded environments. Because serial garbage collector freezes all application threads while
performing garbage collection, it is most suitable for command-line programs only. For using
the serial garbage collector, one needs to turn on the -XX:+UseSerialGC JVM argument.
. Parallel Garbage Collector – Also known as the throughput collector, the parallel garbage
collector is the default garbage collector of the JVM. It uses multiple threads for garbage
collection, and like a serial garbage collector freezes all application threads during garbage
collection.
. CMS Garbage Collector– Short for Concurrent Mark Sweep, CMS garbage collector uses
multiple threads for scanning the heap memory for marking instances for eviction, followed by
sweeping the marked instances. There are only two scenarios when the CMS garbage collector
holds all the application threads:
. When marking the referenced objects in the tenured generation space
. If there is some change in the heap memory while performing the garbage collection, CMS
garbage collector ensures better application throughput over parallel garbage collectors by
using more CPU. For using the CMS garbage collector, the XX:+USeParNewGC JVM
argument needs to be turned on.
. G1 Garbage Collector – Used for large heap memory areas, G1 garbage collector works by
separating the heap memory into multiple regions and then executing garbage collection in
them in parallel. Unlike the CMS garbage collector that compacts the memory on STW (Stop
The World) situations (https://stackover ow.com/questions/16695874/why-does-the-jvm-full-gc-
need-to-stop-the-world), G1 garbage collector compacts the free heap space right after
https://hackr.io/blog/java-interview-questions 22/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
reclaiming the memory. Also, the G1 garbage collector prioritizes the region with the most
garbage. Turning on the –XX:+UseG1GC JVM argument is required for using the G1 garbage
collector.
Note: It is recommended to avoid implementing synchronization for all methods. This is because
when only one thread can access the synchronized code, the next thread needs to wait.
Consequently, it results in slower performance of the program.
Question: Can you tell the di erence between execute(), executeQuery(), and
executeUpdate()?
Answer:
execute() – Used for executing an SQL query. It returns TRUE if the result is a ResultSet, like
running Select queries, and FALSE if the result is not a ResultSet, such as running an Insert or
an Update query.
executeQuery() – Used for executing Select queries. It returns the ResultSet, which is not null,
even if no records are matching the query. The executeQuery() method must be used when
executing select queries so that it throws the java.sql.SQLException with the 'executeQuery
method cannot be used for update' message when someone tries to execute an Insert or
Update statement.
https://hackr.io/blog/java-interview-questions 23/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Note: The execute() method needs to be used only in a scenario when there is no certainty about
the type of statement. In all other cases, either use executeQuery() or executeUpdate() method.
Question: Could you demonstrate how to delete a cookie in JSP with a code
example?
Answer: Following code demonstrates deleting a cookie in JSP:
Question: Write suitable code examples to demonstrate the use of nal, nal, and
nalize.
https://hackr.io/blog/java-interview-questions 24/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Answer: Final: The nal keyword is used for restricting a class, method, and variable. A nal class
can't be inherited, a nal method is disabled from overriding, and a nal variable becomes a
constant i.e., its value can't be changed.
class FinalVarExample {
public static void main( String args[])
{
final int a=10;
a=50; /* Will result in an error as the value can’t be changed now*/
}
Finally: Any code inside the nal block will be executed, irrespective of whether an exception is
handled or not.
class FinallyExample {
public static void main(String args[]){
try {
int x=100;
}
catch(Exception e) {
System.out.println(e);
}
finally {
System.out.println("finally block is executing");}
}
}
}
Finalize: The nalize method performs the clean up just before the object is garbage collected.
class FinalizeExample {
public void finalize() {
System.out.println("Finalize is called");
}
public static void main(String args[])
{
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1= NULL;
f2=NULL;
System.gc();
}
}
https://hackr.io/blog/java-interview-questions 25/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Answer: The value stored in a volatile variable is not read from the thread's cache memory but
from the main memory. Volatile variables are primarily used during synchronization.
That completes the list of top Java interview questions. What do you think about the list we
compiled? Let us know by dropping your comments in the dedicated window below. Also, check
out these best Java tutorials (https://hackr.io/tutorials/learn-java?ref=blog-post) to further re ne
your Java skill set.
public: It is an access modi er de ning the accessibility of the class or method. Any Class can
access the main() method de ned public in the program.
static: The keyword indicates the variable, or the method is a class method. The method main()
is made static so that it can be accessed without creating the instance of the class. When the
method main() is not made static, the compiler throws an error because the main() is called by
the JVM before any objects are made, and only static methods can be directly invoked via the
class.
void: It is the return type of the method. Void de nes the method does not return any type of
value.
https://hackr.io/blog/java-interview-questions 26/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
main: JVM searches this method when starting the execution of any program, with the
particular signature only.
String args[]: The parameter passed to the main method.
boolean Boolean
char Character
double Double
oat Float
int Integer
long Long
Question: Explain the concept of boxing, unboxing, autoboxing, and auto unboxing.
Answer:
Boxing: The concept of putting a primitive value inside an object is called boxing.
Unboxing: Getting the primitive value from the object.
Autoboxing: Assigning a value directly to an integer object.
Auto unboxing: Getting the primitive value directly into the integer object.
Question: De ne the Singleton class in Java. How can a class be made Singleton?
https://hackr.io/blog/java-interview-questions 27/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Answer: A Singleton class allows only one instance of the class to be created.
Question: What if the public static void is replaced by static public void, will the
program still run?
Answer: Yes, the program would compile and run without any errors as the order of the speci ers
don't matter.
Equals() ==
https://hackr.io/blog/java-interview-questions 28/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
class Operator {
public static void main(String[] args)
{ public class Equals{
/* integer-type*/ public static void main(String[] args)
System.out.println(10 == 20); {
/* char-type*/ String s1 = new String("HELLO");
System.out.println('a' == 'b'); String s2 = new String("HELLO");
/* char and double type*/ System.out.println(s1 == s2);
System.out.println('a' == 97.0); System.out.println(s1.equals(s2));
/* boolean type*/ }
System.out.println(true == true); }
}
}
ing the concept of pointers can be contradicting. Also, JVM is responsible for implicit memory
allocation; thus, to avoid direct access to memory by the user, pointers are discouraged in Java.
this() super()
Represents the current instance of the Represents the current instance of the
class. parent/base class.
It is used to call the default constructor of It is used to call the default constructor of the
the same class parent/base class.
Accesses method of the current class Accesses method of the base class
Must be the rst line of the block It must be the rst line of the block.
i.
class Adder {
Static int add(int a, int b)
{
return a+b;
}
Static double add( double a, double b)
{
return a+b;
}
public static void main(String args[])
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
ii.
class Car {
void run(){
System.out.println(“car is running”);
}
Class Audi extends Car{
void run()
{
System.out.prinltn(“Audi is running safely with 100km”);
}
public static void main( String args[])
{
Car b=new Audi();
b.run();
}
}
https://hackr.io/blog/java-interview-questions 30/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
class RemoveDuplicates
{
public static void main(String args[])
{
/*create ArrayList with duplicate elements*/
ArrayList duplicate = new ArrayList();
duplicate.add(5);
duplicate.add(7);
duplicate.add(1);
duplicate.add(4);
duplicate.add(1);
duplicate.add(7);
System.out.println("Given array: "+ duplicate);
Set <Integer> withoutDuplicates = new LinkedHashSet<Integer>(duplicate)
duplicate.clear();
duplicate.addAll(withoutDuplicates);
System.out.println("Array without duplicates: "+ duplicate);
}
}
https://hackr.io/blog/java-interview-questions 31/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
import java.util.Scanner;
public class NumberReversal
{
public static void main(String args[])
{
System.out.println("Please enter the number to be reversed");
Scanner sc = new Scanner (System.in);
int number = sc.nextInt();
int reverse = reverse(number);
System.out.println("Reverse of number: " + number + " is " + reverse(number));
}
public static int reverse(int number){
int reverse = 0;
int remainder = 0;
do{
remainder = number%10;
reverse = reverse*10 + remainder;
number = number/10;
}while(number > 0);
return reverse;
}
}
https://hackr.io/blog/java-interview-questions 32/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
import java.util.Scanner;
import java.util.Arrays;
public class Binary {
public static void main(String[] args) {
System.out.println("Enter total number of elements : ");
Scanner s = new Scanner (System.in);
int length = s.nextInt();
int[] input = new int[length];
System.out.printf("Enter %d integers", length);
for (int i = 0; i < length; i++) {
input[i] = s.nextInt();
}
/* binary search requires the input array to be sorted so we must sort the array first*/
Arrays.sort(input);
System.out.print("the sorted array is: ");
for(int i= 0; i<= length-1;i++)
{
System.out.println(input[i] + " ,");
}
System.out.println("Please enter number to be searched in sorted array");
int key = s.nextInt();
int index = BSearch(input, key);
if (index == -1) {
System.out.printf("Sorry, %d is not found in array %n", key);
} else {
System.out.printf("%d is found in array at index %d %n", key,
index);
}
}
public static int BSearch(int[] input, int number) {
int low = 0;
int high = input.length - 1;
while (high >= low) {
int middle = (low + high) / 2;
if (input[middle] == number) {
return middle;
} else if (input[middle] < number) {
low = middle + 1;
} else if (input[middle] > number) {
high = middle - 1;
}
}
return -1;
}
}
https://hackr.io/blog/java-interview-questions 33/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
import java.util.Scanner;
public class Prime
{
public static void main(String args[])
{
System.out.println("Enter the number to check: ");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
boolean isPrime = false;
if(num!=0)
{
isPrime = checkPrime(num);
}else
{
System.out.println("Enter valid number");
}
if(isPrime == false)
{
System.out.println(" NOT PRIME!!");
}
else
{
System.out.println("PRIME!!");
}
}
public static boolean checkPrime(int number)
{
int sqrt = (int) Math.sqrt(number) + 1;
for(int i = 2; i<sqrt; i++)
{
if(number % i== 0)
{
return false;
}
}
return true;
}
}
https://hackr.io/blog/java-interview-questions 34/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
import java.util.Scanner;
public class Fibo
{
public static void main(String args[])
{
System.out.println("Enter the number upto which Fibonacci series should be printed ");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
System.out.println("Fibonacci Series upto %d is" + num);
for(int i=1; i<=num; i++)
{
System.out.print(fib(i) + " ");
}
}
public static int fib(int n)
{
if(n ==1 || n==2)
{
return 1;
}
return fib(n-1) + fib(n-2);
}
}
https://hackr.io/blog/java-interview-questions 35/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
import java.util.Scanner;
public class PalinDrome
{
public static void main(String args[])
{
System.out.println("Enter the string to check");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
boolean isPalindrome;
isPalindrome = checkPalindrome(str);
if(str.equals(" "))
{
System.out.println("Enter valid string");
}
else
{
if(isPalindrome)
{
System.out.println("PALINDROME!!");
}
else
{
System.out.println("NOT A PALINDROME!!");
}
}
}
public static boolean checkPalindrome(String input)
{
int str_length = input.length();
int i=0, j= str_length-1;
while(i<j)
{
if(input.charAt(i) != input.charAt(j))
return false;
i++;
j--;
}
return true;
}
}
*
**
***
****
*****
https://hackr.io/blog/java-interview-questions 36/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Answer:
import java.util.Scanner;
public class Swap
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter a number: ");
int a = s.nextInt();
System.out.println("Enter second number: ");
int b = s.nextInt();
System.out.println("Value of a and b before swapping: " + "a = " +a + " b = " + b);
swap(a,b);
}
public static void swap(int a , int b)
{
int swap_variable;
swap_variable = a;
a = b;
b = swap_variable;
System.out.println("Value of a and b after swapping: " + "a = " +a + " b = " + b);
}
}
https://hackr.io/blog/java-interview-questions 37/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
import java.util.Scanner;
public class Armstrong
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = s.nextInt();
int a=number, sum = 0, num=0;
while(a%10 !=0)
{
num = a%10;
sum = sum + (num*num*num);
a = a/10;
}
if(sum == number)
{
System.out.println("Armstrong Number!");
}
else
{
System.out.println("Not an Armstrong Number!");
}
}
}
We have also provided a PDF for your preparation so that you can download and learn and
prepare on the go. Download Java Interview Questions PDF (https://bit.ly/2MEd10z)
Summary
The aforementioned Java Interview Questions and Java Programming Interview Questions is the
creme collection to prepare you for the interview as every concept is explained in much detail.
Inside reference, links are also provided for your further reading.
Java is a broad eld of study. Buy this course for further reading and preparing for a Java-based
interview: Java interview Guides: 200+ Interview Question and Answer
(https://click.linksynergy.com/deeplink?
id=jU79Zysihs4&mid=39197&murl=https://www.udemy.com/course/java-interview-questions-and-
answers/)
Follow this book that will help you crack core Java interviews: Elements of Programming
Interviews in Java: The insider guide second edition (https://geni.us/0gm5K)
We also suggest you share your interview experiences and Java programming interview
quotations that you come across in your di erent tech company interviews. Share with us in the
comments below so that we can all help each other and build an interactive community to learn
https://hackr.io/blog/java-interview-questions 38/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Java (https://hackr.io/blog/tag/java)
Share:
(https://twitter.com/intent/tweet?
text=Java+Interview+Questions+and+Answers+https%3A%2F%2Fhackr.io%2Fblog%2Fjava-interview-questions)
( https://www.linkedin.com/shareArticle?mini=true&url=https://hackr.io/blog/java-interview-questions)
(http://www.reddit.com/submit?url=https://hackr.io/blog/java-interview-questions)
(https://news.ycombinator.com/submitlink?u=https://hackr.io/blog/java-interview-questions)
(https://api.whatsapp.com/send?text=https%3A%2F%2Fhackr.io%2Fblog%2Fjava-interview-questions)
https://hackr.io/blog/java-interview-questions 39/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Related Posts
(https://hackr.io/blog/google-interview-questions)
(https://hackr.io/blog/google-interview-questions)
Read More (https://hackr.io/blog/google-interview-questions)
(https://hackr.io/blog/best-hadoop-interview-questions)
(https://hackr.io/blog/best-hadoop-interview-questions)
Read More (https://hackr.io/blog/best-hadoop-interview-questions)
(https://hackr.io/blog/java-8-interview-questions)
https://hackr.io/blog/java-interview-questions 40/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
(https://hackr.io/blog/java-8-interview-questions)
Read More (https://hackr.io/blog/java-8-interview-questions)
Leave a comment
Email address*
Enter email
Name*
Name
Comment*
SUBMIT
karthik
what is dispatcherservlet?
Reply
karthik
what is di erence between spring and springboot ,microservice?
Reply
Karena Noonan
Di erence between notify() method and notifyAll() method in Java.
Reply
Sam Willy
https://hackr.io/blog/java-interview-questions 41/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
When multiple threads are waiting on any lock in Java, then while the notify() method sends a
noti cation to only one of them, the notifyAll() method sends noti cations to all of the waiting
threads
Reply
Chung Jack
Explain about Map and their types.
Reply
Jackie Smith
A Map is a Java object that maps keys to values. Each key in a Map object can have only one
value and a Map object can’t have duplicate keys. It is of three types:
i. HashMap – Implemented as a hash table with no order
ii. LinkedHashMap – Implemented as a hash table with insertion order
iii. TreeMap – Implementation based on red-black tree structure and ordered by the key
Reply
Nidia Gra
How does cookies work in Servlets?
Reply
Jimmy Gerald
A Servlet container sets a cookie in the header of the HTTP response with the cookie name
along with the unique session ID as its value. The cookie is stored in the user browser, which
sends it back to the server for all the following requests until the cookie is valid.
Reply
Walker Almond
What do you mean by aggregation?
Reply
Rocky Rickman
Also described as a “has-a” and “whole/part” relationship, aggregation is a relationship between
two Java classes. The aggregate class has a reference to some other class. A class with all its
data members public is an aggregate class. Aggregate classes have neither constructor
de nitions nor virtual functions.
Reply
Celesta Lavoie
Can you override a private or static method in Java?
Reply
https://hackr.io/blog/java-interview-questions 42/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Mahmood Khan
No, it isn’t possible to override either a private method or a static method in Java. Because the
scope of the private access speci er is limited within a class, it can’t be overridden. Overriding
the static method won’t yield any error, but the output will turn out to have deviated.
Reply
Rona Moon
What is the di erence between HashSet and TreeSet?
Reply
Kyle Mannequin
The biggest di erence between HashSet and TreeSet is in terms of performance. HashSet is
much faster than TreeSet. However, HashSet doesn’t guarantee any order. On the contrary,
TreeSet maintains objects in some sorted order de ned by the Comparator or Comparable
method
Reply
Arron Nunley
Di erence between equals() and ==?
Reply
Ram Naresh
Although both equals() and == are used to compare objects for equality in Java, there is one big
distinguishing factor between the two. While == checks whether the two objects point to the
same memory location, equals() checks whether the two objects have the same value or not.
Reply
Richelle Ritter
Di erence between Default and Protected access speci ers.
Reply
Rachel McCartney
Protected data members and methods are accessible by the classes belonging to the same
package in addition to the subclasses belonging to any other package. Default data members
and methods, on the other hand, are only accessible by the classes belonging to the same
package.
Reply
https://hackr.io/blog/java-interview-questions 43/44
7/1/2020 100+ Best Java Interview Questions & Answers in 2020
Related Tutorials
Java
(https://hackr.io/tutorials/learn-java)
Node.js
(https://hackr.io/tutorials/learn-node-js)
Perl
(https://hackr.io/tutorials/learn-perl)
PHP
(https://hackr.io/tutorials/learn-php)
Python
(https://hackr.io/tutorials/learn-python)
Recommended Learning
Head First Java (geni.us)
(https://hackr.io/tutorial/head- rst-java)
(https://hackr.io/tutorial/complete-java-masterclass)
(https://hackr.io/tutorial/java-video-tutorial-by-derek-banas)
(https://play.google.com/store/apps/details?id=io.hackr.hackr&hl=en)
(https://apps.apple.com/in/app/hackr-io/id1188958684)
https://hackr.io/blog/java-interview-questions 44/44