Variable

變數

Variables type

String:

int:

float:

char:

boolean:

Declaring 宣告

Syntax: type variableName = value;

Example:

String name = "John";

int myNum = 15;

System.out.println(name);

System.out.println(myNum);

myNum = 20; // myNum is now 20

System.out.println(myNum);

Output: John 15 20

Other Example:

int myNum = 5;

float myFloatNum = 5.99f;

char myLetter = 'D';

boolean myBool = true;

String myText = "Hello";

Final關鍵字

變數宣告時,放在type前面,表示該變數是常數,無法再更改。

public class Main {

public static final double PI = 3.14159;

public final int x = 10;

public static void main(String[] argv) {

final int local = 10;

Main m = new Main();

PI = 100; // 編譯錯誤,只能於宣告時給值。

m.x = 10; // 編譯錯誤,只能於宣告時給值。

local = 100; // 編譯錯誤,只能於宣告時給值。

}

}