Java
Java
2022/06/19 (連結更新)
基本概念
一般而言,一個基本的java程式一定會有:
package com.example.demo;
public class DemoApplication {
public static void main(String[] args) {
}
}
跟其他語言(如:python、php)不同,java程式一定要是個類別,以範例程式為例,類別名稱是DemoApplication,而且這個檔案也必須儲存為DemoApplication.java。
public class DemoApplication {
}
跟其他語言(如:python、php)不同,執行java程式不是同第一行開始執行,而是執行main。
public class DemoApplication {
public static void main(String[] args) {
}
}
java一開始的設計就已經是認定輸出、輸入會是多元化,所以,如果要在螢幕上輸出,就要採用System.out.println。System.out.println接受一個字串參數,並將字串顯示在螢幕上。
public class DemoApplication {
public static void main(String[] args) {
System.out.println("Hello");
}
}
變數
java是強資料型態的語言,一方面,在使用變數之前, 一定要先定義,另一方面,也必須定義變數的資料型態,以一個整數變數為例,「int」表示是一個整數變數,「qty」是變數名稱,另外,也可以利用「=」指定起始值 ,跟php很像,結尾要有「;」:
int qty = 0;
細節請詳參Java Variables
跟很多語言一樣,可以利用「=」改變內容,唯一不同的是,不能改變資料型態,也不能使用未定義變數。
qty = qty + 1;
qty = "0"; //語法錯誤
q = qty + 1; //語法錯誤
跟很多語言一樣(其實都來自於c語言)當然也可以利用「++」讓變數加一寫成:
qty++;
細節請詳參Java Operators
在java裡,定義一個常數,使用的關鍵字是「final」,而不是「const」
final int qty = 0;
qty ++; //語法錯誤
變數範圍
在java裡,定義在大括號裡的變數,在大括號外面就不認得了。
{
int qty = 0;
System.out.println(qty);
}
System.out.println(qty);//語法錯誤
基本語法
java跟php很像,有if、switch、while、for等基本語法。
陣列
陣列的語法跟php有點類似,要注意的是,java指定陣列起始值使用的是大括號,另外,也要先指定陣列裡所有元素的資料型態。
int[] myNum = {10, 20, 30, 40};
System.out.println(myNum[0]);
java也有類似php的foreach,只是,語法長的不太一樣:
for (int num : myNum) {
System.out.println(num);
}
Java裡沒有php的Associative array,不過,有類似的資料結構,如:Java HashMap 。
方法
在java裡,所有的函數都必須屬於類別,稱之為方法。在java裡的方法,要定義回傳值的資料型態,如果沒有回傳值,則使用void。
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
方法有兩種,一種是類別方法 (static method)
// Static method
public static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
public static void main(String[] args) {
}
一種是物件方法
// Object method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
使用物件方法,一定要先產生物件。
Main myObj = new Main(); // Create an object of Main
myObj.myPublicMethod(); // Call the public method on the object
php裡也有類別與物件,只是較少人使用。然而,在java裡類別與物件卻是必備的核心概念。
public class Main {
// Static method
public static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
// Object method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error
Main myObj = new Main(); // Create an object of Main
myObj.myPublicMethod(); // Call the public method on the object
}
}
物件變數
Java Classes and Objects (W3School)
Java Class Attributes (W3School)
Java Class Methods (W3School)
Defining Classes (Wikibooks)
W3School
Wikibooks
基本語法
Debug
Exception
命名規則
要有意義,所以名稱都應該有意義,避免類似「i」、「i」、「firstVariable」等無法代表變數內容的名稱。
類別名: 類別名的第一個字一律大寫,如果是由多個字組成,每個字的開頭一律大寫,如:PurchaseOrder。
物件名: 物件名的第一個字一律小寫,如果是由多個字組成,除第一個以外,每個字的開頭一律大寫,如:purchaseOrder。
屬性(變數)名: 屬性的第一個字一律小寫,如果是由多個字組成,除第一個以外,每個字的開頭一律大寫,如:reorderPoint,習慣上不再冠類別名,(如:在Customer裡,不用customerName,而是,name)。
方法名: 方法的第一個字一律小寫,如果是由多個字組成,除第一個以外,每個字的開頭一律大寫,如:getReorderPoint。
進階Java語法
4 Things That are most confusing for Java Developer
Usage of Announymous Classes
Multithreading
Implementation of Synchronization
Serialization
Annotation
@在java中稱為Annotation,Annotation是java 5的新語法,雖然很多人將Annotation翻譯為註解,但是,Annotation跟Comment是完全不一樣的,Comment是純粹給人看的,而Annotation卻是給系統看的。
Java annotation (wikipedia)
Asynchronous
Generic
java 5.0之後的語法: 泛型(Generic)
Lambda
Optional
Please stop the Java Optional mess!
Optional badly done
Use of Optional in Java fields in our classes
Express the optionality of a value in constructors by using Optional
Stream
How to handle exceptions properly within streams: the functional way
Java Stream API — Learn how to convert streams to other data structures
Switch
String title = switch (person) {
case Dali, Picasso -> "painter";
case Mozart, Prokofiev -> "composer";
case Goethe, Dostoevsky -> "writer";
};
Synchronization
Textblock
String myMultiLineText = """
first line
second line
""";
Thread
How to use the Executor Framework in Java : A Complete Guide for Thread Management with Java Executor — Part 1
How to use Java Callable and Future : A Complete Guide for Thread Management with Java Executor — Part 2
Annotations for Concurrency in Java. Our approach to coloring threads
Socket
10 excellent GitHub repositories for every Java developer
Java Design Patterns
Interviews
Algorithms
Realworld
Awesome Java
Baeldung Tutorials
JHipster
RxJava Android Samples
Java8 Tutorial
Cracking the Coding Interview in Java
參考資料
Java SE 5 is the most significant release
SE5
Generic data structures
For-each loop
Auto-boxing/unboxing
Variadic methods (varargs)
Return type covariance
Annotations
Enumerations
Standard library
Static imports
SE6
Standard library
SE7
Generic diamond operator
Try-with-resources statement
Numeric literal syntax
Switch on strings
Multi-catch
Standard library: Various utilities
SE8
Better generic type inference
Capture of effectively final variables
Standard library
Interface default methods
Syntax and new features in Java 8
Default interface methods
Lambda expressions
Reference methods
Repeatable annotations
Stream
5 Features in Java 9 that WILL Change How You Develop Software (and 2 That Won’t)
Java + REPL = jshell
Noteworthy API Updates: Concurrency and Stack Walking
G1 will be the new default garbage collector
HTTP 2.0 is the future
The process API just got a huge boost
4 Amazing Techniques for Writing Better Java
Covariant Types (Java 5)
The covariant return type specifies that the return type of the class may vary in the same direction as the subclass.
Intersectional Generic Types
Auto-Closeable Classes
Java 7 introduces the try-with-resources
Final Classes and Methods
A New Future for Java (based on Java 14)
History of JVM Languages
Java
Groovy
Scala
Clojure
Kotlin
The “Kotlinisation” of Java
Java records
Improved switch statement
Text blocks
Java 17 language compared to Java 8. How modern Java is better than Java 8?