CodeGym /Java Blog /Toto sisi /Java 中的數字運算符
John Squirrels

San Francisco

# Java 中的數字運算符

``````
public class Main {

public static void main(String[] args) {

int x = 999;
int y = 33;

System.out.println(x+y);
System.out.println(x-y);
System.out.println(x*y);
System.out.println(x/y);
}
}
``````

``````
public class Main {

public static void main(String[] args) {

int x = 33;
int y = 33%2;
System.out.println(y);
}
}
``````

• 等於 ( `==`)
• 大於 ( `>`)
• 小於 ( `<`)
• 大於或等於 ( `>=`)
• 小於或等於 ( `<=`)
• 不等於 ( `!=`)

``````
public class Main {

public static void main(String[] args) {

int x = 33;
int y = 999;
System.out.println(x=y);// We expect false to be displayed
}
}
``````

``````
public class Main {

public static void main(String[] args) {

int x = 33;
int y = 999;
System.out.println(x==y);
}
}
``````

``````
public class Main {

public static void main(String[] args) {

int x = 999;
int y = 33;
int z = 256;

x = y = z;
System.out.println(x);
}
}
``````

• `y = z`， 那是，`y = 256`
• `x = y`， 那是，`x = 256`

## 一元運算符。

• 一元減號。它翻轉數字的符號。

``````
public class Main {

public static void main(String[] args) {

int x = 999;

// Change the sign for the first time
x = -x;
System.out.println(x);

// Change the sign for the second time
x= -x;
System.out.println(x);
}
}
``````

• 遞增 (++) 和遞減 (--)

``````
public class Main {

public static void main(String[] args) {

int x = 999;
x++;
System.out.println(x);

x--;
System.out.println(x);
}
}
``````

``````
public class Main {

public static void main(String[] args) {

int x = 999;
int y = x++;
System.out.println(y);
}
}

``````

``````
public class Main {

public static void main(String[] args) {

int x = 999;
int y = x++;
System.out.println(y);
System.out.println(x);
}
}
``````

``````
public class Main {

public static void main(String[] args) {

int x = 999;
int y = ++x;
System.out.println(y);
}
}
``````

## 複合運算符

• 任務
• 算術運算符

• `+=`
• `-=`
• `*=`
• `/=`
• `%=`

``````
public class Main {

public static void main(String[] args) {

int x = 999;
int y = 33;

x += y;
System.out.println(x);
}
}
``````

## 邏輯運算符

• `!`- 邏輯。它翻轉布爾值
``````
public class Main {

public static void main(String[] args) {

boolean x = true;
System.out.println(!x);
}
}
``````

• `&&`- 邏輯。只有當兩個操作數都為真時，它才返回真。
``````
public class Main {

public static void main(String[] args) {

System.out.println(100 > 10 && 100 > 200);
System.out.println(100 > 50 && 100 >= 100);
}
}
``````

• `||`- 邏輯當至少一個操作數為真時，它返回真。

``````
public class Main {

public static void main(String[] args) {

System.out.println(100 > 10 || 100 > 200);
}
}
``````

TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION