Java Basics Part 8/20 - Basic Operators

Java Basics Part 8/20 - Basic Operators

目錄


Java 提供了豐富的操作運算符。可以分成以下幾組:

  • 算術運算符
  • 關係運算符
  • 位運算符
  • 邏輯運算符
  • 賦值運算符
  • 其他運算符

算術運算符

算術運算符用在數學表達式中:

假設 A 的值是 10, B 的值 是 20

SR.NO Operator and Example
1
    加: A + B => 30
2
    減: A - B => -10
3
    乘: A * B => 200
4 / 除: B / A =>2
5 % 取模: B % A => 0
6 ++ 自加1: B++ => 21
7 --自減1: B-- => 19

關係運算符

同樣,假設 A 是 10,B 是 20

SR.NO Operator and Description
1 == 等於: A== B false
2 != 不等於: A != B true
3 > 大於: A > B false
4 < 小於: A < B true
5 >= 大於等於: A >= B false
6 <= 小於等於: A <= B true

位運算符

Java 定義了很多位運算符,可以用在 int, long,short,char 和 byte 上。

位運算符操作的是 bit。假設 a = 60; b = 13.

a = 0011 1100
b = 0000 1101

a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

同樣,假設整形 A 是 60, B 是 13

SR.NO Operator and Description
1 & 位與: A & B => 12(0000 1100)
2 | 位或: A
3 ^ 位異或: A ^ B => 49(0011 0001)
4 ~ 位補碼: ~A => -61(1100 0011)
5 << 左移:A << 2 => 240(1111 0000)
6 >> 右移: A >> 2 => 15(1111)
7 >>> 無符號右移: A >>> 2 => 15(0000 1111)

邏輯運算符

假設 A 爲 true, B 爲 false

Operator Description
1 && 邏輯與: A && B => false
2 || 邏輯或: A || B => true
3 ! 邏輯非: !(A&&B) => true

賦值運算符

SR.NO Operator and Description
1 =
2 +=
3 -=
4 *=
5 /=
6 %=
7 <<=
8 >>=
9 &=
10 ^=
11 |=

其他運算符

條件運算符(?:)

variable x = (expression) ? value if true : value if false
舉例:

public class Test {

   public static void main(String args[]){
      int a, b;
      a = 10;
      b = (a == 1) ? 20: 30;
      System.out.println( "Value of b is : " +  b );

      b = (a == 10) ? 20: 30;
      System.out.println( "Value of b is : " + b );
   }
}

// output
Value of b is : 30
Value of b is : 20

instanceof 操作符

這個操作符僅用於對象的引用變量。它會檢查出一個對象是否是一個特定的類型。

( Object reference variable ) instanceof (class/interface type)
如果 對象 是 類 的實例,那麼結果就是 true,否則就是 false

class Vehicle {}

public class Car extends Vehicle {
   public static void main(String args[]){
      Vehicle a = new Car();
      boolean result =  a instanceof Car;
      System.out.println( result );
   }
}
// output 
true

操作符優先級

Category Operator Associativity
Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= =
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章