Java
basic demo & projects
- Java utils : Useful java util scripts
- Design Pattern : Design Pattern examples
- utility_Java : legacy java project
- Spring play ground : backend projects built with spring boot framework
- JVM faq : JVM cheatsheet
- RX Java : Reactive programming with Java
- Scraping service
- webFluxPoc - Spring Web flux POC
- Grpc Demo :
grpc
request, response demo - Guice Demo :
Guice
injection framework demo - AOP Demo: AOP(Aspect Oriented Programming intro)
Java Hello World
- JavaHelloWorld : basic1
-
Data types
- Primitive Data Types
- Int, String, Float, boolean, char....
- Reference types (Non-Primitive Data Types)
- user defined. e.g. :
class myClass{ int id; Double age; } myClass m1 = new myClass;
- ref1
- ref2
- String
- String basic method demo
- String <--> other class/dtype transform demo
- String VS StringBuffer VS StringBuilder
- Primitive Data Types
-
Basics Data Types VS Wrapper
- Wrapper can "encapsulate" basic data type -> make them has
object
properties (for OOP) - so can use object method, such as toString, equals, hashcode...
- WrapperDemo1
- WrapperDemo2
- Need to pickup
- Basic type <--> Wrapper <--> String
// basic type, wrapper -> String class float f1 = 12.3f; String str2 = String.valueOf(f1); Double d1 = new Double(12.34); String str3 = String.valueOf(d1); // String class -> basic type, wrapper int num2 = Integer.parseInt(str1); String str2 = "true"; Boolean b1 = Boolean.parseBoolean(str2); // wrapper -> basic type Integer in1 = new Integer(12); int in1_ = in1.intValue();
- "autoboxing", "unboxing"
// autoboxing int num = 10; Integer in1 = num; // unboxing int in3 = in1;
- Wrapper can "encapsulate" basic data type -> make them has
-
Basic operator
-
Array
- Array1D
- Array2D
- ArrayClassDemo
- Array in memory (java)
- every valuable in the method is "local" valuable
- "local" valuable will be put into the "Stack"
- Any object from "new" will be put into the "Heap"
-
Collection
- Collection Demo1
- Collection Demo2
- Collection Demo3 : collection <--> array
- Iterator Demo1
- foreach Demo1
- List
- List Demo1
- Iterator methods : foreach, Iterator
- Set
- Set Demo1
- Set, HashSet : "comparision" method : TreeSet : hashCode(), equals()
- LinkedHashSet
- TreeSet
- TreeSet Demo1
- "comparision" method : TreeSet : compareTo(), compare()
-
Map
-
TreeMap
-
Properties
-
Collections
: Collection tool- NOTE :
Collections
is NOT a data structure, but a tool class for operating data structures (e.g. Set, List, Map..) under collection - Collections Demo1
- NOTE :
-
Class
-
Methods
-
Switch
-
Value Reference/Assignment:
- Assignment
- Value Assignment1
- Value Assignment2
- implemented Ordering (1->2->3->4, meaning : 4) will be the final value)
-
- default initial values
-
- explicit initial values
-
- assigne values via constructor
-
- getter, setter. e.g. "class.method", "class.attr"
-
- Transfer
- valueTransfer1
- valueTransfer2 : plz refer this video
- valueTransfer3
- Concepts
- Basic data type : assigned value is the storage "actual value"
- Reference data type : assigned value is the storage "address value" (e.g. : 0X111, 0XABC)
- Assignment
-
Recursion
-
Import
-
Others
- GetArgsFromCli
- System getProperties Demo
- BigInteger BigDecimal Demo
- Enumeration - Enumeration (枚舉類) demo
- Annotation - Annotation (註解) demo
-
- Array1D:
-
JavaHelloWorld : basic2 : OOP/class
-
Java class and its class members:
- field
- method
- constructor
- code
- inner class
-
OOP features:
- Encapsulation
- Inheritance
- Polymorphism
-
Other key words
- this, super, static, final, abstract, interface, package
-
Steps:
- step 1: create class, design elements in class
- step 2: create class instance
- step 3: call the method, attr... inside class via
class.attr
,class.method
-
java : "everything is an object"
- we encapsulate functionality, structure ... into the class, and use them via instantiate the class.
Frontend Backend DB -------- -------- -------- pom --> Class object --> table (HTML) <-- (Java) <-- (Mysql, Postgre...) (CSS) (JS)
-
Anonymous Object
-
Overloading
- In same class, if
more than one methods are with same name, but WITH DIFFERENT PRRAMETER NUMBERS OR DIFFERENT PRRAMETER TYPE
- Overloading1
- Overloading2
- In same class, if
-
Constructor
- Intro :
- create class instance (*** here the "Person_1" is the DEFAULT CONSTRUCTOR; rather than class)
- (if there no given constructor, java will have a default one)
- create class instance = new + "constructor"
- Use case :
- create class instance
Initialize the instance attr
- Constructor1
- Constructor2
- Constructor3
- ConstructorDemo1
- Intro :
-
Encapsulation
- Encapsulation1
- In short :
- hide the things need to hide : users don't need to know how does the library/Class... do the implementation
- export the things need to export : users only need to know the how/where (e.g. :
API
) to use the library/Class.
- pros : make the code extenable, scalable, easy to maintain
-
JavaBean
- CustomerBean
- A java class that has below properties
-
- the class is a
public
class
- the class is a
-
- with a
no argument
public
constructor
- with a
-
- has corresponding getter, setter methods
-
-
This
-
this
can be used inattr
,class
,method
,constructor
-
this
onattr
,method
- this can be referred as "current class"
- in class, method, we can use "this.method" for calling other method in same class
- pattern :
this.attr
,this.method
,this.constructor
....
-
- this call
constructor
- in the class's constructor, we use "this(var) or this() or ..." calling the other constructor in the same class
- CAN'T call itself (constructor) (via this())
- calling constructor via
this()
need to be in the1st line
of code - can only use
1
this()
inside a constructor - if constructor's variable is as same as class's variable => we MUST use
this.var
explicitly
- this call
- thisDemo1
- thisDemo2
- thisDemo3
- thisDemo4
- thisDemo5
-
-
Getter & Setter
-
Extends
- Extends_demo1
- Extends_demo2
- the "children" class can
reuse
,overwrite
theattr/method
that their "parent" class already defined - general form :
class A extends B{}
- A : children class (subclass)
- B : parent class (superclass)
- Once A extends from B, A will get all structure, attr, method from B
- Note : private method CAN'T be called (it is received, but can't be called due to the
encapsulation
) in subclass (child class) - Subclass (child class)
CAN STILL define its own method, attr ...
after extending from superclass (parent class) - One superclass can have
multiple
subclass - A subclass can only have
ONE
superclass - superclass - subclass is a
relative
concept - It's OK to have "indirect" extends. e.g. :
A extends B, B extends C ....
- If there a class that we don't explicitly define its superclass (extends), then this class extends from
java.lang.Object
class by default - All classes in java (except java.lang.Object) are
direct/indirect
subclass ofjava.lang.Object
-
Overwrite
- Overwrite_demo1
- Overwrite_demo2
subclass
can overwrite the same method (same method name, same param) that itssuperclass
has- Note : For overwrited methods, it's needed to have the same method name, and the same params as the one in superclass (method name + params ) (for overwrite)
- only
non-static
method can be overwritten - access_modifiers
- method in subclass can have "bigger"
access_modifiers
than its superclass (access_modifiers : private, public, ...) private
method in superclassCAN NOT
be overwritten
- method in subclass can have "bigger"
- return_value_type
- if return_value_type is
void
in superclass -> it's needed to bevoid
in subclass as well - if return_value_type is
A type
in superclass -> the return_value_type in subclass can be "A type" orany subclass of A type
- if return_value_type is
basic data type
(e.g. Int, String, float...) in superclass -> the return_value_type need the be the same basic data type as its superclass
- if return_value_type is
- Exception_type
- subclass' Exception_type must be
smaller or equal
than the one in superclass
- subclass' Exception_type must be
// pattern @override // @override is just a comment, not necessary actually access_modifiers return_value_type method_name(parames){ // java code } // pattern2 @override access_modifiers return_value_type method_name throws Exception_type (parames){ // java code }
-
Controlling Access
- Super
- Super_1
- Super_2
- Super_3
- Instance_1
super
can be recognized as "superclass relative"- super can be called on : attr, method, constructor
- using
- we can call method in superclass explicitly via super.method_name from subclass
- If method name are same in superclass and subclass -> we need to call method in superclass (current class) explicitly via
super.method
- calling subclass's (current class) method :
this.method
- super call constructor
- we can use superclass' constructor in subclass via "super constructor"
- "super constructor" need to be declared in 1ST LINE of subclass constructor
- in subclass, we can only chosse either "this constructor" or "super constructor" (choose one of them !)
- if we don't declare any "this constructor" or "super constructor".. -> it will use "super constructor" (super(), no argument) by default
- Polymorphism (
Upcasting
)- polymorphism_1
- polymorphism_2
- polymorphism_3
- polymorphism_4
- polymorphism_5
- polymorphism_6
- call superclass and point to subclass' instance
- Polymorphism is actually
Upcasting
- Polymorphism NOT working in
attr
(still use its superclass' attr) - pattern :
superclass p1 = new subclass();
- (following above) p1 will be the superclass class type, so it CAN'T use the method that only exist in subclass
- During compile
- => can only call methods defined in superclass
- During runtime
- => will run the methods overridden in subclass
- summary :
- => Compile : check left (<-)
- => Running : check right (->)
- use requirements:
- there is extends in class (superclass, subclass)
- method override is necessary
Downcasting
- Downcasting_1
- Downcasting_2
- Upcasting ref
- pattern :
// MUST do upperCasting first (?) superclass p1 = new subclass(); // then do downcasting subclass x1 = (subclass) p1;
- Upcasting VS DownCasting
- Superclass ---DownCasting---> Subclass
- Superclass <---Upcasting--- Subclass
- Summary:
Uppercasting
: make subclass to superclass typeDowncasting
: make superclass to subclass type- In dev, we use Uppercasting >> than Downcasting
-
Instanceof
- instanceof_1 - instanceof demo
a instanceof A
: check if a is instance of A, if yes, return True, else False- using case :
-> to prevent the "ClassCastException" exception, we use instanceof before we do DownCasting. (if return true, then do
DownCasting
, else do nothing)
-
java.lang.Object
- objectDemo1
- objectDemo2
- java.lang.Object basics, properties
- garbage collect (GC) intro
-
Equals
VS==
- EqualsDemo1
- EqualsDemo2
- EqualsDemo3
- EqualsDemo4
==
- ==, an operator
- For comparing
BASIC data type
- compare
CONTENT (attr: such as value..)
- If compare "basic data type"
- type don't need to be the same, ONLY compare their "actual value" in memory
- If compare "REFERENCE data type"
- will compare if their address in memory are the SAME
- e.g. if they are belong to the same instance
Equals
- Equals is a method, NOT operator
- For comparing
Reference data type
- compare
address in memory
- For some types (class) such as String, Date, File
- -> They've overridden the equals method
- -> SO compare if "content" (attr: such as value..) are the SAME; but NOT address
- In general cases, we want equals to compare "content" rather than address
- -> so we need to OVERWRITE the equals method
-
toString()
-
For loop
-
-
JavaHelloWorld : basic3
- Static demo
-
Can be used in
attribution
,method
,code block
,inner class
-
Static attribution
- with
static
: static attr -> every instance use THE SAME attr -> when modify attr in one instance, will modify others as well - Not with static : non-static attr (instance attr) -> every instance has its own attr -> when modify attr in one instance, will NOT accect others
static attr | non static attr class yes | no (can class call attr ?) instance yes | yes (can instance call attr ?)
- with
-
Static method
- lives in method's "static area"
static method
is loaded whenclass
is loadedstatic method
CAN ONLY callstatic method
orstatic attr
non static method
CAN call both :static/non-static method
andstatic/non-static attr
this
,super
are NOT allowed in static method
static method | non static method class yes | no (can class call method ?) instance yes | yes (can instance call method ?)
-
When to use
static attr
?- attr can be used by multitple classes, and they are unchanged from class to class
-
When to use
static method
?- method which use static attr
- constant in class (as attr) are usually declared as
static
- methods in util class
- (can use directly, no need to instantiate class)
- e.g. Math, Array, Collections
-
-
Design pattern :
Singleton
-
Can only
create ONE class instance
-> reduce system loading -
Only allow some classes be existing in some specific class instances -> can save resources
- ref1
- ref2
- ref-scala
- SingletonDemo1
- SingletonDemo2 : Singleton - Eager initialization
- SingletonDemo3 : Singleton - Lazy initialization
- SingletonDemo4
- SingletonDemo5
- LazyInitSynchronized1 : solve Lazy initialization's thread safety with synchronized method
# Steps 1. make constructor private 2. make object inside class 3. export a public static method 4. implement the code
-
Lazy initialization VS Eager initialization
- Lazy initialization :
- pros : delay instance create (load fast)
- cons : thread un-safety --> need to use "multi-thread"
- Eager initialization:
- pros : thread safety (data, process in different threads
NOT
affect each other) - cons : takes time to load
- pros : thread safety (data, process in different threads
```java // https://www.youtube.com/watch?v=b-UAaq-G4uI&list=PLmOn9nNkQxJEqCNXBu5ozT_26xwvUbHyE&index=91 // Method 1) : 餓漢式 (Eager Singleton) // pros : Thread safety // cons : could create a class, but not uses it -> resource wasting class Single{ public Single() {}; // make constructor private private static Single s = new Single(); public static Single getInstance(){ return s; } } // Method 2) : 懶漢式 (Singleton) // pros : no resource wasting, only make the instance when need it // cons : Thread safety concern // https://www.baeldung.com/guice class Single2{ private Single2(){} private static Single2 s = null; public static Single2 getInstance(){ if (s == null){ s = new Single2(); } return s; } } // Method 3) : static internal method // optimize with above method 1), and 2) // pros : 1. no resource wasting, only make the instance when need it // pros : 2. Thread safety (no interruption when running) class Singleton{ private Singleton(){}; private static class SingltonInstance{ // make it private private static final Singleton INSTANCE = new Singleton(); } // export below static method to public public static Singleton getInstance(){ return SingltonInstance.INSTANCE; } }
- Lazy initialization :
-
-
Design pattern :
Template
- TemplateDemo1
- TemplateDemo2
- Common use cases:
- DB op
- Junit for unit test
- Java Web (e.g. spring MVC) : Servlet's doGet/do/Post method
- JDBC (spring)
-
Design pattern :
Proxy
- ProxyDemo1
- ProxyDemo2
- Offers an agent (proxy) that help access control on the specific class
- -> So users can access the
agent
class only rather than "proxied" class
- -> So users can access the
- using case:
- safety -> prevent actual class to be visited directly
- remote proxy -> RMI
- delay loading -> load the proxy class first, if needed, load the actual class
-
Design pattern :
Factory
- Simple Factory
- Factory Method
- Abstract Factory
- diff between Abstract Factory VS Factory Method -> complexity when create class
-
Final
- Can decorate : class, method, attr
- Final class
- CAN'T BE EXTENDED (no sub class)
- example : String, System, StringBuffer
- Final method
- CAN'T BE OVERRIDDEN (no overwrite method)
- example : getClass() method in Object class
- FinalDemo1
-
Code block
- purpose : for class, object initializing
- static code block
- *** Executed when class is loaded (since it's static)
- will only run ONCE
- init class attr, inform
- non-static code block
- *** Executed when class is instantiated
- *** can init class attr when instantiate the class
- Block_demo1
- Block_demo2
-
Abstract
- AbstractDemo1
- AbstractDemo2
- AbstractDemo3
- AbstractDemo4
- Can decorate
- class
- method
- abstract class
- CAN NOT BE instantiated
- STILL NEED CONSTRUCTOR (used in sub class)
- in development, we always offer sub class that can instantiate via above
- abstract method
- ONLY has method declare, has NO code body (method implementation)
- inference : if a class has abstract method -> this class must be an ABSTRACT CLASS
- Abstract class can has NO abstract method
- if sub class overwrites all abstract methods in super class -> sub class CAN instantiate
- if sub class NOT overwrites all abstract methods in super class -> sub class CAN NOT instantiate, this sub class is also an abstract class
-
Interface
- interfaceDemo1
- interfaceDemo2
- interfaceDemo3
- interfaceDemo4
- interfaceDemo5
- interfaceDemo6
- use keyword "interface"
- in java, interface, and class are the structure in the same level
- how to define interface ? elements inside interface ?
- JDK 7 and before
- -> can ONLY use global constant and abstract method
- -> global constant : public static final (public static final can be omitted)
- -> abstract method : public abstract (public abstract can be omitted)
- JDK 8 and after
- -> can HAVE global constant, abstract method, static method, default method
- JDK 7 and before
- CAN NOT define constructor in interface
- interface CAN NOT be instantiated
- in java, we usually use CLASS to "implement" interface (not extend)
- -> if class implements all abstract methods in interface -> this class can be instantiated
- -> if class NOT implement all abstract methods in interface -> this class CAN NOT be instantiated
-
Inner Class
- Static demo
-
JavaHelloWorld : basic4
- Unit Tests
- Exception
- ExceptionDemo1
- ExceptionDemo2
- ExceptionDemo3
- ExceptionDemo4
- ExceptionDemo5
- ExceptionDemo6
- ExceptionDemo7
- ExceptionDemo8
- ExceptionDemo9
- "throw" - "get" model
throw
- in
runtime
- When program runs, once there is an exception
- -> will generate an exception obj at the running code
- throw can from
- -> system auto generated
- -> set up by developer
- in
get
- method that deal with exception
- two types
-
- try-catch-finally
compile
-
- throws
-
try-catch-finally
- Know the exception cases, can handle them in cases
- throws +
exception type
- Have unhandled exception, so the program will throw the exception to
upper
layer anyway. If upper layer still CAN'T solve it, will pass to upper layer, and ... (repeat it till meet highest layer)
- Have unhandled exception, so the program will throw the exception to
- There are only 2 ways deal with exception:
try-catch-exception
- -> Really deal with the exception on place
throws
- -> NOT really deal with the exception,
- -> only "throws" the exception to the upper layer.
- (upper layer still need to deal with such exception)
-
JavaHelloWorld : Advanced
-
Program VS Process (進程) VS Thread (線程)
- Program : collection of code for purpose, a static instance
- Process :
running process
of the program, ora running program
. is a dynamic process. has its cycle : launch - exist - terminate- examples
- running spotify
- running whatsapp
- Program is
static
; while process isdynamic
- Process as
resource allocation
unit, will allocate threads to different memory spaces
- examples
- Thread : A process has
multiple
thread. Each thread is an execution unit inside the program- if one process can run multiple threads
in parallell
-> We say it's amutiple threading
program - thread as an allocation & execution unit, each thread has its independent running thread and counter (pc)
- Multiple threads in the same process CAN USE
same storage unit / memory space ..
-> they allocate instance from the sameheap
-> but such memory sharing mechanisms may causethready safety
concerns.
- if one process can run multiple threads
parallel (並行) VS Concurrency (並發)
- Parallelism : multiple CPUs run different tasks. e.g. multiple people do different stuffs
- Concurrency : One CPU does different tasks (jump between tasks). e.g. one person does different stuffs
- https://github.com/yennanliu/CS_basics/blob/master/doc/faq/java/java_multi_thread.md
-
Process
-
Thread
-
A
thread
is a thread of execution in a program. The JVM allows an application to have multiple threads of execution running concurrently. -
Thread create and use
-
Thread life cycle
-
Thread sync
-
Thread communication
-
Thread create and use (JDK 5.0)
-
ThreadDemo4 : common thread methods demo
-
ThreadDemo6 : Callable interface (new in JDK 5.0)
- RunnableDemo1 : Runnable create multi thread demo
-
Thread Safety
- ThreadSafety1
- BoxOfficeThread1.java : thread (Thread) safety ("Synchronized code block")
- BoxOfficeThread2.java : thread (Thread) safety ("Synchronized method")
- BoxOfficeRunnable1.java : thread (Runnable) safety ("Synchronized code block")
- BoxOfficeRunnable2.java : thread (Runnable) safety ("Synchronized method")
- explanation
- ThreadSafety2
- ThreadSafety2 : thread safety via "lock"
- ThreadSafety3
- ThreadSafety3 : thread safety example : bank account (synchronized method)
- ThreadSafety1
-
ThreadCommunication
- ThreadCommunication1 : Thread communication methods demo (wait(), notify(), notifyAll())
- ThreadCommunication2 : Thread communication demo : producer, consumer
- Thread Communication methods:
-
- wait():
- once run this method, the thread will be in
blocked
status and RELEASE Synchronized monitor (lock)
-
- notify():
- once run this method, the thread will be "WAKED UP", if there are multiple threads, the first priority thread will be waked up
-
- notifyAll():
- once run this method, ALL of the OTHER threads will be "WAKED UP"
-
-
Thread Dead Lock
- DeadLock1 : Dead Lock demo 1
-
Thread Pool
-
4 ways create multi thread
-
Method 1) : Inherit
Thread
class- Thread class is implemented from Runnable interface actually
// java public class Thread implements Runnable
-
Method 2) : Implement
Runnable
interface- we prefer Implement Runnable in general
- reason 1) without single class inheritance limitation (Runnable is a interface)
- reason 2) the attr/val .. are shared by multi thread by default (because the implementation way)
// java MyWindow my_window = new MyWindow(); Thread t1 = new Thread(my_window); Thread t2 = new Thread(my_window); Thread t3 = new Thread(my_window);
- we prefer Implement Runnable in general
-
Note : We need to overwroide run() method in both 2 methods
-
Method 3) : Callable + Future
-
Method 4) : Thread pool
-
-
Thread Cycle
-
Case study
- box office
part 1
part 2
-
Other examples
-
Thread Lock
-
Lock
synchronized
,ReentrantLock
arepessimistic
lock
-
-
Generic type
- demo 1 : Generic intro
- demo 2 : Generic type with custom class demo
- demo 3 : Generic with custom structure
- demo 4 : Generic method demo
- demo 5 : Generic class demo (example : DAO)
- demo 6 : Generic type with inheritance, wildcard
- demo 7 : Generic type with limited condition
- demo 8 : Generic type example1
- demo 9 : Generic type example2
-
IO
-
ClassLoader
- Steps -Load -> Link -> Initialize
-
Internet
- demo1 : TCP/UDP comparision
- demo2 : TCP demo 2 : client/server (via
socket
) : send msg - demo3 : TCP demo 3 : client/server (via
socket
) : send file - demo4 : TCP demo 4 : client/server (via
socket
) : send file and send/receive response - demo5 : UDP demo 1 : intro and basic implementation
- demo6 : URL demo 1 : intro and basic demo
- demo7 : URL demo 2 : download file from server and save it
-
TimeStamp API
- DateTime API before JDK 8
-
- System.currentTimeTimeMillis();
-
- java.util.Date and its sub class java.sql.Date
-
- SimpleDateFormat
-
- Calendar
-
- DateTimeApi : date, timestamp.. API demo
- CalendarApi : Calendar API demo
- LocalDateTime : LocalDate, LocalTime, LocalDateTime API demo
- InstantApi : Instant API demo
- DateTimeFormatterApi : DateTimeFormatter API demo
- DateTime API before JDK 8
-
Compare API
- ComparableComparator : Comparable, Comparator API demo
-
Reflection
- Demo 1 : Reflection basic demo
- Demo 2 : Create running class instance via reflection
- Demo 3 : Reflection dynamic
- Demo 4 : Reflection : get Runtime class instance : attr, class name, data type, permission
- Demo 5 : Reflection : get Runtime class instance : method
- Demo 6 : Reflection get constructor
- Demo 7 : Reflection get interface, packages
- Demo 8 : Reflection get/set attributions
- Demo 9 : Reflection Get methods from running class instance (Important!!)
-
Dynamic Proxy (動態代理)
- static proxy
- StaticProxyDemo1 : static proxy review/demo
- StaticProxyDemo2 : static proxy review/demo 2
- dynamic proxy
- DynamicProxyDemo1 : dynamic proxy demo1
- DynamicProxyDemo2 : dynamic proxy demo2
- static proxy
-
Lambda expression
- demo1 : Lambda intro, example
- demo2 :
Lambda form 1-6
demo - demo3 : functional interface 1
- MethodRefTest : method reference demo
- ConstructorRefTest : Constructor reference demo
-
Stream API
-
Optional
- demo1 : Optional demo 1
-
-
JavaHelloWorld : Advanced data structure
- String class
-
JavaHelloWorld : Mini project
-
JavaHelloWorld - Utils : General Util class
Design pattern
mkdir -p src/main/java/hello
# check maven version
mvn -v
# build the project
mvn compile
# Package the project
mvn package
# Run
java -jar target/gs-maven-0.1.0.jar
# Test
mvn test
Ref
- Java interview questions
- Java learning ref
- Spring Boot API Tutorial