Java Summary (Learning Unit 1–4) –
NPRKO151
1. Basic Java Structure
Every program starts in the main method.
File name must match the public class name.
Java is case sensitive.
public class Oefen {
public static void main(String[] args) {
// code
}
}
2. Output (Print)
println() prints and moves to a new line.
print() prints on the same line.
printf() for formatting (e.g. 2 decimal places).
System.out.println("Hallo");
System.out.print("Hallo");
System.out.printf("Price: %.2f", 19.999);
3. Variables and Data Types
int (integer), double (decimal), char (1 character), boolean (true/false), String (text).
Use "" for String and '' for char.
int x = 10;
double y = 2.5;
char c = 'A';
boolean b = true;
String name = "Chris";
4. Operators
Arithmetic: +, -, *, /, %
Comparison: ==, !=, >, <, >=, <=
Logical: && (AND), || (OR), ! (NOT)
Increment/Decrement: x++, x--
5. Input (Scanner)
Import Scanner and create object.
Use nextInt(), nextDouble(), next(), nextLine().
IMPORTANT: Use nextLine() after nextInt() to consume the newline.
import java.util.Scanner;
Scanner input = new Scanner(System.in);
int x = input.nextInt();
input.nextLine();
String name = input.nextLine();
6. If / Else
Used for decision making.
Can use if, else if, and else.
Do not put ; after if.
if (x > 10) {
System.out.println("Big");
} else {
System.out.println("Small");
}
7. Switch
Used for more than one fixed choice.
Remember break; and default.
switch (dag) {
case 1: System.out.println("Monday"); break;
default: System.out.println("Unknown");
}
8. Math Functions
Constants: Math.PI, Math.E
Pow & sqrt: Math.pow(), Math.sqrt()
Rounding: round(), ceil(), floor()
Random: Math.random()
Trig uses radians (use Math.toRadians()).
Math.sqrt(25);
Math.pow(2,3);
Math.round(4.6);
Math.random();
Math.sin(Math.toRadians(90));
9. Strings and Characters
String methods: length(), toUpperCase(), equals(), charAt()
Character methods: isDigit(), isLetter()
String name = "Chris";
name.length();
name.toUpperCase();
Character.isDigit('5');
10. Common Mistakes (Very Important)
Math.pi instead of Math.PI
nextInt() + nextLine() problem
Wrong quotes ('' vs Verkeerde quotes ('' vs "")quot;Verkeerde quotes ('' vs "")quot;)
if(...) ; fout
Class name and file name do not match