Show Menu
Cheatography

Java Interview Questions Cheat Sheet (DRAFT) by

Common Java Interview Questions Source: https://medium.com/@s.sreejith/core-java-interview-cheat-sheet-dce4f2590f4f

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Other Concepts

Dependency Injection
Dependency Injection is a design pattern used in software develo­pment to manage depend­encies between objects. It allows the depend­encies of a class to be provided extern­ally, rather than having the class create or manage them intern­ally. This pattern promotes loose coupling and makes the code more modular, testable, and mainta­inable.
Dependency Injection in Spring
Dependency Injection (DI) is a fundam­ental concept in the Spring framework, which provides a powerful and flexible way to manage depend­encies in a Java applic­ation. Spring's DI container, also known as the Spring IoC (Inversion of Control) container, is respon­sible for instan­tiating and wiring depend­encies for your applic­ation.
Lifecycle of a Spring bean
1. Bean Definition: In this stage, the bean config­uration is defined in either XML or Java-based config­ura­tion. It includes specifying the bean class, depend­encies, and other proper­ties.
 
2. Instan­tiation: During this stage, the Spring container creates an instance of the bean based on the bean defini­tion. The container uses the bean's constr­uctor or a factory method to create the object.
 
3. Dependency Injection: Once the bean is instan­tiated, the container injects any required depend­encies into the bean. This can be done through constr­uctor injection, setter injection, or field injection.
 
4. Bean Post-P­roc­essing: After dependency injection, Spring applies any registered BeanPo­stP­roc­essors to modify the bean instance. BeanPo­stP­roc­essors can perform tasks such as initia­lizing proxy objects or adding additional behavior to the bean.
 
5. Initia­liz­ation: At this stage, any initia­liz­ation logic specified for the bean is executed. This can involve implem­enting the Initia­liz­ingBean interface, defining custom initia­liz­ation methods using annota­tions, or specifying initia­liz­ation methods in the bean config­ura­tion.
 
6. Ready for Use: After initia­liz­ation, the bean is ready for use. It can now respond to requests and perform its designated tasks.
 
7. Usage: During this stage, the bean is actively used by other components or services in the applic­ation. It carries out its assigned functi­onality and can be accessed and manipu­lated as needed.
 
8. Destru­ction: When the bean is no longer needed or when the applic­ation is shutting down, the container triggers the destru­ction of the bean. This involves executing any defined destru­ction logic, such as implem­enting the Dispos­abl­eBean interface, specifying custom destru­ction methods using annota­tions, or defining destru­ction methods in the bean config­ura­tion.
Spring IoC (Inversion of Control) container
The Spring IoC (Inversion of Control) container is a core component of the Spring framework that manages the lifecycle and depend­encies of objects (beans) in a Spring applic­ation. The IoC container is respon­sible for creating, config­uring, and wiring the beans, allowing developers to focus on writing the business logic of their applic­ation.

Basic

Java language and platform
Java language : High level, Platform Indepe­ndent, Portable
 
Java platform : JRE and API
JVM, JRE & JDK
JVM : VM that provide specif­ication for JRE.
 
JRE : implem­ent­ation of JVM where the byte code get executed.
 
JDK : JRE + Tools (javac, javadoc, jar).
Static
Static Variable : belong to class and get memory only once in class area at the time of class loading.
 
Static Method : belong to class, cant use non static variables and methods inside if it is not known
 
Static Block : initialize static variables and executed before main method at the time of class loading.
 
Static Import : access any static member of a class directly. There is no need to qualify it by the class name in program.
Access Modifiers
Public > Protected > Default > Private
Final
variable (can’t change, constant), method­(can’t override), class (can’t inherit)
Package
group of similar classes, interface and sub package.
 
java.lang package is imported implic­itly( Throwable, Iterable, Compar­able, Object).

STRING

Java String
Immutable
 
Literals — stored in string constant pool(i­nside heap)i­ntern()
 
Object — stored directly in heap
 
When the intern() method is executed then it checks whether the String equals to this String Object is in the pool or not. If it is available, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
String­Buffer
mutable
 
thread safe and synchr­onized
 
less efficient than String­Builder
String­Builder
mutable
 
non-sy­nch­ron­ize­d,i.e., not thread safe
 
more efficient than String­Buffer

Object

Every class in Java is directly or indirectly derived from the Object class.
toString() : provides String repres­ent­ation of an Object. The default toString() method for class Object returns a string consisting of class name+@­+un­signed hexade­cimal repres­ent­ation of the hash code of the object.
hashCode() : For every object, JVM generates a unique number which is hashcode.
equals­(Object obj) : Compares the given object to “this” object
finalize() method : This method is called just before an object is garbage collected. It is called by the Garbage Collector on an object when garbage collector determines that there are no more references to the object.
clone() : It returns a new object that is exactly the same as this object
wait(), notify() notify­All() are related to Concur­rency.
 

OOP

Object
real time entity with state and behavior.
Class
collection of similar Objects.
 
Constr­uctor : special function used to initialize state of an object. No return Type but returns current instance of the class. Not inherited so cant make final. Called by super() method from child class.Cant have this() and Super() together in constr­uctor as both should be the first statement.
 
this : points current object, it is final type, can be used in synchr­onized block
Encaps­ulation
wrapping data and associated function into single unit implements data hiding using private property accessed using getter and setter methods.
Inheri­tance
mechanism by which one class acquire properties and behavior of another on class, Code re-usa­bility.
 
Super : points to parent class object.
Polymo­rphism
same message can be processed in more than one form.
 
Method Overlo­ading : same function name but differ in number and type of arguments within the same class, Readab­ility , Compile time.
 
Method overriding : specific implem­ent­ation of method in child class which is already defined in defined in parent class, Run time(only method not property).
 
Covarient return type : child class method return type should be sub type of return type of parent class.
Abstra­ction
implem­ent­ation hiding using Abstract class and Interface.
 
Abstract class : cant be instan­tiated, should have at least one abstract method, can have constr­uct­or(­called by extended class constr­uctor during object creation).
 
Interface : no constr­uctor and instance, public static final members.
 
Tagged­/Marker interface: no members defined, used to give mark/tag. eg: serial­izable, clonable.
Relation
Associ­ation : relati­onship where all objects have their own life-cycle & there is no ownership. eg: teache­r-s­tudent
 
Aggreg­ation : special type of associ­ation, separate life cycle but there is ownership eg : depart­ment- teacher
 
Compos­ition : Special type of aggreg­ation, no separate life cycle and if parent deleted, all child will get delete.

Collection

Collection
Interface in java.util package extended Iterable interface.
List
maintain insertion order, include duplicate elements, can have null entry.
 
ArrayList : dynamic array, index based, best for store and fetch, increases size by half
 
LinkedList : doubly linked list, best for adding and removing
Queue
Priori­tyQ­ueue, Dequeu­e-A­rra­yDe­queue
 
Priori­tyQueue : min/max heap
Set
no duplicate elements
 
HashSet : no order mainta­ined, can have single null
 
Linked­HashSet : insertion order mainta­ined, can have single null
 
TreeSet : sorted, no null value
Map
key value pair, unique key
 
HashMap : no order, can have single null key
 
Linked­HashMap : insertion order, can have single null key
 
TreeMap : sorted based on key, can’t have any null key
Collec­tions
java.u­til.Co­lle­ctions utility class
 
Sorting : List by Collec­tio­ns.s­ort(), Set by converting to TreeSet, Map by converting to TreeMap, Need to implement Comparable or Comparator
 
Comparable : lang, compar­eTo(), change base class, single sort logic
 
Comparator : util, compare(), don’t change base class, multiple sort logic
 
Unmodi­fiable : unmodi­fia­ble­Col­lec­tion() return an unmodi­fiable view of the specified collection
Legacy Class
all are synchr­onized and thread safe
 
Property, Vector­(in­crease size by double), Stack, HashTa­ble(no null key and null value)
Iteration
Iterator : legacy iteration support, list and set, can remove, forward only
 
ListIt­erator : legacy iteration support, list, can remove and add, forward and backward
 
Enumerator : only for legacy support
 
 
To succes­sfully store and retrieve objects from a Hashtable, the objects used as keys must implement the hashCode method and the equals method. Because hashcode used to find the bucket and equals used to replace existing value in that place of bucket.( if equals not overridden then it insert into a new LinkedList node that it use. It it total violation of rule as key are unique in map)
 

EXCEPTION HANDLING

Throwable
exception and error
Exception
can be handled using try-catch block or throws.
 
checked and unchecked exception
Checked exception
found at compile time.
 
ClassN­otF­oun­dEx­cep­tion, SQLExc­eption, IOExce­ption
Unchecked exception
occur during run time.
 
Arithe­mat­icE­xce­ption, Number­For­mat­Exc­eption, NullPo­int­erE­xce­ption, Arrray­Ind­exO­utO­fBo­und­Exc­eption, String­Ind­exO­utO­fBo­und­Exc­eption
Error
cant be handled
 
Irreco­varable
 
StackO­ver­flo­wError
Finally
block after try/catch, always executed ( not if program exits)
Throw
keyword, within method, followed by instance, single, cant propagate checked exception
Throws
keyword, within method signature, followed by class, multiple, can propagate checked exception
Exception Overriding
if parent method not defined exception, child cant define checked exception but can define unchecked
 
else child can define only sub class exception
Try with resource
autocl­osable

Concur­rency

Fail-fast
immedi­ately throws Concur­ren­tmo­dif­ica­tio­nEx­cep­tion, if any structural modifi­cation occur

Generics

Generic
Generics in progra­mming languages, such as Java, allow the creation of classes, interf­aces, and methods that can work with different types, providing flexib­ility and type safety. It enables the definition of generic algorithms and data structures that can be used with various types without sacrif­icing type checking at compile time.
Wildca­rd(?)
Lower-­bound <? super type>
 
Upper-­bound <? type>
 
Unbound <?>

Memory

Types
Heap Area, Method Area, Stack, Native Method Stack & PC Register
 
You can not force Garbage collection in Java. Though you can request it by calling Sytem.gc() or its cousin Runtim­e.g­etR­unt­ime­().g­c(). It’s not guaranteed that GC will run immedi­ately as result of calling these method
Immutable Class Creation
Declare the class as final so it can’t be extended.
 
Make all fields private so that direct access is not allowed.
 
Don’t provide setter methods for variables
 
Make all mutable fields final so that it’s value can be assigned only once.
 
Initialize all the fields via a constr­uctor performing deep copy.
 
Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.
Deep Copy and Shallow Copy
The shallow copy is the approach when we only copy field values and therefore the copy might be dependent on the original object.
 
In the deep copy approach, we make sure that all the objects in the tree are deeply copied, so the copy isn’t dependent on any earlier existing object that might ever change.

SOLID Principles

Single Respon­sib­ility Principle
The Single Respon­sib­ility Principle states that a class should have only one reason to change, meaning it should have only one respon­sib­ility or job. In other words, a class should have a single purpose or focus.
Open-Closed Principle (OCP)
The Open-C­losed Principle states that software entities (classes, modules, functions, etc.) should be open for extension but closed for modifi­cation. In other words, the behavior of a software entity should be easily extendable without modifying its existing code.
Liskov Substi­tution Principle (LSP):
The Liskov Substi­tution Principle states that objects of a superclass should be replac­eable with objects of its subclasses without affecting the correc­tness of the program. In other words, a subclass should be able to be used wherever its superclass is expected, without causing any unexpected behavior.
Interface Segreg­ation Principle (ISP):
The Interface Segreg­ation Principle states that clients should not be forced to depend on interfaces they do not use. It suggests that interfaces should be specific to the needs of the clients, and no client should be obligated to depend on methods it does not need.
Dependency Inversion Principle (DIP):
The Dependency Inversion Principle states that high-level modules should not depend on low-level modules. Instead, both should depend on abstra­ctions. It also states that abstra­ctions should not depend on details; details should depend on abstra­ctions.