Java Notes by Bunny
Java Notes by Bunny
Java Notes by Bunny
We also recommend you brush up on your Java skills with this Java Cheat Sheet before
starting your Java interview preparation.
We have divided these interview questions into several sections, including one for
programming Java interview questions.
in Java. The JIT compiler converts the Java bytecode into machine language
which is called the main thread. Java allows the creation of several threads using
which allows a single Java program to operate on multiple platforms without any
modifications.
You may want to check out detailed explanations of Java features here.
It then compiles the bytecode of the Java method into native machine code.
After that, the JVM calls the compiled code directly instead of interpreting it.
released by Oracle
Corporation:
Platform
Platform
Platform
9. Explain Typecasting.
The concept of assigning a variable of one data type to a variable of another data type.
This is not possible for the boolean data type. There are two types: implicit and explicit.
● Implicit: Storing values from a smaller data type to the larger data type. It is
● Explicit: Storing the value of a larger data type into a smaller data type. This
data type, the extra data will be truncated. This code example explains it :
float f = 3.14f;
int i = (int) f;
After execution, the variable i will contain only 3 and not the decimal portion.
○ Out of Range: Typecasting does not allow assigning value more than its
range; if that happens then the data is lost in such cases. This code
long l = 123456789;
byte b = (byte) l; // byte is of not the same range as long so there will
be loss of data.
● Default
● Private
● Protected
● Public
There are many languages that follow OOPs concepts — some popular ones are Java,
Python, and Ruby. Some frameworks also follow OOPs concepts, such as Angular.
background details. The technique is used for creating a new suitable data type
● 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
aggregation. Child objects don't have a lifecycle. As such, they automatically get
This allows the variables of a class to be only accessible by the parent class and
no other classes.
● 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
several forms.
Break Continue
Used with both loop and switch Used with only loop statements.
statement.
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()
Example of Class:
void area()
void volume ()
void num_sides()
}
}
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.
While local variables are declared inside a method or a code block, instance variables
are declared inside a class but outside a method. Even when not assigned, instance
variables have a value that can be null, 0, 0.0, or false. This isn't the case with local
variables that need to be assigned a value, where failing to assign a value will yield an
error. Local variables are automatically created when a method is called and destroyed
as soon as the method exits. For creating instance variables, the new keyword must be
used.
21. What is Method Overriding?
23. What role does the final keyword play in Java? What impact does it
have on a variable, method, and class?
The final keyword in Java is a non-access modifier that applies only to a class, method,
or variable. It serves a different purpose based on the context where it is used.
● With a class: When a class is declared as final, then it is disabled from being
● With a method: Any method accompanying the final keyword is restricted from
● With a variable: A variable followed by the final keyword is not able to change
the value that it holds during the program execution. So, it behaves like a
constant.
● A class that implements the interface must provide an implementation for all
provide an implementation for all the methods contained by it. A class that
extends the abstract class, however, doesn't require implementing all 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.
2. Two classes with the same can exist in two different packages.
3. Packages can hide classes, thus denying access to certain programs and
To make a thread, you need to extend a thread class and override the run
A disadvantage of using the thread class is that it becomes impossible to extend any
other classes.
implementing a runnable interface. For doing so, there is the need to provide the
The thread lifecycle has the following states and follows the following order:
● New: In the very first 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
● Running: The thread enters the running state after the run() method is invoked.
35. When is the Runnable interface preferred over thread class and
vice-versa?
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.
a subset of a process.
● Changes: A change made to the parent process doesn't affect child processes.
However, a change in the main thread can yield changes in the behavior of other
● Control: Processes are controlled by the operating system and can control only
child processes. On the contrary, threads are controlled by the programmer and
are capable of exercising control over threads of the same process to which they
belong.
● Dependence: Processes are independent entities while threads are dependent
entities
● Memory: Threads run in shared memory spaces, but processes run in separate
memory spaces.
t.start();
t.join();
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.
Afterwards, 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,
connections 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
finished. The time for which the thread needs to enter the sleep state is
● Waiting: Although it can be called on any Java object, the wait() method can only
● Checked Exceptions: Classes that extend the 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
the compile time. As such, the compiler doesn't necessitate handling unchecked
unchecked exceptions.
Declaring the throws keyword: We can declare the exception using throws keyword at
the end of the method. For example:
class ExceptionCheck{
addition();
class ExceptionCheck{
add();
try{
addition();
catch(Exception e)
e.printStacktrace();
}
}
42. Is it possible to write multiple catch blocks under a single try block?
Yes, it is possible to write several catch blocks under a single try block. However, the
approach needs to be from specific to general. The following example demonstrates it:
try {
a[10]= 10/0;
}
catch(ArithmeticException e)
catch(ArrayIndexOutOfBoundsException e)
catch(Exception e)
43. How does the throw keyword differ from the throws keyword?
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.
try:
The try block must have a catch() or a final() or both blocks after it.
catch:
When an exception is raised in the try block, it is handled in the catch block.
final:
This block is executed regardless of the exception. It can be placed either after try{} or
catch {} block.
addition()
}
add();
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 flow of execution stops. It is
called Exception Propagation.
{
System.out.println("Hello Java File here!");
To compile: javac.java
● Deletion
● Insertion
● Manipulation
● Searching
● Sorting
● Interfaces: Collection, List, Map, Queue, Set, Sorted Map, and Sorted Set
Values contained in a HashTable are unique and depend on the key. Methods are not
synchronized in HashMap, while key methods are synchronized in HashTable.
However, HashMap doesn't have thread safety, while HashTable has the same.
For iterating values, HashMap uses an iterator and HashTable uses an enumerator.
HashTable doesn't allow anything that is null, while HashMap allows one null key and
several null values.
when there is no emphasis on the order. A HashMap allows one null key and
● HashTable: Doesn't allow anything null and has methods that are synchronized.
● 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.
The element with the high priority is served before the element with low priority in a
priority queue. Elements in a priority queue are ordered either according to the
comparator or naturally. The order of the elements in a priority queue represents their
relative priority.
1. 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
2. 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.
3. 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.
most suitable for command-line programs only. For using the serial garbage
2. 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
3. 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:
over parallel garbage collectors by using more CPU resources. For using
to be turned on.
collector works by separating the heap memory into multiple regions and then
collector that compacts the memory on STW (Stop The World) situations, G1
garbage collector compacts the free heap space right after 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.
t.start();
synchronized(object){
}
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.
ResultSet, like running Select queries, and FALSE if the result is not a 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
statements that return nothing. The output varies depending on whether the
Language (DDL) statements. The output is an integer and equals the total row
count for the former case, and 0 for the latter case.
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.
response.addCookie(mycook1);
58. Write suitable code examples to demonstrate the use of final, final,
and finalize.
Final: The final keyword is used for restricting a class, method, and variable. A final
class can't be inherited, a final method is disabled from overriding, and a final variable
becomes a constant i.e., its value can't be changed.
class FinalVarExample {
Finally: Any code inside the final block will be executed, irrespective of whether an
exception is handled or not.
class FinallyExample {
try {
int x=100;
catch(Exception e) {
System.out.println(e);
finally {
Finalize: The finalize method performs the clean up just before the object is garbage
collected.
class FinalizeExample {
System.out.println("Finalize is called");
f1= NULL;
f2=NULL;
System.gc();
Deserialization is the exact opposite process of serialization where Java objects are
retrieved from the byte stream.
There can be several reasons that result in the OutOfMemoryError exception, of which
the most notable ones are:
● Using an application server that doesn't perform a memory cleanup post the
deployment
Any class can access the main() method defined 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 defines the method that does not
● main: JVM searches this method when starting the execution of any program,
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
boxing.
● Auto unboxing: Getting the primitive value directly into the integer object.
int i = 5;
Integer jj = i; /*Unboxing*/
65. Define the Singleton class. How can a class be made Singleton?
A Singleton class allows only one instance of the class to be created. A class can be
made singleton with the following steps:
2. By not allowing the user to create an instance with default constructor by defining
a private constructor.
3. Create a static method to return the object of an instance of A.
class Single
}
66. What if the public static void is replaced by static public void, will the
program still run?
Yes, the program would compile and run without any errors as the order of the specifiers
doesn't matter.
Equals() ==
{ {
/* boolean type*/
System.out.println(true == true);
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 It is used to call the default constructor of
of the same class the parent/base class.
Accesses method of the current class Accesses method of the base class
Must be the first line of the block It must be the first line of the block.
Java Coding Interview Questions
Apart from having good knowledge about concepts of Java programming, you are also
tested for your skills in coding in Java programming language. The following are Java
coding interview questions that are relevant for freshers and are quite popular amongst
Java programming interviews.
70. Take a look at the two code snippets below. What is the important
difference between the two?
i.
class Adder {
return a+b;
return a+b;
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”);
void run()
b.run();
Code snippet i. is an example of method overloading while the code snippet ii.
demonstrates method overriding.
71. Write a program for string reversal without using an inbuilt function.
{
public static void main(String args[])
System.out.print(charArray[i]);
System.out.println();
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
class RemoveDuplicates
{
public static void main(String args[])
duplicate.add(5);
duplicate.add(7);
duplicate.add(1);
duplicate.add(4);
duplicate.add(1);
duplicate.add(7);
duplicate.clear();
duplicate.addAll(withoutDuplicates);
import java.util.Scanner;
int reverse = 0;
int remainder = 0;
do{
remainder = number%10;
number = number/10;
return reverse;
}
74. Write a program that implements binary search.
import java.util.Scanner;
import java.util.Arrays;
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.println("Please enter number to be searched in sorted array");
if (index == -1) {
} else {
index);
int low = 0;
if (input[middle] == number) {
return middle;
low = middle + 1;
return -1;
import java.util.Scanner;
if(num!=0)
isPrime = checkPrime(num);
}else
{
if(isPrime == false)
else
System.out.println("PRIME!!");
if(number % i== 0)
return false;
}
return true;
import java.util.Scanner;
}
public static int fib(int n)
return 1;
import java.util.Scanner;
boolean isPalindrome;
isPalindrome = checkPalindrome(str);
if(str.equals(" "))
else
if(isPalindrome)
System.out.println("PALINDROME!!");
else
System.out.println("NOT A PALINDROME!!");
if(input.charAt(i) != input.charAt(j))
return false;
i++;
j--;
return true;
**
***
****
*****
Answer:
{
for(int i=5; i>=0; i--)
System.out.println();
System.out.print(" * ");
System.out.println();
import java.util.Scanner;
int a = s.nextInt();
System.out.println("Enter second number: ");
int b = s.nextInt();
swap(a,b);
int swap_variable;
swap_variable = a;
a = b;
b = swap_variable;
import java.util.Scanner;
while(a%10 !=0)
num = a%10;
a = a/10;
if(sum == number)
System.out.println("Armstrong Number!");
else
}
}
Summary
These core Java Interview Questions and Java Programming Interview Questions are a
great way to prepare you for the interview.
You can also take a look at this course for further reading and preparing for a
Java-based interview: Java interview Guides: 200+ Interview Question and Answer
We recommend this book to help you succeed in your future Java interviews: Elements
of Programming Interviews in Java: The insider guide second edition
There are several basic Java interview questions that can appear in an interview. Look at the
ones we’ve listed above to get a sense of them.
You should prepare for a Java interview by learning both the theory and practicing coding. There
are several related questions above.
Advanced Java interview questions can be of many kinds, including both theory and
coding-based questions. Check out the list of Java programming questions above to
see what they are like.