Java的知識點5——擴充套件賦值運算子、 關係運算符、 邏輯運算子、字串連線符、 條件運算子
阿新 • • 發佈:2018-12-15
擴充套件運算子
程式
public class Dd1 {
public static void main(String[] args) {
int a=3;
int b=4;
a+=b;//相當於a=a+b;
System.out.println("a="+a+"\nb="+b);
a=3;
a*=b+3;//相當於a=a*(b+3)
System.out.println("a="+a+"\nb="+b); }
}
執行結果:
a=7 b=4 a=21 b=4
關係運算符
- ==、!= 是所有(基本和引用)資料型別都可以使用
- > 、>=、 <、 <= 僅針對數值型別(byte/short/int/long, float/double。以及char)
邏輯運算子
短路與和邏輯與的程式:
public class Dd1 { public static void main(String[] args) { //1>2的結果為false,那麼整個表示式的結果即為false,將不再計算2>(3/0) boolean c=1>2&&2>(3/0); System.out.println(c); //1>2的結果為false,那麼整個表示式的結果即為false,還要計算2>(3/0),0不能做除數,//會輸出異常資訊 boolean d=1>2&2>(3/0); System.out.println(d); } }
程式執行結果:
false Exception in thread "main" java.lang.ArithmeticException: / by zero at Dd1.main(Dd1.java:7)
位運算子
public class Test1 { public static void main(String[] args) { int a=3*2*2; int b=3<<2; //相當於:3*2*2 int c=12/2/2; int d=12>>2; //相當於:12/2/2 System.out.println(a+"\t"+b+"\t"+c+"\t"+d); } }
程式執行結果:12 12 3 3
注: 1. &和|既是邏輯運算子,也是位運算子。如果兩側運算元都是boolean型別,就作為邏輯運算子。如果兩側的運算元是整數型別,就是位運算子。
2. 不要把“^”當做數學運算“乘方”,是“位的異或”操作。
字串連線符
“+”運算子兩側的運算元中只要有一個是字串(String)型別,系統會自動將另一個運算元轉換為字串然後再進行連線
條件運算子
public class Test2 {
public static void main(String [] args) {
int score=80;
int x=-100;
String type=score<60?"不及格":"及格"; //type=及格
int flag=x>0?1:(x==0?0:-1); //flag=-1
System.out.println("type="+type);
System.out.println("flag="+flag);
}
}
程式執行結果:
type=及格 flag=-1