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;
指派運算符:=,*=