Skip to content
My Compiler
LoginRegister

Learn Java: a Beginner Tutorial

Follow these lessons in order. Each one has a short explanation and code you can run instantly in My Compiler.

  1. Lesson 1: Hello, World!

    Every language starts here: print a message to the screen to check that everything works.

    public class Main {
        public static void main(String[] args) {
            System.out.println("Hello, World!");
        }
    }
    Open in compiler
  2. Lesson 2: Variables

    Variables store values such as text, whole numbers and decimals so you can reuse them.

    public class Main {
        public static void main(String[] args) {
            String name = "Ada";
            int age = 21;
            double height = 1.75;
            System.out.println(name + " " + age + " " + height);
        }
    }
    Open in compiler
  3. Lesson 3: Conditions

    if / else lets your program choose a path depending on a value.

    public class Main {
        public static void main(String[] args) {
            int age = 18;
            if (age >= 18) {
                System.out.println("Adult");
            } else if (age >= 13) {
                System.out.println("Teenager");
            } else {
                System.out.println("Child");
            }
        }
    }
    Open in compiler
  4. Lesson 4: Loops

    Loops repeat a block of code: use for when you know the count and while when you wait for a condition.

    public class Main {
        public static void main(String[] args) {
            for (int i = 1; i <= 5; i++) {
                System.out.println(i);
            }
            int n = 3;
            while (n > 0) {
                System.out.println("Countdown " + n--);
            }
        }
    }
    Open in compiler
  5. Lesson 5: Functions

    A function packs code into a reusable block that takes inputs and returns a result.

    public class Main {
        static int add(int a, int b) {
            return a + b;
        }
    
        public static void main(String[] args) {
            System.out.println(add(2, 3));
        }
    }
    Open in compiler
  6. Lesson 6: Fibonacci sequence

    Each number is the sum of the two before it. A classic exercise that combines variables, loops and arithmetic.

    public class Main {
        public static void main(String[] args) {
            int a = 0, b = 1;
            for (int i = 0; i < 10; i++) {
                System.out.print(a + " ");
                int next = a + b;
                a = b;
                b = next;
            }
        }
    }
    Open in compiler