Java Fundamentals for Beginners: Syntax, OOP and Collections
Learn Java from zero: the JDK and JVM, variables and types, control flow, methods and arrays, classes and inheritance, exceptions and collections, with quizzes.
Study this lesson with its quizzes on Brainbotox →
What is Java? JDK, JVM and your first program
Java is a statically typed, object-oriented language whose source code is compiled to bytecode and run by the Java Virtual Machine (JVM), so the same compiled program runs on Windows, Linux and macOS.
JDK, JRE and JVM
| Name | What it is |
|---|---|
| JVM | The virtual machine that executes bytecode and manages memory |
| JRE | The JVM plus the standard libraries, enough to run programs |
| JDK | The JRE plus development tools such as the compiler javac |
From source to execution
- You write
Hello.java. javac Hello.javacompiles it to bytecode inHello.class.java Hellostarts the JVM, which loads and runs the class.- The JVM's just-in-time (JIT) compiler turns hot bytecode into machine code, and the garbage collector frees unused objects.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}public static void main(String[] args). A public class must be in a file with the same name: Hello in Hello.java.Good to know
- "Write once, run anywhere": bytecode is portable, the JVM is specific to each platform.
- Every statement ends with a semicolon, and Java is case-sensitive.
- A new Java version ships every six months. Long Term Support (LTS) versions such as 17, 21 and 25 are the usual choice in companies.
- Real projects are built with Maven or Gradle, which also download libraries.
Check yourself
- What does javac produce?
- Which component executes Java bytecode?
- What does the JDK contain that the JRE does not?
- What is the signature of the Java entry point?
- A public class named Hello must be declared in a file named Hello.java.
- Why is compiled Java portable across operating systems?
Java variables, primitive types and operators
Java has eight primitive types that hold values directly, and reference types (objects such as String) whose variables hold a reference to an object.
The eight primitives
| Type | Holds | Example |
|---|---|---|
byte, short, int, long | Whole numbers of 8, 16, 32, 64 bits | long big = 5_000_000_000L; |
float, double | Floating point of 32, 64 bits | double pi = 3.14; |
char | One UTF-16 character | char c = 'A'; |
boolean | true or false | boolean ok = true; |
Declaring variables
int age = 30; String name = "Ada"; // String is a class, not a primitive var count = 10; // local type inference: still an int final double VAT = 0.2; // cannot be reassigned
Operators and conversions
int a = 7 / 2; // 3: integer division
int r = 7 % 2; // 1: remainder
double d = 7 / 2.0; // 3.5
int n = (int) 3.9; // 3: a cast truncates
int p = Integer.parseInt("42");Strings and equality
String s1 = new String("hi");
String s2 = new String("hi");
System.out.println(s1 == s2); // false: different objects
System.out.println(s1.equals(s2)); // true: same text== compares references. Always compare strings with .equals().Strings are immutable: s.toUpperCase() returns a new string.
Wrapper classes
Each primitive has an object form: Integer, Double, Boolean. Java converts automatically between them (autoboxing). A wrapper can be null, a primitive cannot.
Check yourself
- How many primitive types does Java have?
- How should you compare the text of two String objects?
- What is the value of 7 / 2 in Java?
- What does final mean on a variable?
- String is one of Java's primitive types.
- What is autoboxing?
Java control flow: if, switch and loops
Control flow statements choose which code runs and how often: if and switch for decisions, and for, while and do while for repetition.
if and the ternary operator
if (score >= 90) {
grade = "A";
} else if (score >= 70) {
grade = "B";
} else {
grade = "C";
}
String label = score >= 50 ? "pass" : "fail";The condition must be a boolean. && and || short-circuit: the right side is skipped when the left side decides the result.
switch
switch (day) { // classic form
case "Sat":
case "Sun":
System.out.println("Weekend");
break;
default:
System.out.println("Weekday");
}break makes execution fall through into the next case.String kind = switch (day) { // switch expression (Java 14+)
case "Sat", "Sun" -> "Weekend";
default -> "Weekday";
};The arrow form has no fall-through and returns a value.
Loops
for (int i = 0; i < 3; i++) { } // 0, 1, 2
for (String n : names) { } // enhanced for: every element
while (k > 0) { k--; } // may run zero times
do { k++; } while (k < 5); // runs at least oncebreak leaves the loop. continue jumps to the next iteration.Check yourself
- What happens in a classic Java switch when a case has no break?
- Which loop always runs its body at least once?
- What does continue do?
- What is true of the arrow form case "Sat" -> ...?
- In a != null && a.length() > 0, what happens when a is null?
- What does for (String n : names) do?
Java methods, arrays and strings
A method is a named block of code with typed parameters and a return type, and Java always passes arguments by value. Arrays are fixed-size containers of one type.
Methods
static int add(int a, int b) {
return a + b;
}
static void greet(String name) { // void: returns nothing
System.out.println("Hello " + name);
}
static int sum(int... nums) { // varargs
int total = 0;
for (int n : nums) total += n;
return total;
}Overloading: several methods can share a name if their parameter lists differ.
Pass by value
static void change(int x, int[] arr) {
x = 99; // changes the local copy only
arr[0] = 99; // changes the caller's array
}Arrays
int[] nums = {4, 8, 15};
int first = nums[0]; // indexes start at 0
int size = nums.length; // a field, no parentheses
int[] zeros = new int[5]; // filled with 0nums[3] here throws ArrayIndexOutOfBoundsException. The size of an array never changes.Useful String methods
| Call | Result |
|---|---|
"Hello".length() | 5 |
"Hello".charAt(0) | 'H' |
"Hello".substring(1, 3) | "el" |
"a,b".split(",") | ["a", "b"] |
" hi ".trim() | "hi" |
StringBuilder and append(). Using += creates a new String object on every pass.Check yourself
- How does Java pass arguments to methods?
- A method receives an int[] and sets arr[0] = 99. What does the caller see?
- How do you get the number of elements of an array nums?
- What is method overloading?
- Which class should you use to build a long string in a loop?
- What does "Hello".substring(1, 3) return?
Java classes, objects, inheritance and interfaces
A class is a blueprint with fields (data) and methods (behaviour), and an object is an instance created with new. Java's object-oriented model rests on encapsulation, inheritance and polymorphism.
A class
public class BankAccount {
private double balance; // hidden state
private final String owner;
public BankAccount(String owner) { // constructor
this.owner = owner;
}
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("Must be positive");
balance += amount;
}
public double getBalance() { return balance; }
}
BankAccount acc = new BankAccount("Ada");
acc.deposit(100);Access modifiers
| Modifier | Visible from |
|---|---|
private | The same class only |
| (none) | The same package: "package-private", the default |
protected | The package and subclasses |
public | Everywhere |
Inheritance and polymorphism
class Animal {
String speak() { return "..."; }
}
class Dog extends Animal {
@Override
String speak() { return "Woof"; }
}
Animal a = new Dog();
System.out.println(a.speak()); // WoofDog), not the type of the variable (Animal). A class can extend only one class but implement many interfaces.Abstract classes and interfaces
abstract class Shape { abstract double area(); }
interface Printable { void print(); }
class Circle extends Shape implements Printable {
double r;
double area() { return Math.PI * r * r; }
public void print() { System.out.println(area()); }
}static and Object
A static member belongs to the class, not to an instance: Math.sqrt(9). Every class inherits from Object, which provides toString(), equals() and hashCode(). Override them to print and compare your objects meaningfully.
Check yourself
- What is the default access level of a Java member with no modifier?
- How many classes can a Java class extend?
- Animal a = new Dog(); a.speak(); where Dog overrides speak. Which version runs?
- What is the purpose of @Override?
- You can create an instance of an abstract class with new.
- Which class is the root of every Java class?
Java exceptions and the basic collections
Java signals errors with exceptions, handled by try, catch and finally, and stores groups of objects in collections such as ArrayList, HashMap and HashSet.
Checked and unchecked exceptions
| Kind | Rule | Examples |
|---|---|---|
| Checked | The compiler forces you to catch it or declare it with throws | IOException, SQLException |
| Unchecked | Subclass of RuntimeException; no obligation | NullPointerException, IllegalArgumentException, ArrayIndexOutOfBoundsException |
try {
int n = Integer.parseInt(text);
} catch (NumberFormatException e) {
System.out.println("Not a number");
} finally {
System.out.println("Always runs");
}try-with-resources
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
} // reader is closed automaticallythrow raises an exception. throws in a method signature declares that the method may let one escape.ArrayList
List<String> names = new ArrayList<>();
names.add("Ada");
String first = names.get(0);
int size = names.size();HashMap and HashSet
Map<String, Integer> ages = new HashMap<>();
ages.put("Ada", 36);
Integer age = ages.get("Bob"); // null when the key is missing
int safe = ages.getOrDefault("Bob", 0);
Set<String> tags = new HashSet<>();
tags.add("java"); tags.add("java"); // size is 1: no duplicatesList<Integer>, not List<int>. Removing elements from a list inside a for-each loop over it throws ConcurrentModificationException; use removeIf.Check yourself
- What must you do with a checked exception?
- Which of these is an unchecked exception?
- What does try-with-resources guarantee?
- What does map.get(key) return when the key is absent from a HashMap?
- Which collection refuses duplicate elements?
- List<int> is a valid Java type.