DOCODIVE
Beginner Free Learning Path

Java Beginner Guide

Build a strong Java foundation from zero with 20 beginner lessons. Learn variables, strings, loops, arrays, classes, methods, and more — each with code, exact output, and official Oracle documentation links.

3–4 weeks 20 lessons 3 projects 1 capstone No experience required
Start Learning
01

What is Java & The JVM

Java is a compiled, object-oriented language. You write .java source files, the compiler turns them into bytecode (.class files), and the Java Virtual Machine (JVM) runs that bytecode on any platform. This is why Java's motto is 'Write Once, Run Anywhere'.

Java
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello from Java!");
    }
}
Every Java program needs a class (Main). The main method is the entry point — Java always starts here. System.out.println() prints text to the console. The semicolon ends each statement, and curly braces define code blocks.
terminal
Hello from Java!
When the JVM runs this program, it finds the main method and executes println(), which prints the exact text inside the quotes.
02

Setting Up: JDK, IDE & Hello World

To write Java you need the JDK (Java Development Kit). You can code in any text editor or an IDE like IntelliJ IDEA or Eclipse. The smallest runnable program is a class with a main method — the famous 'Hello World'.

Java
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
The class is named Hello, and the file must be named Hello.java. public means the class is accessible. static means main can run without creating an object. void means main returns nothing. The args parameter holds command-line arguments.
terminal
Hello, World!
After compiling with 'javac Hello.java' and running with 'java Hello', the JVM calls main and prints the message. This is the standard first program in Java.
03

Variables & Data Types

Java is statically typed — every variable must declare its type. The main primitive types are int (whole numbers), double (decimals), char (single character), boolean (true/false), and the object type String (text).

Java
public class Main {
    public static void main(String[] args) {
        int age = 25;
        double price = 19.99;
        char grade = 'A';
        boolean isStudent = true;
        String name = "Ali";
        System.out.println(name + " is " + age + " years old.");
    }
}
Each variable declares its type first, then a name, then a value. int holds whole numbers, double holds decimals, char holds one character (in single quotes), boolean holds true/false, and String holds text (in double quotes). The + operator joins strings.
terminal
Ali is 25 years old.
The + operator concatenated the String values. The int variable age was automatically converted to text when joined with the string, so the final line reads naturally.
04

Operators

Java operators work like math. Arithmetic operators (+, -, *, /, %) do calculations. Relational operators (==, !=, >, <) compare values. Logical operators (&&, ||, !) combine boolean conditions.

Java
public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = 3;
        System.out.println(a + b);
        System.out.println(a / b);
        System.out.println(a % b);
        System.out.println(a > b);
        System.out.println(a == 10 && b == 3);
    }
}
a + b adds (13). a / b does integer division — both are ints, so the result is 3, not 3.333. a % b gives the remainder (1). a > b compares (true). a == 10 && b == 3 checks both conditions with logical AND (true).
terminal
13 3 1 true true
Integer division truncates the decimal. Modulo returns the remainder after division. The comparison and logical expressions both evaluated to true because both conditions held.
05

Strings & String Methods

String is Java's most-used class. It has many built-in methods: length() returns the character count, toUpperCase() and toLowerCase() change case, and charAt() gets a character at an index.

Java
public class Main {
    public static void main(String[] args) {
        String text = "Hello Java";
        System.out.println(text.length());
        System.out.println(text.toUpperCase());
        System.out.println(text.charAt(0));
        System.out.println(text.substring(0, 5));
    }
}
length() returns 10 (characters). toUpperCase() returns the string in capitals. charAt(0) returns the first character 'H'. substring(0, 5) returns characters from index 0 up to (not including) 5, which is 'Hello'.
terminal
10 HELLO JAVA H Hello
Each method returned a new value. Strings are immutable — the methods do not change the original text, they return new strings. substring's second index is exclusive, which is why (0,5) gave 'Hello'.
06

Taking Input with Scanner

The Scanner class reads user input from the keyboard. You create a Scanner object, then use methods like nextLine() for text and nextInt() for numbers. Scanner lives in java.util, so it must be imported.

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = sc.nextLine();
        System.out.println("Hello, " + name);
        sc.close();
    }
}
import java.util.Scanner makes Scanner available. new Scanner(System.in) creates a scanner that reads from the keyboard. nextLine() reads a full line of text. Finally, sc.close() releases the resource.
terminal
Enter your name: Ali Hello, Ali
The program printed the prompt, waited for the user to type 'Ali' and press Enter, then printed the greeting using the input. This is how interactive Java programs work.
07

Conditionals: if/else & switch

if and else let your program make decisions. switch compares one value against several cases. Both control which code block runs based on conditions.

Java
public class Main {
    public static void main(String[] args) {
        int score = 85;
        if (score >= 90) {
            System.out.println("A");
        } else if (score >= 70) {
            System.out.println("B");
        } else {
            System.out.println("C");
        }
    }
}
The first if checks if score is 90 or more — false for 85. The else if checks if score is 70 or more — true, so 'B' prints. Because a match was found, the final else block is skipped.
terminal
B
Only one block runs in an if/else chain — the first condition that is true. 85 is not high enough for A but is high enough for B.
08

Loops: for, while, do-while

Loops repeat code. for is used when you know the count. while repeats while a condition is true. do-while always runs at least once because the condition is checked after the body.

Java
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}
The for loop has three parts: int i = 1 starts the counter, i <= 5 is the condition that keeps it running, and i++ increments i after each iteration. println prints the current value of i each time.
terminal
1 2 3 4 5
The loop ran five times, printing 1 through 5, each on its own line. Once i became 6, the condition i <= 5 was false and the loop stopped.
09

Arrays: Basics

An array stores multiple values of the same type in one variable. Arrays have a fixed length set at creation, and elements are accessed by index starting from 0.

Java
public class Main {
    public static void main(String[] args) {
        int[] nums = {10, 20, 30, 40};
        System.out.println(nums.length);
        System.out.println(nums[0]);
        System.out.println(nums[3]);
    }
}
int[] declares an integer array. The curly braces initialize it with four values. nums.length returns 4. nums[0] accesses the first element (10), and nums[3] accesses the last element (40).
terminal
4 10 40
The array holds four values, so length is 4. Index 0 gives the first element and index 3 gives the last, since indexing starts at 0.
10

ArrayList (Dynamic Array)

Unlike regular arrays, ArrayList can grow and shrink. It is part of java.util and provides methods like add(), get(), and size(). ArrayList only stores objects, not primitives directly.

Java
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Ali");
        names.add("Sara");
        System.out.println(names.size());
        System.out.println(names.get(0));
    }
}
ArrayList<String> creates a list that holds strings. add() appends items. size() returns the current count (2). get(0) retrieves the first item. No fixed size was declared — the list grows as needed.
terminal
2 Ali
Two items were added, so size is 2. get(0) returned the first added name. This shows ArrayList's dynamic nature compared to fixed arrays.
11

Methods

Methods are reusable blocks of code inside a class. A method has a return type, a name, and optional parameters. void means the method returns nothing.

Java
public class Main {
    static void greet(String name) {
        System.out.println("Hello, " + name);
    }

    public static void main(String[] args) {
        greet("Ali");
        greet("Sara");
    }
}
greet is a method that takes a String parameter and returns nothing (void). It prints a greeting using the parameter. main calls greet twice with different names. static means greet can be called without creating an object.
terminal
Hello, Ali Hello, Sara
Each call to greet printed a greeting with the passed name. Reusing one method for two different inputs shows why methods are powerful.
12

Method Parameters & Return

Parameters pass data into a method. The return keyword sends a value back to the caller. The return type in the method signature must match the returned value's type.

Java
public class Main {
    static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        int result = add(5, 3);
        System.out.println(result);
    }
}
add takes two int parameters and has int as its return type. return a + b sends the sum back. In main, add(5, 3) evaluates to 8, which is stored in result and printed.
terminal
8
The method computed 5 + 3 and returned 8. The caller stored that returned value in result. The method does not print anything itself — it only returns.
13

Classes & Objects

A class is a blueprint. An object is an instance of that class. Classes define fields (data) and methods (behavior). You create objects with the new keyword.

Java
class Car {
    String brand;
    int year;

    void info() {
        System.out.println(brand + " " + year);
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.brand = "Toyota";
        myCar.year = 2020;
        myCar.info();
    }
}
Car is a class with two fields (brand, year) and a method (info). new Car() creates a Car object. The object's fields are assigned values, then info() prints them.
terminal
Toyota 2020
The info() method read the object's fields and printed them. This demonstrates how objects bundle data (fields) and behavior (methods) together.
14

Constructors

A constructor initializes an object when it is created. It has the same name as the class and no return type. Constructors can accept parameters to set initial field values.

Java
class Person {
    String name;
    int age;

    Person(String n, int a) {
        name = n;
        age = a;
    }
}

public class Main {
    public static void main(String[] args) {
        Person p = new Person("Ali", 25);
        System.out.println(p.name + " " + p.age);
    }
}
Person has a constructor that takes a name and age and assigns them to the fields. new Person("Ali", 25) calls that constructor, setting name to 'Ali' and age to 25.
terminal
Ali 25
The constructor ran during object creation and initialized both fields. This is the standard way to set up an object's initial state.
15

Access Modifiers (public, private)

Access modifiers control visibility. public means accessible from anywhere. private means only accessible inside the same class. This is the foundation of encapsulation — hiding internal data.

Java
class BankAccount {
    private double balance;

    void deposit(double amount) {
        balance += amount;
    }

    double getBalance() {
        return balance;
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount acc = new BankAccount();
        acc.deposit(100);
        System.out.println(acc.getBalance());
    }
}
balance is private, so it cannot be accessed directly from outside the class. deposit() and getBalance() are the only ways to change and read it. In main, deposit adds 100 and getBalance returns the updated value.
terminal
100.0
The balance started at 0.0 (default for double), then 100 was added. The private field was protected — external code had to use the methods.
16

Getters & Setters

Getters and setters are methods that read and modify private fields. They give controlled access to data, allowing validation before a value is set. This is a core Java convention.

Java
class Student {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String n) {
        if (n.length() > 0) {
            name = n;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student();
        s.setName("Ali");
        System.out.println(s.getName());
    }
}
getName() returns the private name field. setName() only assigns a value if it is not empty — that is validation. The Main class uses these public methods instead of touching name directly.
terminal
Ali
setName stored 'Ali' because it passed the length check. getName returned it. The private field was safely accessed only through the getter/setter.
17

Static vs Instance Members

Instance members belong to each object. Static members belong to the class itself and are shared by all objects. You access static members with the class name, and instance members with an object.

Java
class Counter {
    static int count = 0;
    int instanceCount = 0;

    void increment() {
        count++;
        instanceCount++;
    }
}

public class Main {
    public static void main(String[] args) {
        Counter a = new Counter();
        Counter b = new Counter();
        a.increment();
        b.increment();
        System.out.println("Static: " + Counter.count);
        System.out.println("Instance A: " + a.instanceCount);
        System.out.println("Instance B: " + b.instanceCount);
    }
}
count is static — shared by all Counter objects. instanceCount is an instance field — each object has its own copy. Both a and b call increment(), which increases the shared static count twice and each object's own instanceCount once.
terminal
Static: 2 Instance A: 1 Instance B: 1
The static count reached 2 because both objects shared it. Each object's instanceCount stayed at 1 because those are separate copies. This is the key difference between static and instance.
18

Wrapper Classes

Each primitive type has a wrapper class: int → Integer, double → Double, char → Character, boolean → Boolean. Wrappers let primitives be used where objects are required, like in ArrayList, and provide utility methods like parseInt().

Java
public class Main {
    public static void main(String[] args) {
        String text = "42";
        int num = Integer.parseInt(text);
        Integer obj = num;
        System.out.println(num + 10);
        System.out.println(obj.toString());
    }
}
Integer.parseInt() converts the string '42' into the int 42. num + 10 is arithmetic. Integer obj = num uses autoboxing — Java automatically wraps the primitive into an Integer object. obj.toString() converts it back to text.
terminal
52 42
The parsed int was used in addition (42 + 10 = 52). Autoboxing made the int usable as an object, and toString returned the text form. Wrappers bridge the gap between primitives and objects.
19

Type Casting

Casting converts one type to another. Widening (int to double) happens automatically. Narrowing (double to int) requires an explicit cast because data may be lost.

Java
public class Main {
    public static void main(String[] args) {
        int a = 10;
        double b = a;
        double c = 9.99;
        int d = (int) c;
        System.out.println(b);
        System.out.println(d);
    }
}
double b = a is widening — automatic, no cast needed. int d = (int) c is narrowing — the (int) cast truncates 9.99 to 9, dropping the decimal. The cast explicitly tells Java to allow the potential data loss.
terminal
10.0 9
The int became a double (10.0). The double became an int (9) but lost the .99 — that is why explicit casting is required for narrowing.
20

Beginner Recap + Mini Projects

You now know Java basics, variables, operators, strings, input, conditionals, loops, arrays, ArrayList, methods, classes, constructors, access modifiers, getters/setters, static members, wrappers, and casting. Apply them in three mini projects: (1) Calculator, (2) Even/Odd Checker, (3) Simple Grade Calculator.

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = sc.nextInt();
        if (n % 2 == 0) {
            System.out.println(n + " is even");
        } else {
            System.out.println(n + " is odd");
        }
        sc.close();
    }
}
Scanner reads an integer from the user. The modulo operator (%) checks if n is divisible by 2 — if the remainder is 0, it is even. The if/else prints the appropriate message.
terminal
Enter a number: 7 7 is odd
7 divided by 2 leaves remainder 1, so the else branch ran and printed '7 is odd'. This is the Even/Odd Checker project in action.

Java Beginner Projects

Apply variables, loops, conditionals, Scanner, and methods. Click each project to open its full guide.

About this project

The computer picks a secret number from 1 to 100. You get 7 attempts to find it. After each guess, the program tells you whether to go higher or lower.

What you'll practice
Scanner Random while loop if / else variables
Step-by-step: How it works
  1. Random.nextInt(100) + 1 generates a secret number from 1 to 100.
  2. A while loop runs while attempts remain.
  3. Each turn reads a guess using Scanner.nextInt().
  4. If the guess is low, the program says "too low"; if high, "too high".
  5. The loop breaks when the guess matches the secret number.
  6. If attempts run out, the secret number is revealed.
Java
import java.util.Random;
import java.util.Scanner;

public class NumberGuessing {
    public static void main(String[] args) {
        Random random = new Random();
        Scanner sc = new Scanner(System.in);

        int secret = random.nextInt(100) + 1;
        int attempts = 7;

        System.out.println("Guess the secret number between 1 and 100.");
        System.out.println("You have " + attempts + " attempts.\n");

        while (attempts > 0) {
            System.out.print("Your guess: ");
            int guess = sc.nextInt();
            attempts--;

            if (guess == secret) {
                System.out.println("\nCorrect! The secret number is " + secret + ".");
                break;
            } else if (guess < secret) {
                System.out.println("Too low. " + attempts + " attempt(s) left.\n");
            } else {
                System.out.println("Too high. " + attempts + " attempt(s) left.\n");
            }
        }

        if (attempts == 0) {
            System.out.println("Out of attempts! The secret number was " + secret + ".");
        }

        sc.close();
    }
}
Sample Run
terminal
Guess the secret number between 1 and 100. You have 7 attempts. Your guess: 50 Too high. 6 attempt(s) left. Your guess: 25 Too low. 5 attempt(s) left. Your guess: 37 Correct! The secret number is 37.

About this project

Convert temperatures between Celsius and Fahrenheit. The user picks a direction and enters a value, then the program calculates and prints the result.

What you'll practice
methods double Scanner switch return
Step-by-step: How it works
  1. The user picks a direction: C to F or F to C.
  2. Scanner.nextDouble() reads the temperature.
  3. A switch runs the correct conversion method.
  4. Each method returns the converted value.
  5. printf() prints the result with two decimal places.
Java
import java.util.Scanner;

public class TemperatureConverter {

    static double cToF(double c) {
        return (c * 9 / 5) + 32;
    }

    static double fToC(double f) {
        return (f - 32) * 5 / 9;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Temperature Converter");
        System.out.println("1. Celsius to Fahrenheit");
        System.out.println("2. Fahrenheit to Celsius");
        System.out.print("Choose (1 or 2): ");
        int choice = sc.nextInt();

        System.out.print("Enter temperature: ");
        double temp = sc.nextDouble();

        switch (choice) {
            case 1:
                System.out.printf("%.2f C = %.2f F%n", temp, cToF(temp));
                break;
            case 2:
                System.out.printf("%.2f F = %.2f C%n", temp, fToC(temp));
                break;
            default:
                System.out.println("Invalid choice.");
        }

        sc.close();
    }
}
Sample Run
terminal
Temperature Converter 1. Celsius to Fahrenheit 2. Fahrenheit to Celsius Choose (1 or 2): 1 Enter temperature: 0 0.00 C = 32.00 F

About this project

Build a simple calculator that takes two numbers and an operator (+, -, *, /), then prints the result. It handles division by zero with an error message.

What you'll practice
switch double Scanner operators if / else
Step-by-step: How it works
  1. Two numbers and a char operator are read from the user.
  2. A switch performs the matching operation.
  3. Division checks for zero before calculating to avoid an error.
  4. The result is printed using printf().
  5. An invalid operator shows an error message.
Java
import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter first number: ");
        double a = sc.nextDouble();

        System.out.print("Enter second number: ");
        double b = sc.nextDouble();

        System.out.print("Enter operator (+, -, *, /): ");
        char op = sc.next().charAt(0);

        switch (op) {
            case '+':
                System.out.printf("%.2f + %.2f = %.2f%n", a, b, a + b);
                break;
            case '-':
                System.out.printf("%.2f - %.2f = %.2f%n", a, b, a - b);
                break;
            case '*':
                System.out.printf("%.2f * %.2f = %.2f%n", a, b, a * b);
                break;
            case '/':
                if (b != 0) {
                    System.out.printf("%.2f / %.2f = %.2f%n", a, b, a / b);
                } else {
                    System.out.println("Error: Cannot divide by zero.");
                }
                break;
            default:
                System.out.println("Invalid operator.");
        }

        sc.close();
    }
}
Sample Run
terminal
Enter first number: 10 Enter second number: 4 Enter operator (+, -, *, /): / 10.00 / 4.00 = 2.50

Beginner Capstone Project

Put everything together — variables, arrays, loops, methods, and classes — in one complete project.

About this project

Build a grade calculator that takes multiple subjects, stores them in an array, calculates the average, and prints a letter grade (A, B, C, D, F) plus pass/fail status.

What you'll practice
arrays loops methods if / else Scanner
Step-by-step: How it works
  1. The user enters how many subjects and each score.
  2. Scores are stored in an array.
  3. A loop sums all scores.
  4. The average is calculated by dividing the sum by the count.
  5. Conditionals convert the average into a letter grade.
  6. The grade and pass/fail status are printed.
Java
import java.util.Scanner;

public class GradeCalculator {

    static String getGrade(double avg) {
        if (avg >= 90) return "A";
        else if (avg >= 80) return "B";
        else if (avg >= 70) return "C";
        else if (avg >= 60) return "D";
        else return "F";
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("How many subjects? ");
        int count = sc.nextInt();

        double[] scores = new double[count];
        double sum = 0;

        for (int i = 0; i < count; i++) {
            System.out.print("Enter score for subject " + (i + 1) + ": ");
            scores[i] = sc.nextDouble();
            sum += scores[i];
        }

        double average = sum / count;
        String grade = getGrade(average);

        System.out.printf("%nAverage: %.2f%n", average);
        System.out.println("Grade: " + grade);
        System.out.println(average >= 60 ? "Result: PASS" : "Result: FAIL");

        sc.close();
    }
}
Sample Run
terminal
How many subjects? 3 Enter score for subject 1: 85 Enter score for subject 2: 90 Enter score for subject 3: 78 Average: 84.33 Grade: B Result: PASS
You've completed all 20 lessons. Ready to continue?

Level up with Java Intermediate, Advanced, and Practice resources.

📱 Scan this QR code with your phone camera to instantly open this page.

Works on iOS, Android, and any modern device. No app installation required.

Account Verified!

Your email has been verified successfully.