Core Java Interview Cheat Sheet

A curated list of commonly asked core Java concepts

Sreejith
6 min readMar 17, 2019

BASICS

  1. Java language and platform
  • Java language : High level, Platform Independent, Portable
  • Java platform : JRE and API

2. JVM, JRE & JDK

  • JVM : VM that provide specification for JRE.
  • JRE : implementation of JVM where the byte code get executed.
  • JDK : JRE + Tools (javac, javadoc, jar).

3. 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.

4. Access Modifiers

  • Public > Protected > Default > Private

5. Final

  • variable (can’t change, constant), method(can’t override), class (can’t inherit)

6. Package

  • group of similar classes, interface and sub package.
  • java.lang package is imported implicitly( Throwable, Iterable, Comparable, Object).

OOPS

1. Object

  • real time entity with state and behavior.

2. Class

  • collection of similar Objects.
  • Constructor : 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 constructor as both should be the first statement.
  • this : points current object, it is final type, can be used in synchronized block

3. Encapsulation

  • wrapping data and associated function into single unit implements data hiding using private property accessed using getter and setter methods.

4. Inheritance

  • mechanism by which one class acquire properties and behavior of another on class, Code re-usability.
  • Super : points to parent class object.

5. Polymorphism

  • same message can be processed in more than one form.
  • Method Overloading : same function name but differ in number and type of arguments within the same class, Readability , Compile time.
  • Method overriding : specific implementation 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.

6. Abstraction

  • implementation hiding using Abstract class and Interface.
  • Abstract class : cant be instantiated, should have at least one abstract method, can have constructor(called by extended class constructor during object creation).
  • Interface : no constructor and instance, public static final members.
  • Tagged/Marker interface: no members defined, used to give mark/tag. eg: serializable, clonable.

7. Relation

  • Association : relationship where all objects have their own life-cycle & there is no ownership. eg: teacher-student
  • Aggregation : special type of association, separate life cycle but there is ownership eg : department- teacher
  • Composition : Special type of aggregation, no separate life cycle and if parent deleted, all child will get delete.

EXCEPTION HANDLING

  1. Throwable
  • exception and error

2. Exception

  • can be handled using try-catch block or throws.
  • checked and unchecked exception

3. Checked exception

  • found at compile time.
  • ClassNotFoundException, SQLException, IOException

4. Unchecked exception

  • occur during run time.
  • ArithematicException, NumberFormatException, NullPointerException, ArrrayIndexOutOfBoundException, StringIndexOutOfBoundException

5. Error

  • cant be handled
  • Irrecovarable
  • StackOverflowError

6. Finally : block after try/catch, always executed ( not if program exits)

7. Throw : keyword, within method, followed by instance, single, cant propagate checked exception

8. Throws : keyword, within method signature, followed by class, multiple, can propagate checked exception

9. 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

10. Try with resource autoclosable

STRING

  1. Java String
  • Immutable
  • Literals — stored in string constant pool(inside heap)intern()
  • 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.

2. StringBuffer

  • mutable
  • thread safe and synchronized
  • less efficient than StringBuilder

3. StringBuilder

  • mutable
  • non-synchronized,i.e., not thread safe
  • more efficient than StringBuffer

Collection

framework used to store and manipulate group of objects.

  1. Collection
  • Interface in java.util package extended Iterable interface.

2. 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

3. Queue

  • PriorityQueue, Dequeue-ArrayDequeue
  • PriorityQueue : min/max heap

4. Set

  • no duplicate elements
  • HashSet : no order maintained, can have single null
  • LinkedHashSet : insertion order maintained, can have single null
  • TreeSet : sorted, no null value

5. Map

  • key value pair, unique key
  • HashMap : no order, can have single null key
  • LinkedHashMap : insertion order, can have single null key
  • TreeMap : sorted based on key, can’t have any null key

6. Collections

  • java.util.Collections utility class
  • Sorting : List by Collections.sort(), Set by converting to TreeSet, Map by converting to TreeMap, Need to implement Comparable or Comparator
  • Comparable : lang, compareTo(), change base class, single sort logic
  • Comparator : util, compare(), don’t change base class, multiple sort logic
  • Unmodifiable : unmodifiableCollection() return an unmodifiable view of the specified collection

7. Legacy Class

  • all are synchronized and thread safe
  • Property, Vector(increase size by double), Stack, HashTable(no null key and null value)

7. Iteration

  • Iterator : legacy iteration support, list and set, can remove, forward only
  • ListIterator : legacy iteration support, list, can remove and add, forward and backward
  • Enumerator : only for legacy support

To successfully 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)

Generics

  1. Generic
  • type-safe and checked at compile time

2. Wildcard(?)

  • Upper-bound <? extend type>
  • Lower-bound <? super type>
  • Unbound <?>

Concurrency

  1. Fail-fast
  • immediately throws ConcurrentmodificationException, if any structural modification occur

2. Object

  • Every class in Java is directly or indirectly derived from the Object class.
  • toString() : provides String representation of an Object. The default toString() method for class Object returns a string consisting of class name+@+unsigned hexadecimal representation 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() notifyAll() are related to Concurrency.

Memory

  1. 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 Runtime.getRuntime().gc(). It’s not guaranteed that GC will run immediately as result of calling these method

2. 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 constructor performing deep copy.
  • Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.

3. 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.

Thank you for reading!

--

--