Donate : Link
Medium Blog : Link
Applications : Link
Part 1: https://yourcodeacademy.wordpress.com/2020/08/25/java-interview-questions-part-1-code-factory/
Part 3: https://yourcodeacademy.wordpress.com/2021/03/03/java-interview-questions-part-3-code-factory/
1. Difference between Static and Final method in Java?
| Static Method | Final Method |
| Static methods can be overriden, but they cannot be overriden to be non-static. | Final methods cannot be overridden. |
| A static method is a method that’s invoked through a class, rather than a specific object of that class. | A final method is invoked through object of class. |
| Static method contains only static variables. | Final method contains final and non-final variables but not static variables. |
| Only single copy is created though out the application. | No of object of class = No of copy. |
2. Can we Overload or Override static methods in java?
- https://www.geeksforgeeks.org/can-we-overload-or-override-static-methods-in-java/
- Overload: YES, We can have two or more static methods with same name, but differences in input parameters.

- We cannot overload two methods in Java if they differ only by static keyword (number of parameters and types of parameters is same)

- Override: NO, We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism. Hence the answer is ‘No’.

3. Static keyword in Java.
(1) Static keyword in Java
- static data members in Java are class members and shared among all objects. For example, in the following Java program, static variable count is used to count the number of objects created.
public class Temp {
static int count = 0;
Temp() {
count++;
}
public static void main(String args[]) {
Temp t1 = new Temp();
Temp t2 = new Temp();
Temp t3 = new Temp();
System.out.println("Total " + count + " objects created");
}
}
Output:
Total 3 objects created
(2) Static Member Methods
Mmethods declared as static are class members and have following restrictions:
A. They can only call other static methods. For example, the following program fails in compilation. fun() is non-static and it is called in static main()
public class Temp {
public static void main(String args[]) {
// CE: Cannot make a static reference to the non-static method fun() from the type Temp
System.out.println(fun());
}
int fun() {
return 20;
}
}
B. They must only access static data.
C. They cannot access this or super . For example, the following program fails in compilation.
class Parent {
static int x = 20;
}
public class Temp extends Parent {
public static void main(String args[]) {
// CE: Cannot use super in a static context
System.out.println(super.x);
}
}
- static data members and static methods can be accessed without creating an object. They can be accessed using class name. For example, in the following program, static data member count and static method fun() are accessed without any object.
class Parent {
static int x = 20;
public static void fun() {
System.out.println("Static fun() called");
}
}
public class Temp extends Parent {
public static void main(String args[]) {
System.out.println("Count : " + Parent.x);
Parent.fun();
}
}
(3) Static Block
- Java supports a special block, called static block (also called static clause) which can be used for static initialization of a class. This code inside static block is executed only once: the first time the class is loaded into memory. For example, check output of following Java program.
class Test {
static int i;
int j;
static {
i = 10;
System.out.println("Static block called");
}
}
public class Temp {
public static void main(String args[]) {
// Although we don't have an object of Test, static block is
// called because i is being accessed in following statement.
System.out.println(Test.i);
}
}
Output:
Static block called
10
- Also, static blocks are executed before constructors. For example, check output of following Java program.
class Test {
static int i = getI();
int j = getJ();
static {
System.out.println("Static block called " + i);
}
{
System.out.println("Normal block called " + j);
}
Test() {
System.out.println("Constructor called ");
}
static int getI() {
System.out.println("TO CALL STATIC METHOD BEFORE STATIC BLOCK");
return 10;
}
int getJ() {
System.out.println("TO CALL METHOD BEFORE BLOCK");
return 20;
}
}
public class Temp {
public static void main(String args[]) {
// Although we have two objects, static block is executed only once.
Test t1 = new Test();
Test t2 = new Test();
}
}
Output:
TO CALL STATIC METHOD BEFORE STATIC BLOCK
Static block called 10
TO CALL METHOD BEFORE BLOCK
Normal block called 20
Constructor called
TO CALL METHOD BEFORE BLOCK
Normal block called 20
Constructor called
(4) Static Local Variables
- Java doesn’t support static local variables. For example, the following Java program fails in compilation.
public class Temp {
public static void main(String args[]) {
System.out.println(fun());
}
static int fun() {
// CE: Static local variables are not allowed
static int x = 10;
return x;
}
}
4. Static class in Java.
(1) Can a class be static in Java?
- The answer is Yes, some classes can be made static in Java.
- Java allows a class to be defined within another class. These are called Nested Classes. The class in which the nested class is defined is known as the Outer Class. Unlike top level classes, Inner classes can be Static. Non-static nested classes are also known as Inner classes.
- An instance of an inner class cannot be created without an instance of the outer class. Therefore, an inner class instance can access all of the members of its outer class, without using a reference to the outer class instance. For this reason inner classes can help make programs simple and concise.
(2) What are the differences between static and non-static nested classes?
The following are major differences between static nested classes and inner classes.
A. A static nested class may be instantiated without instantiating its outer class.
B. Inner classes can access both static and non-static members of the outer class. A static class can access only the static members of the outer class.
// Java program to demonstrate how to
// implement static and non-static
// classes in a Java program.
class OuterClass {
private static String msg = "Code Factory";
// Static nested class
public static class NestedStaticClass {
// Only static members of Outer class
// is directly accessible in nested
// static class
public void printMessage()
{
// Try making 'message' a non-static
// variable, there will be compiler error
System.out.println("Message from nested static class: " + msg);
}
}
// Non-static nested class - also called Inner class
public class InnerClass {
// Both static and non-static members
// of Outer class are accessible in
// this Inner class
public void display()
{
System.out.println("Message from non-static nested class: " + msg);
}
}
}
class Main {
// How to create instance of static
// and non static nested class?
public static void main(String args[])
{
// Create instance of nested Static class
OuterClass.NestedStaticClass printer
= new OuterClass.NestedStaticClass();
// Call non static method of nested
// static class
printer.printMessage();
// In order to create instance of
// Inner class we need an Outer class
// instance. Let us create Outer class
// instance for creating
// non-static nested class
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner
= outer.new InnerClass();
// Calling non-static method of Inner class
inner.display();
// We can also combine above steps in one
// step to create instance of Inner class
OuterClass.InnerClass innerObject
= new OuterClass().new InnerClass();
// Similarly we can now call Inner class method
innerObject.display();
}
}
Output:
Message from nested static class: Code Factory
Message from non-static nested class: Code Factory
Message from non-static nested class: Code Factory
5. What is difference between Stack and Heap area of JVM Memory? What is stored inside a stack and what goes into heap?
- The biggest difference between Heap and Stack section of memory is the lifecycle of the objects that reside in these two memory locations
- Memory of Stack Section is bound to a method context and is destroyed once a thread returns from the function i.e. the Stack objects exists within the scope of the function they are created in.
- On the other hand Heap objects exists outside the method scope and are available till GC recollects the memory.
- Java stores all objects in Heap weather they are created from within a method or class. Escape analysis can be enabled in compiler to hint JVM to create method local objects in stack if the objects does not escape the method context. All class level variables and references are also stored in heap so that they can be accessed from anywhere. Metadata of classes, methods, etc also reside in Heap’s PermGen space.
- The Stack section of memory contains methods, local variables and reference variables and all os these are cleared when a thread returns from the method call.
6. Difference between String pool and String heap.
7. Diff bw == and equals
- https://yourcodeacademy.wordpress.com/2020/05/11/java-operator-vs-equals-method-code-factory/
- The equals() method compares the “value” inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not.
- If any two object references of type String refer to the same String instance then great! If the two object references refer to two different String instances .. it doesn’t make a difference. Its the “value” (that is: the contents of the character array) inside each String instance that is being compared.
- On the other hand, the “==” operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references “refer to” the same String instance then the result of the boolean expression would be “true”. If, on the other hand, the value of both object references “refer to” different String instances (even though both String instances have identical “values”, that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be “false”.
8. Is String a wrapper class?
- String is not a wrapper class, simply because there is no parallel primitive type that it wraps. A string is a representation of a char sequence but not necessarily a ‘wrapper’. Autoboxing and unboxing for example do not apply to String. But they do apply to primitives such as int long etc.
9. String a = “abc” and String a = new String(“abc”). How many objects created and where is stored.
- String a = “abc” = 1 object in SCP

- String a = new String(“abc”) = 1 object in Heap and 1 object in SCP

10. What is singleton class? Where is it used?
- The Singleton’s purpose is to control object creation, limiting the number of objects to only one. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources, such as database connections or sockets.
- It is used where only a single instance of class is required to control the action throughout the execution. A singleton class shouldn’t have multiple instances in any case and at any cost. Singleton classes are used for logging, driver objects, caching and thread pool, database connections.
11. How to use singletone class in multithreaded environment ..OR.. multiple object call singleton class java.
- https://yourcodeacademy.wordpress.com/2020/06/10/java-singleton-design-pattern-example-code-factory/
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
// This is called only once
System.out.println("Private Constructor is called");
}
public static Singleton getInstance() {
return INSTANCE;
}
public static void main(String[] args) {
// Even if you ask 100 times, this will only return the same INSTANCE
Singleton stc = Singleton.getInstance();
Singleton stc1 = Singleton.getInstance();
Singleton stc2 = Singleton.getInstance();
}
}
12. Serializable interface
- https://yourcodeacademy.wordpress.com/2019/09/22/serialization-and-deserialization-in-java-code-factory/
- https://yourcodeacademy.wordpress.com/2020/08/20/java-serialversionuid-in-java-code-factory/
- https://java-questions.com/Serialization-interview-questions.html
- https://www.java67.com/2012/10/difference-between-serializable-vs-externalizable-interface.html
- To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its sub interface, java.io.Externalizable.
13. What is Serialization, Deserialization and Externalization?
- Serialization is a mechanism of converting the state of an object into a byte stream.
- Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory.
- Externalization serves the purpose of custom Serialization, where we can decide what to store in stream. Externalizable interface present in java.io, is used for Externalization which extends Serializable interface. It consist of two methods which we have to override to write/read object into/from stream which are

14. What is transient variable?
- Transient is a Java keyword which marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be ‘serialized’. Serialization converts the object state to serial bytes.
15. How to create immutable class? How to create an immutable class with mutable object references in Java?
16. Final, Finally and Finalize
| final | finally | finalize |
| Final is used to apply restrictions on class, method and variable. Final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed. | Finally is used to place important code, it will be executed whether exception is handled or not. | Finalize is used to perform clean up processing just before object is garbage collected. |
| Final is a keyword. | Finally is a block. | Finalize is a method. |
17. Method overloading overriding
| Method Overloading | Method Overriding |
| Method overloading is used to increase the readability of the program. | Method overriding is used to provide the specific implementation of the method that is already provided by its super class. |
| Method overloading is performed within class. | Method overriding occurs in two classes that have IS-A (inheritance) relationship. |
| In case of method overloading, parameter must be different. | In case of method overriding, parameter must be same. |
| Method overloading is the example of compile time polymorphism. | Method overriding is the example of run time polymorphism. |
| In java, method overloading can’t be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. | Return type must be same or covariant in method overriding. |
// Method Overloading
class OverloadingExample{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
// Method Overriding
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
}
18. Implementation of hashCode() and equals() method with program.
- By default, the Java super class java.lang.Object provides two important methods for comparing objects: equals() and hashcode(). These methods become very useful when implementing interactions between several classes in large projects.
- equals(Object obj): a method provided by java.lang.Object that indicates whether some other object passed as an argument is “equal to” the current instance. The default implementation provided by the JDK is based on memory location — two objects are equal if and only if they are stored in the same memory address.
- hashcode(): a method provided by java.lang.Object that returns an integer representation of the object memory address. By default, this method returns a random integer that is unique for each instance. This integer might change between several executions of the application and won’t stay the same.
- https://dzone.com/articles/working-with-hashcode-and-equals-in-java
package com.example.java.programming;
import java.util.HashSet;
import java.util.Set;
/**
* @author code.factory
*
*/
public class EqualHashcode {
public static void main(String... args) {
Employee e1 = new Employee(1, "code");
Employee e2 = new Employee(2, "code");
System.out.println(e1 == e2);
System.out.println(e1.equals(e2));
Set<Employee> set = new HashSet<Employee>();
set.add(e1);
set.add(e2);
System.out.println(set);
}
}
class Employee {
int id;
String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object arg0) {
Employee e = (Employee) arg0;
return this.name.equals(e.name);
}
@Override
public int hashCode() {
return this.name.charAt(0);
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + "]";
}
}
Output:
false
true
[Employee [id=1, name=code]]
19. Access modifiers
| Access Modifier | within class | within package | outside package by subclass only | outside package |
| Private | Y | N | N | N |
| Default | Y | Y | N | N |
| Protected | Y | Y | Y | N |
| Public | Y | Y | Y | Y |
20. What should be Access Modifier in child class in inheritance.
Their is Only one rule while doing Method overriding with Access modifiers i.e.
If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
Access modifier restrictions in decreasing order:
- private
- default
- protected
- public
i.e. private is more restricted then default and default is more restricted than protected and so on.
Example 1:
class A {
protected void method()
{
System.out.println("Hello");
}
}
public class B extends A {
// Compile Time Error
void method()
{
System.out.println("Hello");
}
public static void main(String args[])
{
B b = new B();
b.method();
}
}
Output:
Compile Time Error
Note: In the above Example Superclass class A defined a method whose access modifier is protected. While doing method overriding in SubClass Class B we didn’t define any access modifier so Default access modifier will be used. By the rule, Default is more restricted then Protected so this program will give compile time error. Instead of default, we could’ve used public which is less restricted then protected.
Example 2:
class A {
protected void method()
{
System.out.println("Hello");
}
}
public class B extends A {
public void method()
{
System.out.println("Hello");
}
public static void main(String args[])
{
B b = new B();
b.method();
}
}
Output:
Hello
Note: In the above Example Superclass class A defined a method whose access modifier is protected. While doing method overriding in SubClass Class B we define access modifier as Public. Because Public access modifier is less restricted than Protected hence this program compiles successfully.
21. Java access modifiers with method overriding. *
- https://www.geeksforgeeks.org/overriding-in-java/
- * From Java 5.0 onwards it is possible to have different return type for a overriding method in child class, but child’s return type should be sub-type of parent’s return type. This phenomena is known as covariant return type.
22. Method Overloading with Autoboxing and Widening in Java.
23. Garbage collection
24. Difference between single threaded and multithreaded application in java.
- The main difference between single thread and multi thread in Java is that single thread executes tasks of a process while in multi-thread, multiple threads execute the tasks of a process.
- A process is a program in execution. Process creation is a resource consuming task. Therefore, it is possible to divide a process into multiple units called threads. A thread is a lightweight process. It is possible to divide a single process into multiple threads and assign tasks to them. When there is one thread in a process, it is called a single threaded application. When there are multiple threads in a process, it is called a multi-threaded application.
25. Thread

A Thread is a flow of execution, every Thread is a seperate independant job is there.
We can define a Thread in the following 2 ways :
- Defining a Thread by Extending Thread Class
- By implementing runnable (3 ways)
26. Difference between wait() and sleep().
- The fundamental difference is wait() is from Object and sleep() is static method of Thread.
- The major difference is that wait() releases the lock while sleep() doesn’t releas any lock while waiting.
- The wait() is used for inter-thread communication while sleep() is used to introduce pause on execution, generally.
- The wait() should call from inside synchronise or else we get IllegalMonitorStateException while sleep() can call anywhere.
- To start thread again from wait(), you have to call notify() or notifyAll(). While in sleep(), thread gets start after specified ms/sec interval.
27. Difference/Comparison Table for yield(), join() and sleep().
| Property | yield() | join() | sleep() |
| pupose | pause execution and give chance to other some priority thread | wait for other thread to complete | if thread don’t want to perform any operation |
| is it overloaded (methods) | No | Yes | Yes |
| is it final | No | Yes | No |
is it throw InterruptedException | No | Yes | Yes |
| is it Native | Yes | No | – sleep(ml) is native – sleep(ml, n) is not |
| is it static | Yes | No | Yes |
28. Inter Thread Communication : wait(), notify() and notifyAll().
- 2 Threads can communicate with each other by wait(), notify() and notifyAll() methods.
- The Thread which is expecting updation is responsible to call wait() method then immediately the Thread will entered into waiting state.
- The Thread which is responsible to perform updation after performing updation it is responsible to call notify() method then waiting Thread will get that notification and continue with those updation items.
- wait(), notify() and notifyAll() methods present in Object class but not in Thread class because Thread can call this methods on any Java objects.
- To call wait(), notify() or notifyAll() methods on any object, thread should be owner of that object that is the thread has lock of that object that is the thread should be inside Synchronized area. Hence we can wait(), notify() and notifyAll() methods only from Synchronized area otherwise we will get runtime exception (RE) saying
IllegalMonitorStateException. - If a thread calls wait() method on any object it immediately release the lock of that particular object and entered into waiting state.
- If a thread calls notify() method on any object it release the object of that object but may not immediately. Except wait(), notify() and notifyAll(), there is no any other method where thread release the lock.
Method Is thread release lock?
yield() -> No
join() -> No
sleep() -> No
wait() -> Yes
notify() -> Yes
notifyAll() -> Yes
29. Deadlock in Java Multithreading
- https://www.geeksforgeeks.org/deadlock-in-java-multithreading/
- https://yourcodeacademy.wordpress.com/2020/05/25/java-deadlock-code-factory/
- Synchronized keyword is used to make the class or method thread-safe which means only one thread can have lock of synchronized method and use it, other threads have to wait till the lock releases and anyone of them acquire that lock.
- It is important to use if our program is running in multi-threaded environment where two or more threads execute simultaneously. But sometimes it also causes a problem which is called Deadlock. Below is a simple example of Deadlock condition.

30. Understanding Time Complexity with Simple Examples.
- Imagine a classroom of 100 students in which you gave your pen to one person. Now, you want that pen. Here are some ways to find the pen and what the O order is.
- O(n2): You go and ask the first person of the class, if he has the pen. Also, you ask this person about other 99 people in the classroom if they have that pen and so on,
- This is what we call O(n2).
- O(n): Going and asking each student individually is O(N).
- O(log n): Now I divide the class into two groups, then ask: “Is it on the left side, or the right side of the classroom?” Then I take that group and divide it into two and ask again, and so on. Repeat the process till you are left with one student who has your pen. This is what you mean by O(log n).
31. Synchronized
32. Synchronized block and synchronized method difference in java.
33. is synchronized a modifier identifier what is it?.
- Synchronized is a keyword and a modifier. The synchronized keyword is used to indicate that a method can be accessed exclusively by one thread at a time.
34. How to access protected variables in another class in Inheritance.
class Parent {
protected String protectedStr;
}
class Child extends Parent {
Child() {
sop(protectedStr) // accessible
}
public static void main(String... args) {
sop(protectedStr) // not accessible
sop(new Child().protectedStr); // accessible
sop(new Parent().protectedStr); // accessible
}
}
- Why does this work? -> Because you’ve inherited the class.
That means you’ve got all of its methods and it’s variables.
Now, because your method and variable is protected, it also means that it can be accessed from the subclass.
35. Which value will be returned by below program?
public int temp() {
try {
return 1;
} catch(Exception e) {
return 2;
} finally {
return 3;
}
}
// It will return 3
36. When use abstract class and interface when you design structure of application.
Consider using abstract classes if any of these statements apply to your situation:
- In java application, there are some related classes that need to share some lines of code then you can put these lines of code within abstract class and this abstract class should be extended by all these related classes.
- You can define non-static or non-final field(s) in abstract class, so that via a method you can access and modify the state of Object to which they belong.
- You can expect that the classes that extend an abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
Consider using interfaces if any of these statements apply to your situation:
- It is total abstraction, All methods declared within an interface must be implemented by the class(es) that implements this interface.
- A class can implement more than one interface. It is called multiple inheritance.
- You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
37. Why java have wrapper classes OR Why we need Wrapper Class.
- A Wrapper class is a class which contains the primitive data types (int, char, short, byte, etc). In other words, wrapper classes provide a way to use primitive data types (int, char, short, byte, etc) as objects. These wrapper classes come under java.util package.
- Why we need Wrapper Class:
- Wrapper Class will convert primitive data types into objects. The objects are necessary if we wish to modify the arguments passed into the method (because primitive types are passed by value).
- The classes in java.util package handles only objects and hence wrapper classes help in this case also.
- Datastructures in the Collection framework such as ArrayList and Vector store only the objects (reference types) and not the primitive types.
- The object is needed to support synchronization in multithreading.
38. What does threadsafe mean?
- A piece of code is thread-safe if it functions correctly during simultaneous execution by multiple threads.
- It must satisfy the need for multiple threads to access the same shared data.
- The need for a shared piece of data to be accessed by only one thread at any given time.
39. Utility methods of Wrapper classes
1) valueOf() method: We can use valueOf() method to create Wrapper object for given primitive or String. There are 3 types of valueOf() methods:
- Wrapper valueOf(String s) : Every wrapper class except Character class contains a static valueOf() method to create Wrapper class object for given String.
public static Wrapper valueOf(String s);
- Wrapper valueOf(String s, int radix): Every Integral Wrapper class Byte, Short, Integer, Long) contains the following valueOf() method to create a Wrapper object for the given String with specified radix. The range of the radix is 2 to 36.
public static Wrapper valueOf(String s, int radix);
- Wrapper valueOf(primitive p): Every Wrapper class including Character class contains the following method to create a Wrapper object for the given primitive type.
public static Wrapper valueOf(primitive p);
2) xxxValue() method: We can use xxxValue() methods to get the primitive for the given Wrapper Object. Every number type Wrapper class( Byte, Short, Integer, Long, Float, Double) contains the following 6 methods to get primitive for the given Wrapper object:
- public byte byteValue()
- public short shortValue()
- public int intValue()
- public long longValue()
- public float floatValue()
- public float doubleValue()
3) parseXxx() method: We can use parseXxx() methods to convert String to primitive. There are two types of parseXxx() methods:
- primitive parseXxx(String s): Every Wrapper class except character class contains the following parseXxx() method to find primitive for the given String object.
public static primitive parseXxx(String s);
- parseXxx(String s, int radix): Every Integral type Wrapper class (Byte, Short, Integer, Long) contains the following parseXxx() method to convert specified radix String to primitive.
public static primitive parseXxx(String s, int radix);
4) toString() method: We can use toString() method to convert Wrapper object or primitive to String. There are few forms of toString() method:
- public String toString(): Every wrapper class contains the following toString() method to convert Wrapper Object to String type.
public String toString();
- toString(primitive p): Every Wrapper class including Character class contains the following static toString() method to convert primitive to String.
public static String toString(primitive p);
- toString(primitive p, int radix): Integer and Long classes contains the following toString() method to convert primitve to specified radix String.
public static String toString(primitive p, int radix);
- * All wrapper classes implements Comparable<Wrapper> interface so all override compareTo(Wrapper wrapper). They also have hashCode() and equals(Object obj) methods.
40. Exceptions
- An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
- we have three categories of Exceptions.
- Checked exceptions: A checked exception is an exception that is checked (notified) by the compiler at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply be ignored, the programmer should take care of (handle) these exceptions.
- Unchecked exceptions: An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.
- Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation. E.g. java.lang.StackOverflowError
| Errors | Exceptions |
| Recovering from Error is not possible. | We can recover from exceptions by either using try-catch block or throwing exceptions back to caller. |
| All errors in java are unchecked type. | Exceptions include both checked as well as unchecked type. |
| Errors are mostly caused by the environment in which program is running. | Program itself is responsible for causing exceptions. |
| Errors occur at runtime and not known to the compiler. | All exceptions occurs at runtime but checked exceptions are known to compiler while unchecked are not. |
| They are defined in java.lang.Error package. | They are defined in java.lang.Exception package |
| Examples : java.lang.StackOverflowError, java.lang.OutOfMemoryError | Examples : Checked Exceptions : SQLException, IOException Unchecked Exceptions : ArrayIndexOutOfBoundException, NullPointerException, ArithmeticException. |

41. Assigning values to final variables in Java.
class Test {
// i could be assigned a value here
// or constructor or init block also.
final int i;
Test()
{
i = 10;
}
// other stuff in the class
}
If we make i as static final then we must assign value to i with the delcaration.
class Test {
// Since i is static final,
// it must be assigned value here
// or inside static block .
static final int i;
static
{
i = 10;
}
// other stuff in the class
}
42. Shallow Copy and Deep Copy
class Address {
private String street;
private String city;
private String country;
// standard constructors, getters and setters
}
class User {
private String firstName;
private String lastName;
private Address address;
// standard constructors, getters and setters
}
1) Shallow Copy:
- A shallow copy is one in which we only copy values of fields from one object to another:
@Test
public void whenShallowCopying_thenObjectsShouldNotBeSame() {
Address address = new Address("Downing St 10", "London", "England");
User pm = new User("Prime", "Minister", address);
User shallowCopy = new User(
pm.getFirstName(), pm.getLastName(), pm.getAddress());
assertThat(shallowCopy).isNotSameAs(pm);
}
- In this case pm != shallowCopy, which means that they’re different objects, but the problem is that when we change any of the original address’ properties, this will also affect the shallowCopy‘s address.
@Test
public void whenModifyingOriginalObject_ThenCopyShouldChange() {
Address address = new Address("Downing St 10", "London", "England");
User pm = new User("Prime", "Minister", address);
User shallowCopy = new User(
pm.getFirstName(), pm.getLastName(), pm.getAddress());
address.setCountry("Great Britain");
assertThat(shallowCopy.getAddress().getCountry())
.isEqualTo(pm.getAddress().getCountry());
}
2) Deep Copy:
- A deep copy is an alternative that solves this problem. Its advantage is that at least each mutable object in the object graph is recursively copied.
- Since the copy isn’t dependent on any mutable object that was created earlier, it won’t get modified by accident like we saw with the shallow copy.
- In the following sections, we’ll show several deep copy implementations and demonstrate this advantage.
2.1) Copy Constructor
public Address(Address that) {
this(that.getStreet(), that.getCity(), that.getCountry());
}
public User(User that) {
this(that.getFirstName(), that.getLastName(), new Address(that.getAddress()));
}
@Test
public void whenModifyingOriginalObject_thenCopyShouldNotChange() {
Address address = new Address("Downing St 10", "London", "England");
User pm = new User("Prime", "Minister", address);
User deepCopy = new User(pm);
address.setCountry("Great Britain");
assertNotEquals(
pm.getAddress().getCountry(),
deepCopy.getAddress().getCountry());
}
2.2) Cloneable Interface
- The second implementation is based on the clone method inherited from Object. It’s protected, but we need to override it as public.
- We’ll also add a marker interface, Cloneable, to the classes to indicate that the classes are actually cloneable.
- Let’s add the clone() method to the Address class:
@Override
public Object clone() {
try {
return (Address) super.clone();
} catch (CloneNotSupportedException e) {
return new Address(this.street, this.getCity(), this.getCountry());
}
}
- And now let’s implement clone() for the User class:
@Override
public Object clone() {
User user = null;
try {
user = (User) super.clone();
} catch (CloneNotSupportedException e) {
user = new User(
this.getFirstName(), this.getLastName(), this.getAddress());
}
user.address = (Address) this.address.clone();
return user;
}
- Note that the super.clone() call returns a shallow copy of an object, but we set deep copies of mutable fields manually, so the result is correct:
@Test
public void whenModifyingOriginalObject_thenCloneCopyShouldNotChange() {
Address address = new Address("Downing St 10", "London", "England");
User pm = new User("Prime", "Minister", address);
User deepCopy = (User) pm.clone();
address.setCountry("Great Britain");
assertThat(deepCopy.getAddress().getCountry())
.isNotEqualTo(pm.getAddress().getCountry());
}
43. How many Ways to Create an Object in Java?
1) Java new Operator
A a = new A();
2) Java Class.newInstance() method
A a = A.class.newInstance();
3) Java newInstance() method of Constructor class
import java.lang.reflect.Constructor;
Constructor<A> a = A.class.getConstructor();
4) Java Object.clone() method
public class A implements Cloneable {
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
PSVM(String... args) {
A a1 = new A();
A a2 = a1.clone();
}
}
5) Java Object Serialization and Deserialization
- Serialize object and store into file (must have extension .ser) and then Deserialize object.
44. this and super keyword.
- this() and super(), both are the constructors that’s why must be the first statement.
- Because if you use this() and super() together in a constructor it will give compile time error. Because this() and super() must be the first executable statement. If you write this() first than super() will become the second statement and vice-versa. That’s why we can’t use this() and super() together.
this:
- The
thiskeyword refers to the current object in a method or constructor. - The most common use of the
thiskeyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter). thiscan also be used to:- Invoke current class constructor
- Invoke current class method
- Return the current class object
- Pass an argument in the method call
- Pass an argument in the constructor call
super:
- The
superkeyword refers to superclass (parent) objects. - It is used to call superclass methods, and to access the superclass constructor.
- The most common use of the
superkeyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.
45. Can I define an abstract class without adding an abstract method?
- Of course.
- Declaring a class abstract only means that you don’t allow it to be instantiated on its own.
- Declaring a method abstract means that subclasses have to provide an implementation for that method.
- The two are separate concepts, though obviously you can’t have an abstract method in a non-abstract class.
46. Why we require getters and setters.
- The main difference between making a field public vs. exposing it through getters/setters is holding control over the property. If you make a field public, it means you provide direct access to the caller. Then, the caller can do anything with your field, either knowingly or unknowingly. For example, one can set a field to a null value, and if you use that field in another method, it may blow up that method with a null pointer exception.
- But, if you provide a getter/setter, you provide them indirect access while taking full control. The only way to set a value is through setter, and you get a value through a getter, so now you have exactly one entry and one exit point for your field, as getter/setters are methods, which allows blocks of code, so you can do validation checks on them! The object takes the decision whether you should set the caller value or not. The same applies to a getter method — you can take the decision to return the actual reference or clone it and return the same to the caller.
47. The catch Blocks
catch (final IOException ex) {
logger.log(ex);
throw ex;
}
... OR ...
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
- * If a
catchblock handles more than one exception type, then thecatchparameter is implicitlyfinal. In this example, thecatchparameterexisfinaland therefore you cannot assign any values to it within thecatchblock.
48. Volatile Keyword in Java
- Volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem. The volatile keyword can be used either with primitive type or objects.
- The volatile keyword does not cache the value of the variable and always read the variable from the main memory. The volatile keyword cannot be used with classes or methods. However, it is used with variables. It also guarantees visibility and ordering. It prevents the compiler from the reordering of code.
class Test {
static int var=5;
}
- In the above example, assume that two threads are working on the same class. Both threads run on different processors where each thread has its local copy of var. If any thread modifies its value, the change will not reflect in the original one in the main memory. It leads to data inconsistency because the other thread is not aware of the modified value.
class Test {
static volatile int var = 5;
}
- In the above example, static variables are class members that are shared among all objects. There is only one copy in the main memory. The value of a volatile variable will never be stored in the cache. All read and write will be done from and to the main memory.
| Volatile Keyword | Synchronization Keyword |
| Volatile keyword is a field modifier. | Synchronized keyword modifies code blocks and methods. |
| The thread cannot be blocked for waiting in case of volatile. | Threads can be blocked for waiting in case of synchronized. |
| It improves thread performance. | Synchronized methods degrade the thread performance. |
| It synchronizes the value of one variable at a time between thread memory and main memory. | It synchronizes the value of all variables between thread memory and main memory. |
| Volatile fields are not subject to compiler optimization. | Synchronize is subject to compiler optimization. |
49. Is an empty .java file name a valid source file name?
- We can save a file with only .java name. In that case, For compilation purpose we will have to use below command
JAVAC .java- The Javac command will always yield an .class file which is further compiled to get the output.
- Now suppose you have creeated a class say Student, then the outcome of the command
- Javac .java will give you an class file whose name would be Student.class (similar to class you have defined in your code), now in order to get the output , please run the below command
Java Student
50.

