陳韋傑
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    本篇筆記為我學習 Java 的一些紀錄,會學 Java 主要是因為 NTU Software Engineering Design by J Lee 所需。 本篇撰寫是建立在已有穩固程式語言基礎上,故只會包含 Java 與其他語言的重要差異,以及一些我認為需要特別紀錄的內容。 # 相關連結 ## Java - [Java Wiki](https://zh.wikipedia.org/zh-tw/Java) - [Java 3hr Basic Tutorial](https://www.youtube.com/watch?v=nQ1Z3NxpfIw) - [[推薦] Openhome.cc (Java 17)](https://openhome.cc/zh-tw/java/) ## Design Pattern - [Java设计模式丨图解+框架源码分析23种设计模式](https://www.bilibili.com/video/BV13z4y1D76S/?p=39&share_source=copy_web&vd_source=f95d1e685761ee0ed09f7ba4d03e5484) - [初探設計模式](https://ithelp.ithome.com.tw/users/20112528/ironman/2113?page=1) # 語法基礎 ## 基本架構 - Hello World There should be only one `public class` in one file, also, the filename should be the same as that class. For the following sample the file should be named `HelloWorld.java`. ```java= public class HelloWorld { public static void main(String[] args) { System.out.print("Hello World\n"); System.out.println("Hello World"); System.out.printf("Hello %s%n", "World"); } } ``` - [引用套件與輸出](https://openhome.cc/zh-tw/java/path-package-module/package-import/) The package_name needs to be the same with the file path! See more at [here](https://yubin551.gitbook.io/java-note/basic_java_programming/package_import). ```java= package {package_name} // export as a package import {package_name} // import from existing package ``` - 讀取輸入 ```java= import java.util.Scanner; public class Guess { public static void main(String[] args) { var console = new Scanner(System.in); System.out.print(console.next()); // stops at space System.out.print(console.nextLine()); // stops at newline chat System.out.print(console.nextInt()); System.out.print(console.nextDouble()); } } ``` - [格式化輸出](https://openhome.cc/zh-tw/java/syntax-abc/type/#格式化輸出) - [執行方式](https://openhome.cc/zh-tw/java/path-package-module/hello/) ```cmd= java HelloWorld.java ``` ```cmd= javac HelloWorld.java // Compile to .class file java HelloWorld ``` ## 基本資料型態 - 常見型態:`byte, short, int, long, float, double, char, boolean` - 可使用 `var` 來宣告變數,型態會自動判別,最好僅用在區域變數 - `final` 修飾的變數不可變 - 預設類別:`int` 與 `double`,要放到其他類別的變數要另外轉換 - `String` 不是基本資料型態 ### Casting ```java= double PI = 3.14; float PI = 3.14F; float PI = (float) 3.14; int number = 2147483648; long number = 2147483648L; ``` ### Promote ```java= System.out.println(10 / 3); // 3 System.out.println(10.0 / 3); // 3.333... ``` ```java= short a = 1; short b = 2; short c = (short) (a + b); // need to convert type ``` ### 進階資料型態 - 屬於 `class`,像是`String`、`BigDecimal` - 需要用 `a.equals(b)` 來比較其相等性(不然會比位址) - 關於[字串處理](https://openhome.cc/zh-tw/java/object/string/) - [文字區塊處理](https://openhome.cc/zh-tw/java/object/string/#文字區塊) ### 陣列 - 參考[這裡](https://openhome.cc/zh-tw/java/object/array/) - 陣列複製的時候要注意 shallow copy 的問題! ```java= // 1d array int[] scores = {88, 81, 74, 68, 78, 76, 77, 85, 95, 93}; System.out.println(scores.length); // 2d array int[][] cords = { {1, 2, 3}, {4, 5, 6} }; for(int[] row : cords) { for(int value : row) { System.out.printf("%2d", value); } System.out.println(); } // uninitialized declaration int[] scores = new int[10]; // copying an array int[] scores1 = {88, 81, 74, 68, 78, 76, 77, 85, 95, 93}; var scores2 = new int[scores1.length]; System.arraycopy(scores1, 0, scores2, 0, scores1.length); // or int[] scores2 = Arrays.copyOf(scores1, scores1.length); // object array class Object { ... } Object [] obj_array = { new Object(...); } ``` ## 其他基礎 ### 運算子 - 常見的都有,參見[這裡](https://openhome.cc/zh-tw/java/syntax-abc/operator/),特別注意有 `var c = (condition) ? a : b` 的寫法 ### 條件 - 跟 C++ 一樣,記得條件要括號,是用 `else if` - 有 `switch-case` 的語法,也一樣,記得加 `break` ```java= if (cond){ ... } else if (cond2){ ... } else{ ... } switch (var){ case 1: ... break; case 100: ... break; default: ... } var level = switch(quotient) { case 10, 9 -> 'A'; case 8 -> 'B'; case 7 -> 'C'; case 6 -> 'D'; default -> 'E'; }; ``` ### 迴圈 - 跟 C++ 一樣,有 `do-while` ```java= for(var i = 1; i <= N; i++) { ... } for(var item : item_list) { ... } while(cond) { ... } do { ... } while(cond); ``` ### Function ==Important!!!== - [Java: "Pass-by-Value" vs "Pass-by-Reference" - Unraveling the Confusion](https://dev.to/iamcymentho/java-pass-by-value-vs-pass-by-reference-unraveling-the-confusion-3gmh) - When you pass a primitive type, a copy of its value is passed to the method, leaving the original variable unchanged. - When you pass an object reference, the reference's value (memory address) is copied, not the object itself. This means you can modify the object's properties inside the method, but you can't change the reference itself. ### Commonly Used Packages - **`java.lang`**: Provides fundamental classes automatically imported into every Java program. - Key classes: `String`, `Object`, `Math`, `Integer`, `Boolean`. - **`java.util`**: Offers utility classes for collections, date/time manipulation, and other common functions. - Key classes: `ArrayList`, `HashMap`, `HashSet`, `Date`, `Collections`, `Random`, `Scanner`. - **`java.io`**: Facilitates input and output operations, including file handling and stream manipulation. - Key classes: `BufferedReader`, `InputStream`, `OutputStream`, `File`, `FileReader`, `PrintWriter`. - **`java.nio`**: Supports high-performance, non-blocking I/O operations, useful for large-scale applications. - Key classes: `ByteBuffer`, `FileChannel`, `Path`, `Files`. - **`java.time`**: Handles date and time operations in a modern, thread-safe manner. - Key classes: `LocalDate`, `LocalTime`, `LocalDateTime`, `Duration`, `Period`. - **`java.math`**: Supports precise mathematical computations, especially for large integers and decimals. - Key classes: `BigInteger`, `BigDecimal`. <!-- #### Else - **`java.net`** - Provides tools for networking, enabling communication over the internet or local networks. - Key classes: `Socket`, `ServerSocket`, `URLConnection`, `InetAddress`. - **`java.sql`** - Contains classes for accessing and managing relational databases via SQL. - Key classes: `Connection`, `Statement`, `PreparedStatement`, `ResultSet`, `DriverManager`. - **`java.security`** - Provides cryptographic functionalities and security algorithms. - Key classes: `MessageDigest`, `KeyFactory`, `Signature`. - **`java.awt`** - A set of classes for creating graphical user interfaces (GUIs). - Key classes: `Frame`, `Button`, `Canvas`, `Graphics`. - **`javax.swing`** - Provides a higher-level API for creating modern, lightweight GUI components. - Key classes: `JFrame`, `JButton`, `JLabel`, `JTextField`. - **`java.util.concurrent`** - Contains utilities for writing concurrent and multi-threaded applications. - Key classes: `ExecutorService`, `Future`, `CountDownLatch`, `Semaphore`. - **`java.rmi`** - Enables remote method invocation (RMI) to call methods on objects in different JVMs. - Key classes: `Naming`, `Remote`, `UnicastRemoteObject`. --> ### Miscellaneous #### Syntactic sugar 可用於修飾方法、參數 - `@Nullable`:可以為空 - `@NonNull`:不可為空 - `@SuppressWarnings("unchecked")`: suppress compiler warnings related to unchecked type casting operations # OOP ## Overall - A class can extend only one class (single inheritance for classes). - An interface can extend multiple interfaces. - A class can implement multiple interfaces. ## Basics - If define a constructor with parameters, then default constructor will NOT be automatically created ```java= package {anything}.{anything} class Clothes { String color; char size; Clothes(String color, char size) { this.color = color; this.size = size; } } // Only one public per file public class Field { public static void main(String[] args) { var sun = new Clothes("red", 'S'); Clothes spring = new Clothes("green", 'M'); System.out.printf("sun (%s, %c)%n", sun.color, sun.size); System.out.printf("spring (%s, %c)%n", spring.color, spring.size); } } ``` ## Record - 如果只是記錄屬性,可以使用 `record`,參見[這裡](https://openhome.cc/zh-tw/java/encapsulation/record/) ```java= record Clothes(String color, char size) {} public class Field { public static void main(String[] args) { var sun = new Clothes("red", 'S'); var spring = new Clothes("green", 'M'); System.out.printf("sun (%s, %c)%n", sun.color(), sun.size()); System.out.printf("spring (%s, %c)%n", spring.color(), spring.size()); } } ``` ## Wrapper - 把基本型態打包成 `class` 使用,細節參考[這裡](https://openhome.cc/zh-tw/java/object/primitive-wrapper/) ## Access Modifier (Public, Private, Protected) - [存取修飾子](https://yubin551.gitbook.io/java-note/basic_java_programming/accessmodifier) - [修飾外部類別](https://yubin551.gitbook.io/java-note/basic_java_programming/accessmodifier/modifyclass) ![image](https://hackmd.io/_uploads/HJgSNJkaA.png) ## Encapsulation - 將重複使用的程式碼打包起來 - 權限控管:僅能透過 `getter` 與 `setter` 操作成員變數 ```java= package cc.openhome; class CashCard { private String number; private int balance; private int bonus; ...略 void store(int money) { if(money > 0) { this.balance += money; if(money >= 1000) { this.bonus++; } } else { System.out.println("儲值是負的?你是來亂的嗎?"); } } int getBalance() { return balance; } int getBonus() { return bonus; } String getNumber() { return number; } } ``` ## Overload ```java= public class Some { private int a = 10; private String text = "n.a."; public Some(int a) { if(a > 0) { this.a = a; } } public Some(int a, String text) { if(a > 0) { this.a = a; } if(text != null) { this.text = text; } } ... } ``` ## Static - `static` 關鍵字代表該成員/方法屬於該類別,不屬於實體本身 (or class variable / method and not a part of any instance) - 因為 `this` 是屬於實體的屬性,因此不可能(也不應該)與 `static` 一起用 ```java= class Ball { double radius; static final double PI = 3.1415926; static double toRadians(double angdeg) { // 角度轉徑度 return angdeg * (Ball.PI / 180); } } // access class variable / method System.out.println(Ball.PI); System.out.println(Ball.toRadians(100)); // System.out.println is also a static method from "System"! ``` ## Inheritance - Use `super` to reference to parent class (like `this`) - Java only allows inheritance from one parent class ```java= public class Role { ... } public class SwordsMan extends Role { ... } public class Magician extends Role { ... } public class RPG { public static void main(String[] args) { ... } // Pull up showBlood() to Role level static void showBlood(Role role) { System.out.printf("%s 血量 %d%n", role.getName(), role.getBlood()); } } ``` ### How to determine compile success or not? - Use is-a method ![image](https://hackmd.io/_uploads/rkwjCtACA.png) - Use casting can pass compile, but will failed at run time ```java= SwordsMan swordsMan = new SwordsMan(); Role role = swordsMan; // SwordsMan 是一種 Role,這行通過編譯 // 你告訴編譯器要讓 Role 扮演 Magician,以下這行通過編譯 Magician magician = (Magician) role; // role 參考 SwordsMan 實例,執行失敗 ``` ### Abstract - Can add at class or at Function - Abstract class cannot be instantiate - Child class of abstract class must implement abstract function, or keep it in abstract for its child class (Thus make itself a abstract class) ```java= public abstract class Role { ... public abstract void fight(); } public class SwordsMan extends Role { @Override // Ask the compiler to validate public void fight() { System.out.println("揮劍攻擊"); } } ``` ### Interface - 定義行為外觀 - 與繼承只能一個相比,可以實作多個介面 ```java= public interface Swimmer { public abstract void swim(); } ``` ![image](https://hackmd.io/_uploads/BJO0iDwMJg.png)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully