0% found this document useful (0 votes)
3 views26 pages

Java

The document provides an overview of various concepts in databases, middleware, security, Java programming, design patterns, algorithms, and exception handling. It covers topics such as RDBMS, JIT compilation, OOP principles, threading, JDBC, and design patterns like Singleton and Factory. Additionally, it discusses Java's class loading, cloning, and algorithms like quicksort and LCS, along with JDK, JRE, and JVM distinctions.

Uploaded by

Ayush Sharma
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views26 pages

Java

The document provides an overview of various concepts in databases, middleware, security, Java programming, design patterns, algorithms, and exception handling. It covers topics such as RDBMS, JIT compilation, OOP principles, threading, JDBC, and design patterns like Singleton and Factory. Additionally, it discusses Java's class loading, cloning, and algorithms like quicksort and LCS, along with JDK, JRE, and JVM distinctions.

Uploaded by

Ayush Sharma
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Databases

- RDBMS: MySQL, Oracle, PostGre, etc


DBMS: XML, Windows Registry, etc
RDBMS is DBMS with relational properties.

Middleware

Queue/Topic:
- Queue received by only one *receiver*
- Topic broadcasted to multiple *subscribers*

Proxy Servers:
- API Gateway: Dynamically update configuration via API/Web Interface. Acts as a reverse proxy
as well. Provides authentication, rate limiting.
eg. Zuul Proxy
- Reverse Proxy: Between Internet and App Servers. eg. nginx, apache, etc. primarily for load
balancing, caching.

Security:
- Client -> Auth Server -> Access Token -> Client -> Resource Server with Access token
- Access Token:
- JWT: [Link](subject: username).claims(claims: username?, exp. date?).sign(H256,
SECRET_KEY).build();
- How to extract user details from access token?

- Spring Boot Security:


@Configuration
@EnableWebSecurity
public class BasicConfiguration extends WebSecurityConfigurerAdapter...
{ override configure method and provide Auth roles -> endpoint access... }

- Microservices communication?
- Exception at 1 Microservice: propagation?

Java

I. JIT Compiler
The JIT compiler is enabled by default, and is activated when a Java method is called. The JIT
compiler compiles the bytecode of that method into native machine code, compiling it "just in
time" to run. When a method has been compiled, the JVM calls the compiled code of that
method directly instead of interpreting it.

To help the JIT compiler analyze the method, its bytecode are first reformulated in an internal
representation called trees, which resembles machine code more closely than bytecode.
Analysis and optimizations are then performed on the trees of the method. At the end, the trees
are translated into native code.
Inlining is the process by which the trees of smaller methods are merged, or "inlined", into the
trees of their callers. (Method call is evaluated)

C1, C2, Tiered Compiler

II. OOPS
- Encapsulation: protecting data using access modifiers: public private protected - data hiding
[For easily changing the Implementation for a setter/getter method later]

- Abstraction: Interfaces and Abstract classes


- Inheritance: Super/ Sub class
- Polymorphism: Overloading, Overriding

SOLID: (Bob Martin / [Link]


S - Single Responsibility Principle
O - Open for Extension/Closed for Modification
L - Liskov Subst.: An extended class shouldn't behave differently
I - Interf. Seg.: Clients shouldn't be forced to implement unnecessary methods (Functional
Interfaces should be the way to go, ideally)
D - Dependency Inversion (Read in link above)

III. Collections and Generics


Keep note

IV. Threads: Keep note


Producer-Consumer Problem:
Thread p = new Thread(new Producer());
Thread c = new Thread(new Consumer());
// In Producer(list), check if full and add value++
// Consumer(list) check if empty and remove value--
- without synchronized Consumer might check that list is empty and go to sleep; between check
and sleep, producer might add and wakeup an already awake Consumer (race condition).
Consumer continues and proceeds to sleep. wakeup signal was lost.
Solution: Use wait and notify in sync context.
If producer checks and finds it full, it should immediately call wait().

Solution:
1. Synchronized block: ensures atomic execution, as long as both threads are locked on the
same object (Consumer doesn't enter during (Producer's TOCTOU)
2. BlockingQueue: put() and take() implicitly check state of queue(empty/full)
- Pass a BlockingQueue object while creating Runnable object of Producer/Consumer class
- put() or take() in run method

V. JDBC
Connection conn = [Link](url, name, password)
[Link]()
[Link](sql)
CallableStatement cstmt = [Link](sql) : to execute stored procedure.

[Link]()
[Link](sql)
[Link](sql)
[Link](1,...) setString(...)
[Link]

VI. Variables
- Instance variables have initial default value (null or 0), local don't
- final variables don't ([Link]
A blank final instance variable must be definitely assigned at the end of every constructor of the
class in which it is declared; otherwise a compile-time error occurs
- for final variables, as long as value is assigned in constructor/init block, compiler does not
complain
- a final reference variable is immutable. Object it points to, may not be.
eg. final StringBuffer sb = new StringBuffer("a");
[Link]("b"); // works
sb = new ... // doesn't work
- static variables and their technical values (primitives or references) are stored in PermGen
space. Objects assigned to static references are stored in heap

VII. Design Patterns


1. Adapter Pattern:
- "adapting" or providing functionality in disguise.
- eg. Linkedlist DescendingIterator is an inner class that implements Iterator<>, returns
[Link]() when Iterator().next() is called

2. Singleton:
- early: new object is created at class level
- late: init if null, else return inited object (un-init static ref at field level)
- double checked locking/enum: thread safe
- private constructor
- private Object to return
- reflection : use enum to prevent instantiation
- cloning : override clone() method and throw CloneNotSupportedException

3. Factory Pattern:
- Multiple classes implement the same interface
- [Link]() returns object with return type interface
- eg. [Link]() returns Type Map<>

4. Observer Pattern:
- Subject holds a list of Observers
- Whenever an Observer is instantiated, common object of Subject class is passed through
constructor
- Constructor in each Observer adds itself to Subject's list of observers by calling add method of
Subject object passed
- whenever state of Subject is changed (using setter method), the method iterates through list of
Observers it holds and performs actions
- [Link]
- Behavioral Patterns: this, visitor, template, etc.

5. Bridge Pattern (S)


- Separation of interfaces, such that more subclassed abstraction provides different /more
specific implementation
- eg. StackFIFO class provides implementation for pop() method, where it's behavior is different
from normal StackArray class pop(). It pops in FIFO manner. Here only the pop() method is
overridden in FIFO to provide different implementation
- Similar to adapter. Differs in context. Bridge is used when additional implementation is
required, decided at time of designing. Adapter is used when different implementation is to be
provided depending upon runtime instance.
- [Link]

6. Composite (S)
- used when type of object is not known and casting is required.
- common interface is implemented by all object types. casting is avoided by calling interface
method
- eg. in a hierarchy of files. objects are of type Directory or File. Both implement interface I
- [Link]
VIII. Classes, Methods and String
Inner class:
- Static nested classes can access only static members of the outer class.
- A static class object can be created with the following statement:
[Link] nestedObject = new [Link]();
- inner classes are associated with the instance, we can’t have any static variables in them.
- InnerClass innerClass = [Link] InnerClass();
- Note that inner classes can access outer class private members and at the same time we can
hide inner class from outer world.

- Immutable class: class, data members final (not static), private constructor, no setter methods,
only getter methods

String is immutable. Stored in string pool. Password should be stored in char array since, you
can set it to blank once you are done with it with confidence that it will no longer be retained in
memory.

Class loading and initialization:


Class Loading: Eager/Lazy (Referenced/For initialization)
Class Init: new(), reelection, Static method/field is required

Only using new(), etc will initialize the class (static or not)
Init triggers initialization of static blocks of Parent then Child, followed by non static blocks of
both

[Link] triggers initialization of Only Parent static block, not non static

final static is compile time.


[Link]
?m=1

[Link]():
PrintStream out is set to null using nullPrintStream() method since:
1. System has to be the first to be loaded and initialized not PrintStream [out]. Initializing out to
a value would cause PrintStream to be initialized.
2. out can't be explicitly assigned to null
if it was set to null, the compiler would consider it as a constant, and would replace all the
references to [Link] in other classes with null (that's what inlining means), since out is final
static.
3. nullPrintStream uses an if condition with current time in millis > 0, to bypass inlining
4. later set with initializeSystemClass(), which uses JNI native code to bypass restriction of not
being able to re initialize value of final static reference var [Link]

String pool, intern:


- String literals are stored in String Constant Pool(SCP) when the class is loaded, usually in
permgen(JDK6) /heap(7+)
String s1 = new String("Hey"); // "Hey" is stored in SCP in Perm. Gen, s1 is stored in heap (2
objects are created)
String s2 = [Link](); // s2 points to SCP object
String s3 = [Link]("Hey"); // s3 points to SCP object
String s4 = "HeyHey"
s3 == s4; // prints true
(s2 = s1) vs (s2 = [Link]() ) : if s1 was created using "new", s2 won't point to heap, will point
to SCP object
CP is located in .class file for each type
- concat working: [Link](value, len + otherLen) returns buf[]
- concat(null) throws NPE, whereas "+" operator converts it to "null"

static keyword:
- Class loader initializes static var as part of class init (at runtime)
- static methods can access non static vars/methods only through instance. Hence, calling non
static method from static method requires object, but non static methods can call
- non static can access static, not vice versa w/o an object
- non static methods can access static via [Link]() or simply staticMethod(). same
with any non static target method

inheritance and static methods:


- Java static methods are inherited just like instance methods
class B extends A { ... }
[Link]() compiles even if it is defined only in class A.
- Static methods in interfaces are never inherited: Diamond Problem (Multiple inheritance)

inheritance and default methods:


interface A {
default void m() {
[Link]("hello from A");
}
}

interface B extends A {
default void m() {
[Link]("hello from B");
}
}
interface C extends A {}

class D implements B, C {}

the code

C c = new D();
c.m();

- will print hello from B. The static type of c is unimportant; it is an instance of D, whose most
specific version of m is inherited from B.
- default methods are virtual (dynamic binding)
- private, final and static members (methods and variables) use static binding

IX. Logger, enum


Logger log4j2= [Link](<<Optional: FQ Class name>>);

Enum:
- first line in enum must be declarations
- can be used in switch statements
enum Color { RED } is implicitly:
class Color
{
public static final Color RED = new Color();
}

X. Cloning, copy constructor


clone() in Object class provides a shallow copy (vars value are copied to new variable, object
references point to the same object)
- changes made in shallow copy to objects are reflected in original instance as well
- deep copy can be prepared by overriding clone method and creating new instances explicitly
- Copy constructor: A constructor in the target class that takes an instance of its own type as an
argument and copies variable values/create new objects for references..
- copy constructor doesn't work with Generics
- Advantages of copy: copy can be made to have a different representation from the original.
For example, you can copy a LinkedList into an ArrayList.
- Returns a shallow copy of this HashMap instance: the keys and values themselves are not
cloned
- Java Deep-Cloning library: apache license

XI. Algorithms
BST: O(log2 n)
After Iteration 1,
Length of array = n/(2^1)

After k divisions, the length of array becomes 1


(n/2^k) = 1 => n = 2^k
(log to the base 2) on both sides => log2 n = k log2 (2)
log2 n = k
([Link] : Start Iterations from 0
not 1)

Quick sort and Insertion Sort


Quick Sort: [Link]

quicksort (arr, low, high)


{
index = partitionAroundAPivot(arr, low, high);
quicksort(arr, low, arr[index-1]);
quicksort(arr, arr[index], high);
}

partition(arr, low, high) returns index of pivot after sorting such that elements <pivot are to the
left
recursive call to method(arr, low, pivot-1) and 2nd half
- start partition with i = low - 1; j = low and j < high
- in partition(), compare j with pivot and swap(i++)
- same arr reference is passed. hence print(arr) will be sorted

Insertion sort:
- start with j = 1, i = 0, hold key = a[j]
- if a[j] < a[i], move a[i+1] = a[i], j--
- keep swapping until not greater or j!=0

LCS: common substring:


- m x n matrix is updated with incremented count for common characters
- for each character of second string (vertical): Check each character of other string and update
the value (a) diagonally if it matches or (b) max(either previous)
- (a) since for current (vertical) character, upto the current length of the other string, number of
chars that were common is represented by the value
- (b) since eg. ABAC and ABDA, where ABAC is vertical. string checks will be (ABA & ABDA) and
(ABAC & ABD), while current check is for 'C' and 'A'.
- write another matrix at the same time that is updated with value count
- finally, traverse the matrix, check if both chars are same print, move diagonally. If chars are not
same, check which one has greater value and check that block
- [Link]

XII. Overriding
Exceptions
- If SuperClass does not declare an exception, then the SubClass can only declare unchecked
exceptions
- If SuperClass declares an exception, then the SubClass can only declare the child exceptions
of the exception declared by the SuperClass, but not any other exception.
- If SuperClass declares an exception, then the SubClass CAN declare Zero exceptions

XIII. JDK, JRE and JVM


- JDK:
- JRE:
- JVM: Class Loaders, JNI, etc.
- Bootstrap classes, etc.
- Development Tools: javac, java, RMI, jar, etc.

[Link]

XIV. Integer/Double is less than 0 (negative) or not:


- [Link](double d): returns -1.0, 0, 1.0
- [Link](int i): returns -1, 0, 1
- [Link]() impl: (i >> 31) | (-i >>> 31)

__________________

equals, hashcode, compareTo: Effective Java Book


Collections API: Keep note
Java 8 Streams/Lambda: Eff. Java, Oracle Training Notes
Java 9-11 features: Oracle Notes (to compile)
__________________

**** 2022 ****


XV. Spring Streams and RxJava (Reactive):
- [Link]

XVI. Java Compare and Sort


- [Link]

XVII. Regex:
(?:(?!lazy).)*

(?: # Match the following but do not capture it:


(?!lazy) # (first assert that it's not possible to match "lazy" here
. # then match any character
)* # end of group, zero or more repetitions.

[Link]

XVIII. Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?
[Link]

_______________

Edited:
March 9, 2020
May 13, 2021
May 23, 2021
June 9, 2021

July 3, 2022
Sep 30, 2022
Nov 24, 2022 (added String concat vs + NPE)

Threads

Threads: 9h
Instantiating, States:
- 3 ways:
1. MyThread extends Thread: since Thread class implements Runnable
2. ThreadRunnable implements Runnable, pass to new Thread(runnableObject): allows
multiple inheritance, preferred. Also, subclassing should be reserved for specialized versions of
more general superclasses.
3. Callable interface. call() instead of start. Cannot pass same as runnable. executorService =
[Link]()
- Future<String> future = [Link](callableObject)
- Callable call() method will return object of type String, which is stored into future object.
- [Link](), cancel() if not yet started, etc
- Set = Set Of Callables

- Now in the NEW state


- Call [Link]() to move to RUNNABLE state
- Thread is picked by JVM: RUNNING state
- synchronize part of code that shouldn't be interrupted by another thread locked on same object
- wait() called: WAITING state
sleep(): SLEEPING state
or BLOCKED for resource
The thread is NOT RUNNABLE while in above states.
- suspend(), stop(): deprecated. tells another Thread
- sleep(): throws InterruptedException. another thread has to call interrupt()
- if the thread calling wait() does not own the lock, it will throw an
IllegalMonitorStateException. Runtime exception. Doesn't have to be handled
- yield(): prevent inconsistencies in operating systems that are not preemptive

Thread/Object methods, State Transitions


- start(), run() methods are called on Thread Object
- sleep(), yield() methods are static, always called on current thread.
- SLEEP is a different state. it's not RUNNABLE. it moves to RUNNABLE after waking from
SLEEP/ when interrupted
- wait(): always in a synchronized context. called on monitor object. releases lock. should
always be in a loop
- sleep(): not necessarily in sync context. doesn't release lock, in a sync context.
- Also a wait (and notify) must happen in a block synchronized on the monitor object whereas
sleep does not.
- Thread may leave RUNNING state when:
- run() completes, wait() is called, lock not available or no reason (JVM).
- [Link](): Tells the current thread "B ko join kar". B will complete, then current thread will
continue

start() and run() method:


1. Runnable is passed:
- "target" object is instantiated with passed reference in constructor of Thread
- start() method calls start0() a native function, that starts a new Thread(), which calls run()
method of target object
2. Extend Thread:
- since myThread extends Thread, parent's start() is called which calls start0() native method.
Starts a new Thread, which calls overridden run() method. Since, myThread is an extension all
methods of parent are available

Synchronization:
- Ensures that no other thread locked on the SAME runnable/thread object can access until
current thread completes Synchronized code
- Thread threadA = new Thread(new ThreadRunnable())
Thread threadB = new Thread(new ThreadRunnable())
threadA and threadB represent different Runnable instances
Using "synchronized(this)" anywhere in target class would then have lock on different
instances. threadB would interrupt threadA
- Also, calling synchronized method with new instance, would not lock on same instance.
eg. new ThreadRunnable().methodTest(), where methodTest() is a method in ThreadRunnable
class, and is called from within run() method, is synchronized.
calling new ThreadRunnable().methodTest() each time won't provide sync., since the sync is on
"this", which refers to different instances in this case.

- synchronized method(): locks on "this"


- synchronized static method():
- lock on Class
- only 1 thread can access mutable data at a time
- different "new" objects will have separate/independent locks
- consider locking on "private" object instead of "this": since malicious code could block
[Link]
- Just because a lock is released doesn't mean any particular thread will get it.
- Every Object has a list of threads waiting. Thread waits till notify()/notifyAll() is called
- notifyAll() notifies ALL threads waiting on the Object. notify() will only notify 1 thread and stop

■ Only methods (or blocks) can be synchronized, not variables or classes.


■ Each object has just one lock.
■ Not all methods in a class need to be synchronized. A class can have both synchronized and
non-synchronized methods.
■ If two threads are about to execute a synchronized method in a class, and both threads are
using the same instance of the class to invoke the method, only one thread at a time will be able
to execute the method.
■ If a thread goes to sleep, it holds any locks it has—it doesn't release them.
■ A thread can acquire more than one lock.

synchronized static:
- Threads calling non-static synchronized methods in the same class will only block each other
if they're invoked using the same instance.
- static synchronized methods in the same class will always block each other—they all lock on
the same Class instance
- Two threads executing the same method at the same time will use different copies of the local
variables,
- a static synchronized method and a non-static synchronized method will not block each
other
- Access to static fields should be done from static synchronized methods. Access to
non-static fields should be done from non-static synchronized methods.
- volatile:
Read/write occur to main memory. Since 2 threads might update var in CPU cache and read old
value from main memory.
Guarantees this visibility. Values are read as updated.
Does not guarantee atomicity. eg. i++
Synchronized takes care of both

- Work stealing algorithm


A work item may also spawn new work items that can feasibly be executed in parallel with its
other work. These new items are initially put on the queue of the processor executing the work
item. When a processor runs out of work, it looks at the queues of other processors and "steals"
their work items.

- Double checked locking:


For singleton class/method:
class Singleton
private static var;
if(var == null) #1
synchronized(this)
// after #1 thread2 might have executed
if null
initialize
end if
end if
return var;
end class
- above double check is ideal to avoid synchronization for every call

Semaphore:
- Class in Java concurrent pkg
- used to control how many threads can access critical section
- Semaphore(int) is passed to Thread monitor object constructor
- [Link]() decrements, release() increments the value

______________
2021:
Concurrent Pkg
- ReentrantLock // no sync keyword
- [Link](), unlock()
- BlockingQueue Eg.: [Link]

______________
Edited:
- Feb 3 2020
- Jun 9 2021
Exception Handling & Serialization

Exception Handling: 2h
- A try clause by itself will result in a compiler error. Any catch clauses must immediately
follow the try block. no line in between
- can catch more than one type of exception in a single catch clause. (pipe operator, order
matters)
- You can throw the exception out of main() as well. This results in the Java Virtual Machine
(JVM) halting, and the stack trace will be printed to the output. Same if not handled at all
- The handlers for the most specific exceptions must always be placed above those for more
general exceptions.
- If one Exception class is not a subtype or supertype of the other, then the order in which the
catch clauses are placed doesn't matter.
- Handle or Declare: Each method must either handle all checked exceptions by supplying a
catch clause or list each unhandled checked exception as a thrown exception.
- RuntimeException, Error, and all of their subtypes are unchecked exceptions and unchecked
exceptions do not have to be specified or handled

- Rethrowing the Same Exception: All other catch clauses associated with the same try are
ignored. if a finally block exists, it runs, and the exception is thrown back to the calling method
(the next method down the call stack). If you throw a checked exception from a catch clause,
you must also declare that exception!
- StackOverflow error: method stack overflows. eg. recursive call to same method
- AssertionError IS thrown programmatically

- finally() is always invoked, unless [Link]() is called, usually used to close resources

- If try encounters an exception V and not caught, then:


__ finally executes and V is thrown/end abruptly
__ If the finally block completes abruptly for reason S, then the try statement completes
abruptly for reason S (and the throw of value V is discarded and forgotten)
- Exceptions encountered in catch/finally discard V

Serialization: 2.25h
- Steps:
- 1. Serialization I/O code in try/catch
- 2. ObjectOutputStream os = new ObjectOutputStream(fileOutputStream);
[Link](object);
[Link]();
- 3. ObjectInputStream ois = new ObjectInputStream(fis);
Cat object = (Cat) [Link]();
[Link]();
- [Link]: for composite objects that are not serializable
- transient variables/Object references will be skipped. the references will exist, but object state
won't be serialized. Object references marked transient will always be reset to null
- If composite class cannot be serialized, in class to be serialized:
- mark object reference transient
- private void writeObject(ObjectOutputStream os
{
try { [Link](); // normal ser.
[Link](anything); } }.
when [Link](object) is called readObject() method in target class is invoked.
([Link]

- threads, runtime, etc cannot be serialized, since they are OS specific

- When an instance of a serializable class is deserialized, the constructor does not run, and
instance variables are NOT given their initially assigned values!
- Think of constructors and instance variable assignments together as part of one complete
object initialization process (and in fact, they DO become one initialization method in the
bytecode).
- transient variable will be reset to 0.
transient Object reference will be reset to null
- If you are a serializable class, but your superclass is NOT serializable, then any instance
variables you INHERIT from that superclass will be reset to the values they were given during the
original construction of the object. This is because the nonserializable class constructor WILL
run!
- In a collection or an array, every element must be serializable!

- Static variables are NEVER saved as part of the object's state…

Page 469 in SCJP 6: when "new" is called


Collections and Generics

Collections
- If two objects are defined as equals(), hashcode() method must be overriden. Since, if two
objects are logically equivalent their hashcode must be same
- If hashcode is the same, object will be assigned to same bucket, differentiated by object's key
- If key as well is same,(i.e exactly same Object), then replace the value
- comparing hashcode is cheaper than checking equality
-[Link]
xrsuwu00

Equals and Hashcode:


equals() and hashcode() contract: if only hashcode or only equals is overriden?
- only equals: if elements are equal, must have the same hashcode. else equal elements may
be placed in different bucket. strange behavior of hashed collections
- only hashcode: lead it to same bucket. no way of telling if equal. may not override equal
objects in Map. for HashSet: uniqueness may not be guaranteed, although Objects with same
hashcode will be stored in the same bucket.

Calculating/Implementing hashCode and equals:


- hashCode should ideally use immutable fields (eg. id)
- equals and hashcode must comply such that 2 equal objects return the same hashCode, else
logically equal objects may end up in different buckets. In a Set, since a map is used and objects
are stored as keys. Duplicate entries/keys may exist. This is because, collision won't be
identified.
- 2 unequal object may produce same hashCode/ end up in same bucket. Ideally, they should
produce different hashCodes
- Ways to produce hashCodes:
- return a unique field eg. id
- return hash of multiple fields (fi[Link](), [Link](), etc)
- [Link](fields...)

1. Map<Key, Value> :
HashMap:
- Initial value is 16. hashbuckets are elements of array of Node<> which is linked list. (Tree
Java8)
- put() method returns old value for a key if exists, else null
- Key Object has hashcode() and equals() method
- i. If 2 Objects are equal, their hashcode() must be equal
ii. If 2 Objects are not equal, their hashcode() may or may not be equal
- If 2 keys have the same hashcode() value, hashMap uses linked Node to handle collision.
traverses Entry objects using [Link]()
- for an existing key value is overriden regardless of equality of value
- [Link]() returns Set<[Link]<K, V>>
- Sort by value:
- get a linked list from [Link]()
- [Link](): send a list and comparator object that compares two [Link]<>
values by [Link]().compareTo([Link]())
[Link]

TreeMap:
- TreeMap does not use hashCode() or equals() at all! It solely relies on the compareTo() method
and if your equals() does not comply with compareTo(), TreeMap does not care. it must
([Link]
[Link])

2. Queue
- poll(): return value/null,
remove(): return and remove/exception
- PriorityQueue keeps the lowest element as per Comparator or Comparable at head position

3. ArrayList<> initial value is 10


- Arraylist is backed by array[]
- Incremented by factor of 1.5 (JDK 7+) once limit is reached. all elements are copied to this new
array[]
- ArrayList remove methods remove using [Link] and returns (if byIndex)
- remove(Object)
- [Link](source, index, destArray, toIndex): removeRange(index, toIndex)

4. Fail-safe and Fail-fast iterators:


- Fail-fast throws ConcurrentModificationException immediately, if a thread is modifying it while
another is iterating. Fail-fast behavior of an iterator cannot be guaranteed, should be used only
to detect bugs.
- Fail-safe: works on copy of Collection object
- Iterator interface remove() would leave a space in the array, which is easy to jump over,
because we can immediately recognize that it isn't a member. On the other hand, add() would
put a new element in which wasn't there before. Therefore iterator has remove method only
- CopyOnWriteArrayList, ConcurrentHashMap classes are examples of fail-safe Iterator.
- CHM is designed to iterate one thread at a time.

5. Iterator itr = [Link]()


[Link](): While iterating (else ConcurrentModificationException)
[Link](), [Link]()
iterator() method is defined in concrete implementing classes like ArrayList. it returns new Itr(),
where Itr is a private static inner class that implements Iterator interface
- ListIterator allows bidirectional iteration, modification

6. Hashtable vs ConcurrentHashMap
Hashtable synchronizes at method level on the entire object.
CHM uses bucket-level locking, locks only for write operations. Iteration is one thread at a time.

7. ArrayList, Vector, LinkedList extends AbstractList/AbstractSequentialList >


AbstractCollection: These provide implementations for methods like toString(), subList(), etc
- Arraylist, etc extend AbstractList as well as implement List
- Lists can be heterogenous, unless generics is used. Generics checks type of objects added at
compile time

8. Set
- HashSet uses map internally:
- add(E e) -> return [Link](e, PRESENT) == null
- If returned PRESENT, add will return false, since put method returns existing value
- Set subset includes lower limit excludes upper limit object
- TreeSet is naturally ordered (alphabetically in case of Strings)
Set doesn't hold duplicates
Not necessarily ordered (insertion order), unless of course it's a LinkedSet
- Treeset uses map internally, uses equals as well as Comparable
- Adding element to sorted set: BST?
- Hashset POJO object by default uses reference address as hashcode, got equals

Treeset internals (how to insert element in sorted collection):


- Treeset implements red-black tree
- BST to sort a sorted collection after adding new element
Comparator compare method internal

9. LinkedList<>
- uses an inner private class called Node
- Node constructor: Node<E> previous, data, Node<E> next
- The class stores the first and last Node<E> reference
- for add (to last) : temp node reference points to current last node on heap.
current [Link] node will point to newNode
last reference will point to newNode

10. Implement stack using link list


class StackExample {
Node<T> head;

push(T val) {
Node<T> newNode = new Node<T>();
[Link] = val;
[Link] = head; // newNode next will point to current head (head could be null if empty)
head = newNode; // update current head
}

T pop() {
if (head != null)
tempValue = [Link];
head = [Link]; // head ref var is now pointing to where [Link] was pointing
return tempValue;
}
}

11. Double Brace Initialization:


- First Brace: Creating an anonymous inner class which extends HashSet
- Second Brace: Providing an instance initialization block which invokes the add method and
adds the country name to the HashSet

Generics:
- Use T instead of ? when you need to relate parameters/return type
- ? makes code more readable
- T: Any type
?: Wildcard
- ? extends/super Type : Type bounded
Differences: (T can be used in scope, only extends, allows multiple bounds)
- T can be used elsewhere, ? cannot
- ? can have both lower and upper bounds, T can only have upper bounds (T extends Something)
- T can have multiple bounding classes(T extends Comparable<T> & Cloneable<T>)
[Link]

- Child interface of Iterable, Iterable defines Iterable iterator(). Implementation classes


implement the method using Iterator interface
- If equals() is overriden hashcode() should be overriden as well. Since if two objects are equal
their hashcode must
- TreeSet cannot contain heterogenous objects/null (cannot null: JDK7)
- public E remove() { return EObject; } //perfectly legal

- PECS Rule:
[Link]

if method only reads a list of Parent objects, List<? extends Parent> should be used as the
method param. This allows us to pass both List<Child> and List<Parent> to the method

vice versa for method that writes (? super Child)

______________
Last Edited:
- March 11, 2020
- June 11, 2021 (Double Brace Init)
- March 10, 2023 (PECS Rule)

Java 7/8

Java 7:
1. Diamond “<>” Operator
2. Strings in switch Statement
3. Multi-catch similar exceptions, More precise exception rethrow
4. Automatic Resource Closing
5. Underscore in Numerical Literals
6. Binary Literals with Prefix “0b”
7. Fork-Join rethrow

3. Exception (Exception1 | Exception2 e)


- follows hierarchy, exception if Exception1, Exception2 are not disjoint.
4. try (FileInputStream fis = new FileInputStream(file)) will auto-close fis, without writing
explicitly in finally(), if resource impl AutoCloseable
7. Fork-Join framework is an implementation of the ExecutorService interface
- uses work-stealing algorithm in multi-core systems
(Refer Note: Threads)

______________________________________

Java 8:
1. Lambda Expressions
2. Functional Interfaces
3. Method References
4. Interface Default and Static Methods
5. Streams API
6. Optional
7. Date/Time New API
8. CompletableFuture<>
9. Type Inference

1. Anon function: (arg1, arg2, ...) -> { some body; }


2. SomeInterface<T> si = () -> { methodImplementation... };

1. Lambda Expressions:
i. With Lambda Expression:
[Link](rosterAsArray,
(Person a, Person b) -> {
return [Link]().compareTo([Link]());
}
);

2. Functional Interfaces/ Lambda Expression If method is defined:


[Link](rosterAsArray,
(a, b) -> [Link](a, b)
);

new Thread( ()-> {


[Link]("New thread");
} ).start();

- () -> { return... ; } : Expression Returns Object of type Comparator


- This is also an eg. of functional interface, since Comparator has only one method
- default and static methods do not break the functional interface contract and may be declared

3. Method References:
[Link](rosterAsArray, Person::compareByAge);

- 2 & 3 inherit Type "Person" from Comparator<T> compareTo(Person, Person)

- Types of Method References:


. Reference to a static method: ContainingClass::staticMethodName
. Reference to an instance method of a particular object:
containingObject::instanceMethodName

. Reference to an instance method of an arbitrary object of a particular type


ContainingType::methodName

. Reference to a constructor
ClassName::new

4. Interface Default and Static methods:


- Syntax: default Type methodName()
- default and static methods can have implementation in interface body

5. Streams API:
- [Link]().map(str -> [Link]()).forEach([Link]::println);
- [Link]()
.filter(t -> [Link]() == [Link])
.sorted(comparing(Transaction::getValue).reversed())
.map(Transaction::getId)
.collect(toList()); [Link]

6. Optional
Optional<String> op = [Link](str[2]);
[Link]() returns true if str[2] is not null
- Optional<Address> op = [Link]();
[Link]([Link]::println);
- [Link](), [Link]()

7. Date/Time New API


- LocalDate date = [Link]()
- from = [Link]( 2014, [Link], 16, 0, 0, 0 );
to = [Link]( 2015, [Link], 16, 23, 59, 59 );

final Duration duration = [Link]( from, to );

8. CompletableFuture<>:
- There's a lot, trust me
- It's better than Future<>:
runAsync(Runnable..) : executes in a new Thread
supplyAsync(Runnable..) : runs and returns value from new Thread
complete(): manually complete
perform further action on a Future’s result without blocking using a callback function

9. Type Inference: In Lambda Expressions:


- SomeInterface<Integer,Integer,Integer> si = (number1, number2) -> { return number1 +
number2;};
- skipped "Integer" before number1/ number2

[Link]

___________________

Edited:
March 11, 2020
May 23, 2021

Spring, Hibernate

1. RequestMapping(value = "/something", method = [Link])


- at class level: prefix to all requests
- at method level: specific (appends to class level mapping): GET/POST is only defined for
method-level

2. @RequestBody: maps json/xml input to object in method(@RequestBody Object obj)


- JSON array object to List/array?

3. @PathVariable: maps /somePath/{id} to method(@PathVariable("id") Long id)

4. @ResponseBody: Maps get method output from Object to JSON

5. @RequestParam: maps /somePath/?param="1" to method(@RequestParam("param") String


value)
6. Controllers, servlet xmls:
- [Link]: Dispatcher Servlet. beans definition, InternalViewResolver
- by default servlet name = dispatcher servlet file name
- contextConfig location is alternative way to name servlet file (along with
ContextLoaderListener
- <servlet>, <context-params>... describe custom file locations for servlet files here...</>,
<listener>ContextLoaderListener</>
- OR <servlet>sname, servClass, initparams: Paramname, paramvalue</servlet>

AbstractController:
- override handleRequestInternal method

ParameterizableViewController:
- getViewName() method sets view name via xml file (DI)
- return MAV(getViewName(), map)

UrlFilenameViewController:
- in dispatcher-servlet: UrlFilenameViewController's purpose is:
Transforms the virtual path of a URL into a view name and returns that view
eg. <bean name = "hello" class="UrlFileNameViewController">
<bean class = "SimpleUrlHandlerMapping"><property
name=mappings><value>/**/*.html</value></>
.. in web xml servlet url-pattern is "*.html"

MultiActionController:
- myController extends MAC
- actionName = controller method names
- do not override handleRequest and handleRequestInternal. handleRequestInternal redirects to
resp. methods
- SimpleURLHandlerMapping props name=mappings > <property
key=[Link]>Controller bean id</>

BaseCommandController
- maps from html:form using setter methods
[Link]

7. @RequestMapping("/path", params=...)
Overloading with params is possible

8. Spring Data uses "findBy..." to map method name to sql

9. Autowiring modes:
eg. <bean id =... autowire = "byType"> OR @Component(...)
- byType : default
- if multiple beans exist with the same type, specify @Qualifier(name)
else - throws error

byName: Spring looks for property name in bean definitions


eg. dont have to provide:
<property name = "spellChecker" ref = "spellChecker" />
in list of property for bean.
Spring looks for another bean with that property name that would have required "ref"

byType: Spring looks for a bean with the type expected by property or constructor arg(Employee
e: "Employee" is the type, "e" is the name)

constructor: a bean with same type in CONSTRUCTOR args is searched for

autodetect: by constructor OR byType


If more than one such beans exists, a fatal exception is thrown

@Primary annotation if autowired by type and >1 bean with same type
- @Primary only makes sense when we enable the component scan
- @Configuration
@ComponentScan(basePackages="[Link]")
public class Config { ... }

10. Annotation @Configuration vs XML


@Configuration: tells spring that this is the configuration file
@ComponentScan: In configuration file: Can list @ComponentScan for classes to be scanned
using @ComponentScan(value="[Link]")
([Link]
6tLT&index=4)

@Bean
public LocalSessionFactoryBean getSessionFactory()
else in XML:

<bean value="...LocalSessionFactoryBean">
<property name = "sessionFactory" >

public HibernateTransactionManager getTransactionManager()

in dao class: [Link]()


[Link]() / openSession()

You might also like