Arithmetic Operators
| Operator | Description |
|---|---|
+ - * / % |
Basic math |
++ -- |
Pre- and post-increment/decrement |
+ (unary) |
Keep sign |
- (unary) |
Negate |
Prefix vs. Postfix
int a = 5;
int b = ++a; // a=6, b=6
int c = a++; // c=6, a=7
String Concatenation
String s = "score:" + 100; // "score:100"
Assignment Operators
+= -= *= /= %= all preserve the left-hand variable’s type and perform implicit casting.
byte b = 10;
b += 5; // compiles; same as b = (byte)(b + 5);
Relational Operators
== != > < >= <= instanceof yield boolean.
Account a1 = new Account(1000);
Account a2 = new Account(1000);
boolean same = (a1 == a2); // false, different objects
Logical Operators
| Operator | Name |
|---|---|
& |
non-short-circuit AND |
&& |
short-circuit AND |
| ` | ` |
| ` | |
! |
NOT |
^ |
XOR |
Bitwise Operators
Operate on integral types.
| Operator | Affect |
|---|---|
<< |
left shift (×2) |
>> |
signed right shift (÷2) |
>>> |
unsigned right shift |
& | ^ ~ |
AND, OR, XOR, NOT |
int n = 8; // 1000
int m = n << 2; // 32 (100000)
Ternary Operator
condition ? expr1 : expr2
int abs = (x >= 0) ? x : -x;
Prefer the ternary operator over simple if-else when readability is not sacrificed.
Reading Input
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
String name = sc.next();
Random Integers
Generate an integer in [a, b]:
int value = (int)(Math.random() * (b - a + 1)) + a;
Control-Flow Examples
Combining Logical Operators
public class LogicDemo {
public static void main(String[] args) {
int z = 40;
boolean x = true;
boolean y = false;
if ((z++ == 40) && (y = true)) { z++; } // z=42
if ((x = false) || (++z == 43)) { z++; } // z=44
System.out.println("z = " + z); // 44
}
}
Maximum of Three Numberss
int a = 10, b = 21, c = -21;
int max = (a >= b && a >= c) ? a :
(b >= a && b >= c) ? b : c;
System.out.println("max = " + max);
Conditional Sum or Product
double x = 12.3, y = 32.1;
System.out.println(
(x > 10.0 && y < 20.0) ? (x + y) : (x * y)
);
Swapping Two Variables
String drink1 = "Sprite";
String drink2 = "Cola";
String temp = drink1;
drink1 = drink2;
drink2 = temp;