java思想- - ->控制程序流程

java用運算符(operator)來控制程序。

 使用java運算符

       +,-,*,/,=

幾乎所有的運算符都是作用於primitive數據,==,=,!= 是例外,它們可以作用於任何對象。

 

優先級

先乘除後加減,有括號的先算括號裏面的。

x= x + y - x/z + k

x= x + (y-z)/(z+k)

 

賦值

a = 4; this is right   4 = a ; this is wrong .

primitive持有的是實實在在的數值,不是指向內存的reference。

 

a = b,如果改變a 的數值,b的數值是不發生變化的。

 

對象之間的賦值是在用他們的reference。

c = d,那麼c ,d 現在都指向d原來的reference。

 

example:

public class Test{

 

int i = 0; int ii = 0;

public void static main(String args[]){

Test test1 = new Test();

Test test2 = new Test();

test1.i =  2;

test2.i = 3;

test1.ii = 4;

test2.ii = 5;

test1 = test2;

system.out.println(test1.i + " " + test2.i );

// both the value of them are 3;

System.out.println(test1.ii + " " + test2.ii);

// both the value of them are 5

}

public void static main(String args[]){

Test test1 = new Test();

Test test2 = new Test();

test1.i =  2;

test2.i = 3;

test1.ii = 4;

test2.ii = 5;

test1.i = test2.i;

system.out.println(test1.i + " " + test2.i );

// both the value of them are 3;

System.out.println(test1.ii + " " + test2.ii);

//test1.ii is 4 and test2.ii is 5

}

}

 

數學運算符

    %:是取餘數的。

'/'不是四捨五入的,他會把小數都捨去的。example:26/7 = 3 ,!=4

x +=4; x = x + 4;

 

隨機生成數:Random random =  new Random();

 

單元加號和減號的運算符

a = -b; c = a * -b;

 

自動遞增和遞減

a++ : 先給a++ = a賦值,然後在a = a+ 1;

++a : 先 a = a + 1,然後在 a++ = a;

a-- :先給a-- = a,然後在a = a-1;

--a : 先 a =  a -1 ,然後在a-- = a;

關係運算符:

> ,<  , >= ,<= , == , !=

 

==:比較的是對象的reference

equeals();比較的是對象的內容,不是reference。

 

邏輯運算符:

&&,||,!

邏輯運算符中短接的問題

example:

boolean a ,b ,c;

if(a||b||c){

// if one of them is true , the condition is true all the time .

}

 

位運算符:

&:兩個都是1返回1

|:有一個1就返回1

~:1返回0,0返回1

^:有且只有一個1,返回1

&=,|=,^= 運算並且賦值。

boolean isfor ^=true;

isfor = isfor^true;

 

位運算對boolean類型也是適用的:

example:

true^true : false

true^false: true

false^false : false

 

true|true :true

true|false :true

false|false:false

 

true&true : true

true &false: false

false&false: false

 

三元運算符:

boolean—expression ? value1 : value2

 

逗號運算符的使用:

for(int i=1,j=i+10;i<5;i++,j=i*2) {}

 

加號運算符:

public void print(){

int a = 2;

int b = 3;

int c = 4;

String s = "ricky" + a + b + c;

//a b c的值不會相加的,編譯器會把它們都轉換成字符串。連接起來。

}

 

類型轉換運算符:

cast:自動轉換,強制轉換。

自動轉換使用於:小類型--》大類型

int i = 9;

long lg = i;

強制轉換:大類型---》小類型  會存在數據丟失的情況

long lg = 232;

int i = (int)lg;

java允許除了boolean意外的primitive類型數據進行轉換;

其他任何對象只能在他們的類系裏進行轉換,

(String類型是個特例)

 

常量

十六進制:0x開頭

八進制:0開頭

二進制:由0,1組成。

數字後面:

l/L :long

d/D :double

f/F : float

 

java中所有的類型佔用的空間,在所有的平臺上都是相同的。

 

運算符的優先級別:

單元運算符( + ,- ,++,--)

算數運算符(*,/,%,+,-,<<,>>)

關係運算符(>,<,<=,>=,!=)

關係運算符(&&,||,&,|,^)

條件運算符:a>b ? false: true;

賦值運算符:=,*=

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章