Brainbotox · Lessons · Exams

Java Fundamentals for Beginners: Syntax, OOP and Collections

by lazizanie · Programming · Java · English

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

NameWhat it is
JVMThe virtual machine that executes bytecode and manages memory
JREThe JVM plus the standard libraries, enough to run programs
JDKThe JRE plus development tools such as the compiler javac

From source to execution

  1. You write Hello.java.
  2. javac Hello.java compiles it to bytecode in Hello.class.
  3. java Hello starts the JVM, which loads and runs the class.
  4. 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!");
    }
}
The entry point is 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

  1. What does javac produce?
  2. Which component executes Java bytecode?
  3. What does the JDK contain that the JRE does not?
  4. What is the signature of the Java entry point?
  5. A public class named Hello must be declared in a file named Hello.java.
  6. Why is compiled Java portable across operating systems?

Take the quiz on Brainbotox

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

TypeHoldsExample
byte, short, int, longWhole numbers of 8, 16, 32, 64 bitslong big = 5_000_000_000L;
float, doubleFloating point of 32, 64 bitsdouble pi = 3.14;
charOne UTF-16 characterchar c = 'A';
booleantrue or falseboolean 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
For objects, == 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.

Local variables must be assigned before use. Fields get default values: 0, false or null.

Check yourself

  1. How many primitive types does Java have?
  2. How should you compare the text of two String objects?
  3. What is the value of 7 / 2 in Java?
  4. What does final mean on a variable?
  5. String is one of Java's primitive types.
  6. What is autoboxing?

Take the quiz on Brainbotox

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");
}
In the classic form, forgetting 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 once
break leaves the loop. continue jumps to the next iteration.

Check yourself

  1. What happens in a classic Java switch when a case has no break?
  2. Which loop always runs its body at least once?
  3. What does continue do?
  4. What is true of the arrow form case "Sat" -> ...?
  5. In a != null && a.length() > 0, what happens when a is null?
  6. What does for (String n : names) do?

Take the quiz on Brainbotox

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
}
Java copies the argument. For a primitive, the value is copied. For an object, the reference is copied, so the method can modify the object but cannot make the caller's variable point elsewhere.

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 0
Reading nums[3] here throws ArrayIndexOutOfBoundsException. The size of an array never changes.

Useful String methods

CallResult
"Hello".length()5
"Hello".charAt(0)'H'
"Hello".substring(1, 3)"el"
"a,b".split(",")["a", "b"]
" hi ".trim()"hi"
To build a string in a loop, use StringBuilder and append(). Using += creates a new String object on every pass.

Check yourself

  1. How does Java pass arguments to methods?
  2. A method receives an int[] and sets arr[0] = 99. What does the caller see?
  3. How do you get the number of elements of an array nums?
  4. What is method overloading?
  5. Which class should you use to build a long string in a loop?
  6. What does "Hello".substring(1, 3) return?

Take the quiz on Brainbotox

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

ModifierVisible from
privateThe same class only
(none)The same package: "package-private", the default
protectedThe package and subclasses
publicEverywhere

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());   // Woof
The method that runs depends on the real type of the object (Dog), 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

  1. What is the default access level of a Java member with no modifier?
  2. How many classes can a Java class extend?
  3. Animal a = new Dog(); a.speak(); where Dog overrides speak. Which version runs?
  4. What is the purpose of @Override?
  5. You can create an instance of an abstract class with new.
  6. Which class is the root of every Java class?

Take the quiz on Brainbotox

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

KindRuleExamples
CheckedThe compiler forces you to catch it or declare it with throwsIOException, SQLException
UncheckedSubclass of RuntimeException; no obligationNullPointerException, 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 automatically
throw 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 duplicates
Collections hold objects, not primitives: write List<Integer>, not List<int>. Removing elements from a list inside a for-each loop over it throws ConcurrentModificationException; use removeIf.

Check yourself

  1. What must you do with a checked exception?
  2. Which of these is an unchecked exception?
  3. What does try-with-resources guarantee?
  4. What does map.get(key) return when the key is absent from a HashMap?
  5. Which collection refuses duplicate elements?
  6. List<int> is a valid Java type.

Take the quiz on Brainbotox