Java -- Syntax Basics
Variables, final, var
int n = 42;
final int MAX = 256;
String s = "ate";
var x = 3.14; // Java 10+ local type inference
Integer boxed = null;
Methods, static, overloads
int add(int a, int b) { return a + b; }
static void main(String[] args) { }
void log(String msg) { }
Classes, interfaces, records (Java 16+)
class DUT {
private final String id;
DUT(String id) { [Link] = id; }
boolean test() { return true; }
}
interface RunnableTest { boolean run(); }
record Point(int x, int y) { }
Branching, switch (modern arrow)
if (x < 0) {
} else if (x == 0) {
} else {
}
switch (x) {
case 1 -> [Link]("one");
case 2 -> [Link]("two");
default -> [Link]("other");
}
Loops, enhanced for
for (int i = 0; i < n; i++) { }
for (int v : arr) { }
while (cond) { }
do { } while (cond);
Collections ([Link])
import [Link].*;
List<Integer> list = new ArrayList<>();
[Link](1);
Map<String, Integer> map = new HashMap<>();
[Link]("k", 10);
Set<String> set = new HashSet<>();
Exceptions
try {
throw new IOException("bad");
} catch (IOException e) {
[Link]();
} finally {
cleanup();
}
Packages, imports
package [Link];
import [Link];
import static [Link];
// line comment
/* block comment */
Streams (quick)
import [Link].*;
List<String> xs = [Link]("a", "b");
long count = [Link]()
.filter(s -> [Link]("a"))