Skip to content

Java basics project : data structure, algorithm, syntax, concept

Notifications You must be signed in to change notification settings

yennanliu/JavaHelloWorld

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

JavaHelloWorld

Java basic demo & projects

Projects

Java Hello World

  • Array1D:

- Array2D:

  • 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
    • 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
    • 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
          1. the class is a public class
          1. with a no argument public constructor
          1. has corresponding getter, setter methods
    • This

        1. this can be used in attr, class, method, constructor
        1. this on attr, 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....
        1. 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 the 1st 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
      • thisDemo1
      • thisDemo2
      • thisDemo3
      • thisDemo4
      • thisDemo5
    • Getter & Setter

    • Extends

      • Extends_demo1
      • Extends_demo2
      • the "children" class can reuse, overwrite the attr/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 of java.lang.Object
    • Overwrite

      • Overwrite_demo1
      • Overwrite_demo2
      • subclass can overwrite the same method (same method name, same param) that its superclass 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 superclass CAN NOT be overwritten
      • return_value_type
        • if return_value_type is void in superclass -> it's needed to be void in subclass as well
        • if return_value_type is A type in superclass -> the return_value_type in subclass can be "A type" or any 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
      • Exception_type
        • subclass' Exception_type must be smaller or equal than the one in superclass
      // 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)
      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
      // 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 type
        • Downcasting : 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

    • 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 ?)
        
        
      • Static method

        • lives in method's "static area"
        • static method is loaded when class is loaded
        • static method CAN ONLY call static method or static attr
        • non static method CAN call both : static/non-static method and static/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
      • staticDemo 1

      • staticDemo 2

      • staticDemo 3

      • staticDemo 4

      • staticDemo 5

      • staticDemo 6

    • 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

        # 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
        ```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;
            }
        }
        
    • 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
      • 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
      • 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

  • 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
        • get
          • method that deal with exception
          • two types
              1. try-catch-finally
              • compile
              1. 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)
          • 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, or a running program. is a dynamic process. has its cycle : launch - exist - terminate
        • examples
          • running spotify
          • running whatsapp
        • Program is static ; while process is dynamic
        • Process as resource allocation unit, will allocate threads to different memory spaces
      • 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 a mutiple 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 same heap -> but such memory sharing mechanisms may cause thready safety concerns.
      • parallel (並行) VS Concurrency (並發)
    • 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)

      • ThreadDemo1

      • ThreadDemo2

      • ThreadDemo3

      • ThreadDemo4 : common thread methods demo

      • ThreadDemo5

      • ThreadDemo6 : Callable interface (new in JDK 5.0)

      • Thread Safety

      • ThreadCommunication

        • ThreadCommunication1 : Thread communication methods demo (wait(), notify(), notifyAll())
        • ThreadCommunication2 : Thread communication demo : producer, consumer
        • Thread Communication methods:
            1. wait():
            • once run this method, the thread will be in blocked status and RELEASE Synchronized monitor (lock)
            1. notify():
            • once run this method, the thread will be "WAKED UP", if there are multiple threads, the first priority thread will be waked up
            1. notifyAll():
            • once run this method, ALL of the OTHER threads will be "WAKED UP"
      • Thread Dead Lock

      • ThreadDemo_1

      • RunnableDemo_1

      • CallableDemo_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);
        • Note : We need to overwroide run() method in both 2 methods

        • Method 3) : Callable + Future

        • Method 4) : Thread pool

      • Thread Cycle

      • Case study

      • Other examples

      • Thread Lock

      • Lock

        • synchronized, ReentrantLock are pessimistic 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

      • File IO

      • IO flow

        • IO 1 : FileReader demo
        • IO 2 : FileWriter demo
        • IO 3 : File copy (txt)
        • IO 4 : File copy (picture)
        • IO 5 : make File copy as funciton
        • IO 6 : File copy (picture) : Buffered IO flow
        • IO 7 : File copy (txt): BufferedReader, BufferedFileWriter
        • IO 8 : File encrypt/decrypt demo
      • IO flow2

        • demo1 : Transformation flow demo : InputStreamReader, OutputStreamWriter
      • IO flow3

        • demo1 : standard input and output stream: System.in, System.out
        • demo2 : DataInputStream, DataOutputStream demo
      • ObjectInputOutputFlow

        • demo1 : serialization, deserialization basic demo
        • demo2 : serialization, deserialization with custom java class
      • RandomAccessFile

        • demo1 : RandomAccessFile input, and output flow demo
      • NIO

    • 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
          1. System.currentTimeTimeMillis();
          1. java.util.Date and its sub class java.sql.Date
          1. SimpleDateFormat
          1. Calendar
      • DateTimeApi : date, timestamp.. API demo
        • demo1 : basic constructors, methods
        • demo2 : java.text.SimpleDateFormat, Calendar
      • CalendarApi : Calendar API demo
      • LocalDateTime : LocalDate, LocalTime, LocalDateTime API demo
      • InstantApi : Instant API demo
      • DateTimeFormatterApi : DateTimeFormatter API demo
    • Compare API

    • 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 (動態代理)

    • Lambda expression

    • Stream API

      • demo1 : Stream initiation op demo
      • demo2 : Stream intermedia op demo
      • demo3 : Stream terminate op demo
      • demo4 : Stream reduce op demo
    • Optional

      • demo1 : Optional demo 1
  • JavaHelloWorld : Advanced data structure

  • JavaHelloWorld : Mini project

  • JavaHelloWorld - Utils : General Util class

Design pattern

Run

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

Ref