Syntax, Control Flow and Arrays
Variables and operators
int count = 10;
final double TAX = 0.18; // constant
var message = "inferred as String"; // local type inference (Java 10+)
int quotient = 7 / 2; // 3 (integer division)
double ratio = 7 / 2.0; // 3.5
boolean both = count > 5 && count < 20;
Conditionals
if (count > 10) {
System.out.println("big");
} else if (count == 10) {
System.out.println("exact");
} else {
System.out.println("small");
}
String size = switch (count) { // switch expression (Java 14+)
case 1, 2, 3 -> "tiny";
case 10 -> "ten";
default -> "other";
};
Loops
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
int[] nums = {3, 1, 4, 1, 5};
for (int n : nums) { // enhanced for
System.out.println(n);
}
int n = 3;
while (n > 0) { n--; }
do { n++; } while (n < 3);
break leaves a loop; continue skips to the next iteration.
Arrays
int[] scores = new int[5]; // default values are 0
int[][] grid = new int[3][4];
scores[0] = 90;
System.out.println(scores.length);
java.util.Arrays.sort(nums);
System.out.println(java.util.Arrays.toString(nums));
Strings
String s = "PrepVerse";
s.length(); // 9
s.substring(0, 4); // "Prep"
s.toUpperCase();
s.equals("PrepVerse"); // use equals, not ==
String.join(", ", "a", "b");
StringBuilder sb = new StringBuilder(); // for repeated concatenation
sb.append("a").append("b");
CAUTION
== compares references for objects. Always use .equals() to compare String contents.
Loading Comments...