# Justin's Java Basics Learning Note
## Keywords
- static
- TO-READ : [When to make a method static in Java](https://javarevisited.blogspot.com/2013/07/when-to-make-method-static-in-java.html)
- transient
- **transient** is a variables modifier used in serialization. At the time of serialization, if we don’t want to save value of a particular variable in a file, then we use transient keyword. When JVM comes across transient keyword, it ignores original value of the variable and save default value of that variable data type. Ref : https://www.geeksforgeeks.org/transient-keyword-java/
- volatile
- implementation : The volatilfe force the thread to update the original variable for each variable. Ref : https://dzone.com/articles/java-volatile-keyword-0
- instanceof
- https://stackoverflow.com/questions/7526817/use-of-instance-of-in-java
- synchroized
- http://tutorials.jenkov.com/java-concurrency/synchronized.html
- const
- const vs final
> TO-READ : [Java Made Clear: Difference const vs final Keywords](https://way2java.com/java-introduction/java-made-clear-difference-between-const-and-final-keywords/)
## Boxing and Un-boxing
> TO-READ : https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
## Generics
> TO-READ : https://howtodoinjava.com/java/generics/complete-java-generics-tutorial/
>
## Inheritence and Composition
extend(abstract) vs implements(interface)
- TO-READ : https://www.javaworld.com/article/2076814/inheritance-versus-composition--which-one-should-you-choose-.html
- Choosing between composition and inheritance :
- So how do all these comparisons between composition and inheritance help you in your designs? Here are a few guidelines that reflect how I tend to select between composition and inheritance.
- Make sure **inheritance models the is-a relationship** My main guiding philosophy is that inheritance should be used only when a subclass is-a superclass. In the example above, an Apple likely is-a Fruit, so I would be inclined to use inheritance.
- An important question to ask yourself **when you think you have an is-a relationship is whether that is-a relationship will be constant throughout the lifetime of the application** and, with luck, the lifecycle of the code. For example, you might think that an Employee is-a Person, when really Employee represents a role that a Person plays part of the time. What if the person becomes unemployed? What if the person is both an Employee and a Supervisor? Such impermanent is-a relationships should usually be modelled with composition.
## String
- String "+" vs StringBuilder vs StringBuffer
- TO-READ : https://javarevisited.blogspot.com/2011/07/string-vs-stringbuffer-vs-stringbuilder.html
- String.valueOf vs Integer.toString
- https://stackoverflow.com/questions/27465731/string-valueof-vs-object-tostring
- `String.valueOf()` is more safe
## Integer
> TO-READ : [Java Integer Cache](https://javapapers.com/java/java-integer-cache/)
# Collections
- Basic
- Interface

- Implementations

- List
- ArrayList vs LinkedList
- Set
- Queue
- Map
- Compare
- Hashmap vs HashTable vs ConcurrentHashMap vs SynchronizedHashMap
- TO-READ :
- ConcurrentHashMap
- Reads can happen very fast while write is done with a lock.
- SynchronizedHashMap
- Every read/write operation needs to acquire lock.
- ArrayList vs LinkedList vs Vector
- [ArrayList vs. LinkedList vs. Vector](https://dzone.com/articles/arraylist-vs-linkedlist-vs)
- The difference of their performance is obvious. LinkedList is faster in add and remove, but slower in get. Based on the complexity table and testing results, we can figure out when to use ArrayList or LinkedList.
In brief, LinkedList should be preferred if:
- there are no large number of random access of element
- there are a large number of add/remove operations
- SynchronizedList vs Vector
- https://stackoverflow.com/questions/14932034/in-java-vector-and-collections-synchronizedlist-are-all-synchronized-whats-th
- sream :
- When to(or `NOT` to) use parallelStream
- Is multithreading necessary?
- [Think Twice Before Using Java 8 Parallel Streams](https://dzone.com/articles/think-twice-using-java-8)
## Enum
- [A Java enum switch/case statement example](https://alvinalexander.com/java/using-java-enum-switch-tutorial)
- [Enum Singleton Pattern](https://stackoverflow.com/questions/3930181/how-to-deal-with-singleton-along-with-serialization)
## Serialization
- what :
- Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
- After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
- [Why optional is not serializable?](https://stackoverflow.com/questions/24547673/why-java-util-optional-is-not-serializable-how-to-serialize-the-object-with-suc)
## Annotation
- How to define an annotation
```
public @interface TestAnnotation {
// logic
}
```
- `@Retention`
- RetentionPolicy.SOURCE
- RetentionPolicy.CLASS
- RetentionPolicy.RUNTIME
- `@Target`
- ElementType.ANNOTATION_TYPE
- ElementType.CONSTRUCTOR
- ElementType.FIELD
- ElementType.LOCAL_VARIABLE
- ElementType.METHOD
- ElementType.PACKAGE
- ElementType.PARAMETER
- ElementType.TYPE
- Common java annotation :
- @Deprecated
- @Override
- @SuppressWarnings
## Exceptions
- Checked vs unchecked
- http://www.javapractices.com/topic/TopicAction.do?Id=129
- `Unchecked exceptions` :
represent defects in the program (bugs) - often invalid arguments passed to a non-private method. To quote from The Java Programming Language, by Gosling, Arnold, and Holmes: "Unchecked runtime exceptions represent conditions that, generally speaking, **reflect errors in your program's logic and cannot be reasonably recovered from at run time.**"
- `Checked exceptions` : Checked exceptions:
represent invalid conditions in areas outside the immediate control of the program (**invalid user input, database problems, network outages, absent files**)
## Syntactic Sugar
- Switch support enum and string
- Generic
- Auto boxing and un-boxing
- Variable arguments
- https://www.programiz.com/java-programming/varargs
```
accessModifier methodName(datatype… arg) {
// method body
}
```
- Enum
- Inner class
- https://www.tutorialspoint.com/java/java_innerclasses.htm
- Lambda
- **try-with-resource** : https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
```
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
```
## POJOs
- POJO vs PO vs VO vs DTO vs JavaBean
- Plain Ordinary Java Object (POJO)
- Only attributes, getters and setters.
- Reference :
- [Java (PO, VO, TO, BO, DAO, POJO) interpretation](https://www.programering.com/a/MDM2kjNwATc.html)
- Persistent Object (PO)
- From [JPA ORM(Java Persistent API Object Relational Mapping)](https://www.tutorialspoint.com/jpa/jpa_architecture.htm)
- Hibernate : https://www.tutorialspoint.com/hibernate/hibernate_architecture.htm

- Can be mapped to a table in the database Java object. PO should not contain any operation of the database.
- View Object (VO)
- Value Object (VO)
- Data Transfer Object (DTO)
- JavaBean
## Libraries
- [A curated list of awesome frameworks, libraries and software for the Java programming language.](https://github.com/akullpp/awesome-java
)
### Common Java Libraries we use
- Lombok
- Jackson
- ObjectMapper
- Apache Commons
- Guava
- Cache
- Immutable : ImmutableMap, ImmutableList and ImmutableSortedMutiSet ... etc
- Gson
- SL4J
- Junit
- Mockito
## Java Multithread Programming
### Keywords
- Thread
- Runnable
- Callable
- ReentrantLock
- Semaphore
- Executors
### Compare
- Callable vs Runnable
- https://stackoverflow.com/questions/141284/the-difference-between-the-runnable-and-callable-interfaces-in-java
- The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.
### Thread Pool
- Different types of thread pool
- **Single Thread Executor** : A thread pool with only one thread. So all the submitted tasks will be executed sequentially. Method : Executors.newSingleThreadExecutor()
- **Cached Thread Pool** : A thread pool that creates as many threads it needs to execute the task in parrallel. The old available threads will be reused for the new tasks. If a thread is not used during 60 seconds, it will be terminated and removed from the pool. Method : Executors.newCachedThreadPool()
- **Fixed Thread Pool** : A thread pool with a fixed number of threads. If a thread is not available for the task, the task is put in queue waiting for an other task to ends. Method : Executors.newFixedThreadPool()
- **Scheduled Thread Pool** : A thread pool made to schedule future task. Method : Executors.newScheduledThreadPool()
- **Single Thread Scheduled Pool** : A thread pool with only one thread to schedule future task. Method : Executors.newSingleThreadScheduledExecutor()
- **submit() vs execute()**
- https://stackoverflow.com/questions/3929342/choose-between-executorservices-submit-and-executorservices-execute/35424481#35424481
- **execute**: Use it for fire and forget calls
- **submit**: Use it to inspect the result of method call and take appropriate action on Future objected returned by the call
### Thread Security
- Deadlock
- How to prevent
- https://www.javaworld.com/article/2075692/avoid-synchronization-deadlocks.html
- One of the best ways to **prevent the potential for deadlock is to avoid acquiring more than one lock at a time**, which is often practical. However, if that is not possible, you need a strategy that **ensures you acquire multiple locks in a consistent, defined order**.
## Volatile
- http://tutorials.jenkov.com/java-concurrency/volatile.html
- The Java volatile keyword is used to mark a Java variable as "being stored in main memory". More precisely that means, that **every read of a volatile variable will be read from the computer's main memory, and not from the CPU cache**, and that every write to a volatile variable will be written to main memory, and not just to the CPU cache.
### Synchronized
- https://www.tutorialspoint.com/java/java_thread_synchronization.htm
```
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
```
### ThreadLocal
- https://www.baeldung.com/java-threadlocal
- The TheadLocal construct allows us to store data that will be accessible only by a specific thread.
- **Do Not Use ThreadLocal with ExecutorService**
### Compare
- sleep vs wait
- TO-READ : https://howtodoinjava.com/java/multi-threading/sleep-vs-wait/
- sleep() is a method which is used to pause the process for few seconds or the time we want to.
- But in case of wait() method, thread goes in waiting state and it won’t come back automatically until we call the notify() or notifyAll().
- 3.1. Method called on
- wait() – Call on an object; current thread must synchronize on the lock object.
- sleep() – Call on a Thread; always currently executing thread.
- 3.2. Synchronized
- wait() – when synchronized multiple threads access same Object one by one.
- sleep() – when synchronized multiple threads wait for sleep over of sleeping thread.
- 3.3. Lock duration
- wait() – release the lock for other objects to have chance to execute.
- sleep() – keep lock for at least t times if timeout specified or somebody interrupt.
- 3.4. wake up condition
- wait() – until call notify(), notifyAll() from object
- sleep() – until at least time expire or call interrupt().
- 3.5. Usage
- sleep() – for time-synchronization
- wait() – for multi-thread-synchronization.
## JVM
### Java Memory Structure



[Understand How JVM Treat A Class File JVM Architecture](https://www.oodlestechnologies.com/blogs/Understand-How-JVM-Treat-A-Class-File-JVM-Architecture)

- Heap
- Stack
- Method
- Heap vs Stack
- https://stackify.com/java-heap-vs-stack/
### JVM parameters and performacne optimization
- [JVM performance optimization, Part 1: A JVM technology primer](https://www.javaworld.com/article/2078623/core-java/core-java-jvm-performance-optimization-part-1-a-jvm-technology-primer.html)
## How to deal with null in Java
https://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/