Chapter4This is a featured page

第四章 運算子(operators)重點整理
(1)指派運算子(Assignment Operators)=
給變數一個值。
(2)複合指派運算子(compound assignment operators)+= -= *= /= x
*= 2+5; 代表 x=x *(2+5);
(3)關係運算子(relational Operators)< <= > >=
判斷2變數間數學運算,結果是boolean
(4)等號運算子:= = !=
任何只能有boolean運算數學式的條件判別內可以用=取代==只適合用於
boolean變數,
例如:boolean a=false; if(a=ture){System.out.println(“a is true”)} else
{ System.out.println(“a is false”)}; 結果是a is true,這是合法,如果a為
別種型態則會錯誤,int a=1; if(a=0){};錯誤,除非用if(a==0) 會通過
(5)Enums(Enumerated) Types:以邏輯名稱代替屬性值
重點:1.enum必須先告初始值,不可以先定義建構子或方法
2.類似class定義了新型別,可以定義任意數量的屬性、方法與建構子,
建構子永遠用private
3.不可以繼承別的Class也不能被別的Class繼承
4.使用時不用new
enum Season{ Spring (“Traveling”);
Private.Season(strings){this.whatToDo=…;}} enum Color {RED,BLUE}
代表 Color.RED型別是Color Color c1=Color.RED;
Color c2 = Color.RED; if(c1== c2)if(c1.equals(c2))是相等的。
(6)instanceof:是用來判斷某物件屬於何種類別物件的運運算元。
(String s=”ABC”; boolean flg = s instanceof String;//flg=true)instanceof的左邊通常是
任何 object reference expressionvariable,但右邊必須是與左邊有繼承 關係的
class, interface, array type,否則會發生error
Interface Foo{} class
A implements Foo{}
class B extends A {} ….
A a = new A(); B b = new B();
下列狀況為true
1.a instanceof Foo
2.b instanceof A
3.b instanceof Foo (不直接的實作)
(7)算數運算子:+ - * / %(取餘數)
(8)字串連結運算子(String Concatenation Operator)+可以連結字串
int b = 2; System.out.println(“” + b + 3); 結果: 23
(9)遞增和遞減運算子
++(遞增):分為前置(先加再作其他)或後置(先作其他再加)
--(遞減):分為前置(先減再作其他)或後置(先作其他再減)
例子:
int x = 2; int y = 3;
if ((y == x++) | (x<++y))
{ System.out.println(“x = ” + x + “y = ” + y);} 結果: x = 3 y = 4
例子:
final int x = 5; int y = x++;(產生編譯錯誤,cannot assign a value to final variable)
(10)條件運算子(Conditional Operator) A?B:C 代表Atrue,執行B,反之執行C
(11)邏輯運算子(logical operator)(&|!^&&||)
^ 0 ^11^0結果為1 0 ^01^1結果為0 。^(只能用在int上)。
& | :可以用在int和boolean上。
&& ||: 只能用在boolean上,作用同& |,但是不同在於&& ||有短路运算。
(12)短路的邏輯運算子(Short-Circuit Logical Operators)
&&:短路AND運算元,它不需要浪費時間做不需要的運算,(只要左邊不符
合就不執行右邊)
||:短路OR運算元,它不需要浪費時間做不需要的運算,(只要左邊符合就不
執行右邊)
int z = 5; if(++z>5 || ++z>6) z++; //只執行左邊,結果:z = 7 int z = 5;
if(++z>5 | ++z>6) z++; //兩邊都要執行,結果:z = 8


No user avatar
jefflinweb
Latest page update: made by jefflinweb , Aug 22 2007, 1:55 AM EDT (about this update About This Update jefflinweb Edited by jefflinweb

24 words added
13 words deleted

view changes

- complete history)
Keyword tags: None
More Info: links to this page

Anonymous  (Get credit for your thread)


There are no threads for this page.  Be the first to start a new thread.