Types, Variables, Operators & Control Flow
Types, Variables, Operators & Control Flow
Java's Type System: Primitives vs. References
Java has two categories of types:
Primitive types — stored by value on the stack:
byte b = 127; // 8-bit integer: -128 to 127
short s = 32767; // 16-bit integer: -32,768 to 32,767
int i = 2_147_483_647; // 32-bit integer: ±2.1 billion (default integer type)
long l = 9_223_372_036_854_775_807L; // 64-bit: note the L suffix
float f = 3.14f; // 32-bit float: note the f suffix
double d = 3.141592653589793; // 64-bit float (default floating-point type)
boolean flag = true; // true or false only
char c = 'A'; // 16-bit Unicode character (note single quotes)Underscores in numeric literals (2_147_483_647) are legal and improve readability — they don't affect the value.
Reference types — objects stored on the heap; variables hold a reference (pointer):
String name = "Jordan"; // most common reference type
int[] scores = {95, 87, 91}; // array of primitives
Integer boxed = 42; // Integer is the wrapper class for int---
Type Casting
Widening (safe, automatic — smaller type into larger type):
int i = 100;
long l = i; // automatic widening
double d = i; // automatic wideningNarrowing (potentially lossy — requires explicit cast):
double pi = 3.14159;
int truncated = (int) pi; // → 3 (decimal portion cut off, not rounded)
long big = 10_000_000_000L;
int overflow = (int) big; // → unpredictable — value may overflowAlways check the range before narrowing. Use Math.round() if you need rounding instead of truncation.
---
Operators
Arithmetic:
int a = 17, b = 5;
System.out.println(a + b); // 22
System.out.println(a - b); // 12
System.out.println(a * b); // 85
System.out.println(a / b); // 3 (integer division — decimal dropped)
System.out.println(a % b); // 2 (modulus: remainder of 17/5)
double x = 17.0, y = 5.0;
System.out.println(x / y); // 3.4 (floating-point division)Comparison and Logical:
boolean t = (5 > 3); // true
boolean f = (5 == 3); // false
boolean ne = (5 != 3); // true
boolean and = (true && false); // false (short-circuit: stops at first false)
boolean or = (false || true); // true (short-circuit: stops at first true)
boolean not = !true; // falseIncrement/Decrement:
int n = 5;
n++; // n = 6 (post-increment: use value, then increment)
++n; // n = 7 (pre-increment: increment, then use value)
n--; // n = 6
int result = n++; // result = 6, then n becomes 7
int result2 = ++n; // n becomes 8, then result2 = 8---
Control Flow
if / else if / else:
int score = 87;
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else {
grade = "F";
}
System.out.println("Grade: " + grade); // "Grade: B"Ternary (inline if/else):
String status = score >= 60 ? "Pass" : "Fail";Switch Expression (Java 14+):
int day = 3;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
default -> "Weekend";
};
System.out.println(dayName); // "Wednesday"The arrow syntax (->) eliminates fall-through. Use it over the old case x: break; style in new code.
---
Loops
for loop (index-based):
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}Enhanced for loop (for-each):
int[] scores = {92, 85, 78, 96, 88};
int total = 0;
for (int score : scores) {
total += score;
}
double average = (double) total / scores.length;
System.out.printf("Average: %.1f%n", average); // Average: 87.8while loop:
int n = 1;
while (n <= 10) {
System.out.print(n + " ");
n++;
}
// Output: 1 2 3 4 5 6 7 8 9 10do-while (executes at least once):
int attempts = 0;
do {
System.out.println("Attempt: " + (++attempts));
} while (attempts < 3);
// Always runs at least once, even if condition starts falsebreak and continue:
for (int i = 0; i < 10; i++) {
if (i == 3) continue; // skip 3
if (i == 7) break; // stop at 7
System.out.print(i + " ");
}
// Output: 0 1 2 4 5 6---
Autoboxing and Wrapper Classes
Java's collections can only hold objects, not primitives. Autoboxing handles the conversion automatically:
Integer boxedInt = 42; // autoboxing: int → Integer
int primitive = boxedInt; // unboxing: Integer → int
// Common operations on wrapper classes:
int max = Integer.MAX_VALUE; // 2147483647
int parsed = Integer.parseInt("123"); // parse String to int
String asString = Integer.toString(42); // int to StringBe careful with == on Integer objects — it compares references, not values. Always use .equals() for object comparison:
Integer a = 200, b = 200;
System.out.println(a == b); // false (different objects above cache range)
System.out.println(a.equals(b)); // true (always use this for object equality)