Java Operators, Control Flow, and Arrays
Operators
| Priority | Operator | Category | Associativity |
|---|---|---|---|
| 1 | () | Parentheses | Left to right |
| 2 | !, + (unary), - (unary) | Unary operators | Left to right |
| 2 | ~ | Bitwise operator | Right to left |
| 2 | ++, -- | Increment/decrement | Right to left |
| 3 | *, /, % | Arithmetic operators | Left to right |
| 4 | +, - | Arithmetic operators | Left to right |
| 5 | <<, >> | Shift operators | Left to right |
| 6 | >, >=, <, <= | Relational operators | Left to right |
| 7 | ==, != | Relational operators | Left to right |
| 8 | & | Bitwise/logical operator | Left to right |
| 9 | ^ | Bitwise/logical operator | Left to right |
| 10 | Bitwise/logical operator | ||
| 11 | && | Logical operator | Left to right |
| 12 | |||
| 13 | ?: | Conditional operator | Right to left |
| 14 | =, +=, -=, *=, /=, %= | Assignment operators | Right to left |
Arithmetic Operators
Addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
Integer operations yield integer results (int), unless a long is involved, resulting in a long.
Modulus sign matches the dividend: A % B yields a result with the same sign as A.
Negative numbers and floating-point numbers can also be used with modulus.
Comparison Operators
Greater than (>), less than (<), greater than or equal to (>=), less than or equal to (<=), equal to (==), not equal to (!=).
== compares values for primitive data types.
Comparision operators always return a boolean value (true/false).
Increment and Decrement Operators
a++, a--, ++a, --a.
a++ (post-increment): assign a's value first, then increment a.
++a (pre-increment): increment a first, then assign its value.
Logical Operators
Logical AND (&&): true only if both operands are true.
Logical OR (||): true if at least one operand is true.
Logical NOT (!): negates the boolean value.
Short-circuit evaluation: If the result can be determined from the first expression, subsequent exprestions are not evaluated.
Bitwise Operators
Perform operations on binary bits, then convert back to decimal.
Bitwise AND (&)
Convert A and B to binary, align bits, result is 1 only if both bits are 1.
Bitwise OR (|)
Convert A and B to binary, align bits, result is 1 if at least one bit is 1.
Bitwise XOR (^)
Convert A and B to binary, align bits, result is 1 if bits differ.
Bitwise Complement (~)
Flip bits: 0 becomes 1, 1 becomes 0.
int value = 12 & 11; // Bitwise AND
// 1100 (12) & 1011 (11) = 1000 (8)
System.out.println(value); // Output: 8
value = 12 | 11; // Bitwise OR
// 1100 | 1011 = 1111 (15)
System.out.println(value); // Output: 15
value = 12 ^ 11; // Bitwise XOR
// 1100 ^ 1011 = 0111 (7)
System.out.println(value); // Output: 7
value = ~11; // Bitwise complement
// ~1011 (11) = ...11110100 (two's complement) = -12
System.out.println(value); // Output: -12
Shift Operators
Shift operators move bits left or right.
Left Shift (<<)
Shift bits left, discard high bits, fill low bits with 0. Equivalent to multilpying by 2^n.
Example: int r = 20 << 2; // 20 * 4 = 80
Signed Right Shift (>>)
Shift bits right, fill high bits with sign bit (0 for positive, 1 for negative). Equivalent to dividing by 2^n (floor division).
Example: int r = 20 >> 2; // 20 / 4 = 5
Unsigned Right Shift (>>>)
Shift bits right, always fill high bits with 0. For negative numbers, treats them as unsigned, yielding large positive results.
Example: int r = -20 >>> 2; // Large positive value
Shift operators work only on integer types (int, long). byte, short, char are promoted to int before shifting.
Note: & and | can also operate on boolean values, yielding boolean results.
boolean flag = true & false; // false
int x = 12;
int y = 12;
flag = x++ < 12 & y++ > 12; // Evaluates both sides
flag = x++ < 12 && y++ > 12; // Short-circuits if first is false
Difference between & and &&: & is bitwise/logical AND without short-circuiting; && is logical AND with short-circuiting.
Assignment Operators
=, +=, -=, *=, /=, %=
int num = 12;
num += 2; // num = num + 2;
num -= 2;
num *= 2;
num /= 2;
num %= 2; // Assign remainder of num % 2 to num
Conditional Operator
A ? B : C
A is a boolean condition; B and C must be of compatible types. Returns B if A is true, otherwise C.
int output = true ? 11 : 33; // Output: 11
output = 12.2 != 33.99 ? 'a' : 33; // Output: 'a' (char)
System.out.println(true ? 3 : 4.0); // Output: 3.0 (double)
Control Flow
Conditional Statements
if...else if...else...
Order conditions from most to least restrictive for efficiency.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int grade = input.nextInt();
if (grade >= 85) {
System.out.println("Excellent");
} else if (grade >= 70) {
System.out.println("Good");
} else if (grade >= 60) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}
switch...case...default...
Matches a variable's value to a case; executes from that case until break or block end.
Default runs if no case matches. Case and default order can vary but execution follows matching logic.
Supported types: byte, short, int, char, String, Enum.
int month = 8;
switch (month) {
default:
System.out.println("Invalid month");
break;
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
// ... other cases
}
Fall-through: Without break, execution continues to subsequent cases.
int season = scanner.nextInt();
switch (season) {
case 1:
case 2:
case 3:
System.out.println("Spring");
break;
case 4:
case 5:
case 6:
System.out.println("Summer");
break;
// ... other seasons
default:
System.out.println("Error");
}
Loops
while loop
int counter = 'a';
while (counter <= 'd') {
System.out.println((char) counter);
counter++;
}
do-while loop
Executes at least once.
int i = 1;
do {
System.out.println("Condition false");
} while (i > 20);
for loop
for (int n = 0; n < 10; n++) {
System.out.println(n + 1); // Outputs 1 to 10
}
Loops can be interchanged.
Control Statements
break: Exits the loop.
continue: Skips to next iteration.
for (int a = 1; a < 100; a++) {
if (a % 7 == 0) {
continue; // Skip multiples of 7
}
System.out.println(a);
}
Breaking nested loops: Use labels.
outer: for (int i = 0; i < 30; i++) {
middle: for (int j = 0; j < 20; j++) {
inner: for (int k = 0; k < 10; k++) {
if (k == 5) {
break outer;
}
}
}
}
Infinite loop: Condition never false; code after may still run.
Dead loop: No termination; code after never executes.
while (true) {} // Dead loop
for (;;) {} // Infinite loop
Arrays
One-Dimensional Arrays
Definition: Ordered sequence of elements.
// Static initialization
int[] staticArr = {31, 52, 13, 84};
int[] staticArrA = new int[]{23, 45};
// Dynamic initialization
int[] dynamicArr = new int[4]; // Length 4
Limitations: Fixed type and length.
Accessing elements: Index starts at 0.
System.out.println(staticArr[3]); // Output: 84
System.out.println(Arrays.toString(staticArr)); // Output full array
Setting elements:
dynamicArr[1] = 34;
dynamicArr[3] = 99;
// dynamicArr[4] = 8; // ArrayIndexOutOfBoundsException
Array length:
System.out.println(dynamicArr.length); // Output: 4
Two-Dimensional Arrays
Limitations: Number of rows fixed, column lengths can vary.
int[][] matrix = new int[4][2];
matrix[0][1] = 12;
System.out.println(Arrays.deepToString(matrix));
matrix[2] = new int[]{1, 2, 3, 4}; // Variable column length
System.out.println(Arrays.deepToString(matrix));
// Initialize with random values
int[][] randomMatrix = new int[5][4];
for (int row = 0; row < randomMatrix.length; row++) {
for (int col = 0; col < randomMatrix[row].length; col++) {
randomMatrix[row][col] = (int) (Math.random() * 80);
}
}
System.out.println(Arrays.deepToString(randomMatrix));