java學習(四)運算符
算術運算符:加、減、乘、除、自加、自減、取餘
-
++出現在變量前,先進行自加1,然後再複製
-
++出現在變量後,先賦值,然後再自加1
代碼如下
public class Operator_01{
public static void main(String[] args){
int a = 10;
int b = 3;
System.out.println(a+b); //13
System.out.println(a-b); //7
System.out.println(a*b); //30
System.out.println(a/b); //3
System.out.println(a%b); //1
//重點掌握++ 和 --
//++是自加1,可以出現在變量前,也可以出現變量後,只要++結束就是自加1
int j = 100;
j++;
System.out.println(j); //101
int k = 200;
k--;
System.out.println(k); //199
//++出現在變量前和變量後有啥區別?
//語法:當++出現在變量後,會先做賦值運算傳值,然後再自加1
int m =10;
int n = m++;
System.out.println(m); //11
System.out.println(n); //10
//++出現在變量前,會先進行自加1,然後賦值
int x =10;
int y = ++x;
System.out.println(x); //11
System.out.println(y); //11
int c =80;
int d = 90;
System.out.println(c++); //80 當++出現在變量後,會先做賦值運算傳給括號輸出,再自加1
System.out.println(c); //81
System.out.println(++d); //91
System.out.println(d); //91
}
}
關係運算符:>、>=、<、<=、==、!=
-
所有關係運算符的結果都是布爾類型
邏輯運算符:&、|、!、&&、||,邏輯與或非,短路與短路或
-
邏輯運算符兩邊是布爾類型,結果也是布爾類型
擴展的賦值運算符:==、+=、*=、/=、%=
-
普通賦值運算符語法:右邊先執行,再賦值給左邊
-
使用擴展運算符的時候,永遠不會改變運算結果的類型
-
代碼
public class Operator_03{ public static void main(String[] args){ int k = 20; k += 30; System.out.println(k); // i += 1和 i = i+1有啥區別 byte x = 20; System.out.println(x); //這行代碼報錯?等號右邊結果是int,左邊是byte,不兼容的類型 //x = x+1; //System.out.println(x); //下面這個代碼不報錯原因? //使用擴展賦值運算符的時候,永遠都不會改變運算結果類型 //其實在這裏的 x += 1就等同 x = (byte)(x+1) x += 1; System.out.println(x); x += 300; System.out.println(x);//超出byte的最大值,不會報錯,但會損失精度, } }
條件運算符(三目運算符)
-
布爾表達式?布爾表達式1:布爾表達式2
-
如果布爾表達式結果爲true,表達式1即爲結果
-
如果布爾表達式結果爲false,表達式2即爲結果
-
public class Operator_04{
public static void main(String[] args){
//條件運算符
//boolean sex = true;
//char c = sex ? '男' : '女';
//System.out.println(c);
//一個單引號一個雙引號編譯器會不會報錯?錯誤: 不兼容的類型: 條件表達式中的類型錯誤,
//等式右邊字符串String類型 等式左邊char類型,編譯報錯
//boolean sex = false;
//char c = sex ? '男' : "女";
//System.out.println(c);
//不指定類型,直接放進打印還會報錯嗎?不會,可以輸出字符串女
boolean sex = false;
System.out.println( sex ? '男' : "女");
}
}
字符串拼接
-
當“+”運算的時候,兩邊的操作數都是數字的話,一定會進行求和運算,只 要其中有一個操作數是字符串類型,那麼一定會進行字符串拼接運算,字符串拼接之後的結果 還是字符串類型。
-
需要注意的是,當一個表達式當中有多個“+”,並且在沒有小括號的前提 下,遵循自左向右的順序依次執行。