變量
Instance Variables (Non-Static Fields) 實例變量(非靜態變量)
一個類可以創造多個實例,實例中的變量叫做實例變量,相互獨立。
Class Variables (Static Fields) 類變量(靜態變量)
對比來看,類變量就是類的變量,一個類只能有一份,不能複製,使用static
關鍵字來定義類變量。
代碼:
public class MyVar {
static int classVar = 1; // 類變量(靜態變量)
int instanceVar = 2; // 實例變量
}
對比Python來看就很清楚:
class MyVar: class_var = 1 def __int__(self): instance_var = 2
Local Variables 局部變量
局部變量是由代碼位置決定的,前面的實例變量和類變量,是放到Field位置,而局部變量是放到Method裏面。也就是說,局部變量是放在方法的花括號裏面的變量,並且只能在方法內部訪問,不能被其他地方訪問,這就是所謂的局部。
public class MyVar {
static int classVar = 1; // 類變量(靜態變量)
int instanceVar = 2; // 實例變量
void method() {
int localVar = 3; // 局部變量
}
}
Parameters 參數
參數就是方法名後面小括號裏面的變量。
public class MyVar {
static int classVar = 1; // 類變量(靜態變量)
int instanceVar = 2; // 實例變量
void method(int parameter) { // 參數
int localVar = 3; // 局部變量
}
}
變量命名規則
駝峯命名法,可參考阿里規範: https://github.com/alibaba/p3c
基本數據類型
Java有8個基本數據類型:byte、short、int、long、float、double、boolean、char。
對比Python的6個基本數據類型:Number(數字)、String(字符串)、List(列表)、Tuple(元組)、Set(集合)、Dictionary(字典),你發現了什麼嗎?
Java的String嚴格來說不算基本數據類型,因爲它其實是一個類,java.lang.String
。
默認值
只聲明不賦值的字段(定義在類級別的field),編譯器會給它賦予默認值:
-
byte:0
-
short:0
-
int:0
-
long:0L
-
float:0.0f
-
double:0.0d
-
boolean:false
-
char:\u0000
String或任何對象,會賦值爲null。
而對於局部變量(定義在方法裏面的variable),編譯器不會自動賦值,只聲明不賦值,會報編譯錯誤。
類的field會賦默認值。方法的局部variable不會。
字面量Literals
基本數據類型的初始化可以不使用new,而直接使用字面量:
byte b = 100;
short s = 10000;
int i = 100000;
int hexadecimalValue = 0x1a; // 十六進制
int binaryValue = 0b11010; // 二進制
long x = 10000000L;
float f1 = 123.4f;
double d1 = 123.4;
double d2 = 1.234e2; // 科學計數法
boolean result = true;
char capitalC = 'C';
String也不需要new就能初始化:
String s = "this is a string";
另外還有一個字面量.class
,比如String.class
,用來表示自己的類型。
數組
An array is a container object that holds a fixed number of values of a single type.
注意這裏說的是container object,數組不是基本數據類型,而是容器對象。這一點也可以從數組初始化來論證,數組初始化是需要new的:
int[] anArray;
anArray = new int[10];
代碼示例:
class ArrayDemo {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;
// allocates memory for 10 integers
anArray = new int[10];
// initialize first element
anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// and so forth
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;
System.out.println("Element at index 0: "
+ anArray[0]);
System.out.println("Element at index 1: "
+ anArray[1]);
System.out.println("Element at index 2: "
+ anArray[2]);
System.out.println("Element at index 3: "
+ anArray[3]);
System.out.println("Element at index 4: "
+ anArray[4]);
System.out.println("Element at index 5: "
+ anArray[5]);
System.out.println("Element at index 6: "
+ anArray[6]);
System.out.println("Element at index 7: "
+ anArray[7]);
System.out.println("Element at index 8: "
+ anArray[8]);
System.out.println("Element at index 9: "
+ anArray[9]);
}
}
多維數組:
class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}
};
// Mr. Smith
System.out.println(names[0][0] + names[1][0]);
// Ms. Jones
System.out.println(names[0][2] + names[1][1]);
}
}
使用System.arraycopy()
複製數組:
class ArrayCopyDemo {
public static void main(String[] args) {
String[] copyFrom = {
"Affogato", "Americano", "Cappuccino", "Corretto", "Cortado",
"Doppio", "Espresso", "Frappucino", "Freddo", "Lungo", "Macchiato",
"Marocchino", "Ristretto" };
String[] copyTo = new String[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
for (String coffee : copyTo) {
System.out.print(coffee + " ");
}
}
}
使用java.util.Arrays.copyOfRange
複製數組:
class ArrayCopyOfDemo {
public static void main(String[] args) {
String[] copyFrom = {
"Affogato", "Americano", "Cappuccino", "Corretto", "Cortado",
"Doppio", "Espresso", "Frappucino", "Freddo", "Lungo", "Macchiato",
"Marocchino", "Ristretto" };
String[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9);
for (String coffee : copyTo) {
System.out.print(coffee + " ");
}
}
}
操作符
賦值:
int cadence = 0;
int speed = 0;
int gear = 1;
數學運算:
class ArithmeticDemo {
public static void main (String[] args) {
int result = 1 + 2;
// result is now 3
System.out.println("1 + 2 = " + result);
int original_result = result;
result = result - 1;
// result is now 2
System.out.println(original_result + " - 1 = " + result);
original_result = result;
result = result * 2;
// result is now 4
System.out.println(original_result + " * 2 = " + result);
original_result = result;
result = result / 2;
// result is now 2
System.out.println(original_result + " / 2 = " + result);
original_result = result;
result = result + 8;
// result is now 10
System.out.println(original_result + " + 8 = " + result);
original_result = result;
result = result % 7;
// result is now 3
System.out.println(original_result + " % 7 = " + result);
}
}
x += 1;
等同於x = x + 1;
一元運算符:
class UnaryDemo {
public static void main(String[] args) {
int result = +1;
// result is now 1
System.out.println(result);
result--;
// result is now 0
System.out.println(result);
result++;
// result is now 1
System.out.println(result);
result = -result;
// result is now -1
System.out.println(result);
boolean success = false;
// false
System.out.println(success);
// true
System.out.println(!success);
}
}
++i
和i++
都會加1,區別是++i
的結果是遞增後的值,i++
的結果是原來的值:
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}
關係運算符:
class ComparisonDemo {
public static void main(String[] args){
int value1 = 1;
int value2 = 2;
if(value1 == value2)
System.out.println("value1 == value2");
if(value1 != value2)
System.out.println("value1 != value2");
if(value1 > value2)
System.out.println("value1 > value2");
if(value1 < value2)
System.out.println("value1 < value2");
if(value1 <= value2)
System.out.println("value1 <= value2");
}
}
條件運算符:
class ConditionalDemo1 {
public static void main(String[] args){
int value1 = 1;
int value2 = 2;
if ((value1 == 1) && (value2 == 2))
System.out.println("value1 is 1 AND value2 is 2");
if ((value1 == 1) || (value2 == 1))
System.out.println("value1 is 1 OR value2 is 1");
}
}
?:
等同於if-then-else
class ConditionalDemo2 {
public static void main(String[] args){
int value1 = 1;
int value2 = 2;
int result;
boolean someCondition = true;
result = someCondition ? value1 : value2;
System.out.println(result);
}
}
Instanceof判斷:an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface
class InstanceofDemo {
public static void main(String[] args) {
Parent obj1 = new Parent();
Parent obj2 = new Child();
System.out.println("obj1 instanceof Parent: "
+ (obj1 instanceof Parent));
System.out.println("obj1 instanceof Child: "
+ (obj1 instanceof Child));
System.out.println("obj1 instanceof MyInterface: "
+ (obj1 instanceof MyInterface));
System.out.println("obj2 instanceof Parent: "
+ (obj2 instanceof Parent));
System.out.println("obj2 instanceof Child: "
+ (obj2 instanceof Child));
System.out.println("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));
}
}
class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {}
位運算符:
class BitDemo {
public static void main(String[] args) {
int bitmask = 0x000F;
int val = 0x2222;
// prints "2"
System.out.println(val & bitmask);
}
}
語句
表達式
int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);
int result = 1 + 2; // result is now 3
if (value1 == value2)
System.out.println("value1 == value2");
語句
// assignment statement
aValue = 8933.234;
// increment statement
aValue++;
// method invocation statement
System.out.println("Hello World!");
// object creation statement
Bicycle myBike = new Bicycle();
塊
class BlockDemo {
public static void main(String[] args) {
boolean condition = true;
if (condition) { // begin block 1
System.out.println("Condition is true.");
} // end block one
else { // begin block 2
System.out.println("Condition is false.");
} // end block 2
}
}
控制語句
if-then
void applyBrakes() {
// the "if" clause: bicycle must be moving
if (isMoving){
// the "then" clause: decrease current speed
currentSpeed--;
}
}
if-then-else
class IfElseDemo {
public static void main(String[] args) {
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
while
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
do-while
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}
for
class ForDemo {
public static void main(String[] args){
for(int i = 1; i < 11; i++){
System.out.println("Count is: " + i);
}
}
}
enhanced for
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers =
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
break
class BreakDemo {
public static void main(String[] args) {
int[] arrayOfInts =
{ 32, 87, 3, 589,
12, 1076, 2000,
8, 622, 127 };
int searchfor = 12;
int i;
boolean foundIt = false;
for (i = 0; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at index " + i);
} else {
System.out.println(searchfor + " not in the array");
}
}
}
continue
class ContinueDemo {
public static void main(String[] args) {
String searchMe = "peter piper picked a " + "peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++) {
// interested only in p's
if (searchMe.charAt(i) != 'p')
continue;
// process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}
return
return ++count; // 返回value
return; // 返回void
Switch語句
int quarter = ...; // any value
String quarterLabel = null;
switch (quarter) {
case 0: quarterLabel = "Q1 - Winter";
break;
case 1: quarterLabel = "Q2 - Spring";
break;
case 2: quarterLabel = "Q3 - Summer";
break;
case 3: quarterLabel = "Q3 - Summer";
break;
default: quarterLabel = "Unknown quarter";
};
selector的類型只能是:
-
byte short char int 基本數據類型
-
Byte Short Character Integer 包裝類型
-
枚舉類型
-
String類型
不能是:boolean long float double
不寫break會全部case執行一遍:
int month = 8;
List<String> futureMonths = new ArrayList<>();
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December");
break;
default: break;
}
多個case連寫:
int month = 2;
int year = 2021;
int numDays = 0;
switch (month) {
case 1: case 3: case 5: // January March May
case 7: case 8: case 10: // July August October
case 12:
numDays = 31;
break;
case 4: case 6: // April June
case 9: case 11: // September November
numDays = 30;
break;
case 2: // February
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
如果selector是null,會報空指針異常:NullPointerException
參考資料:
Java Language Basics https://dev.java/learn/language-basics/