AnyCompiler

Variables and Types

Java's primitive types include int, double, boolean, and char — every variable has a declared type, and that type is fixed once declared. Note that these are primitives, not objects: a boolean prints as the word true or false, not 0 or 1.

public class Main {
    public static void main(String[] args) {
        int age = 30;
        double price = 19.99;
        boolean isStudent = false;
        char grade = 'A';
        System.out.println(age + " " + price + " " + isStudent + " " + grade);
    }
}
Output
30 19.99 false A

var type inference

var lets the compiler infer a variable's type from its initializer, introduced in Java 10 — useful when the type is obvious or verbose. It still produces a fixed, fully static type at compile time; it's not a dynamic type the way it might be in a scripting language.

public class Main {
    public static void main(String[] args) {
        var count = 42; // inferred as int
        var pi = 3.14159; // inferred as double
        System.out.println(count + " " + pi);
    }
}
Output
42 3.14159

What a real type-mismatch error looks like

Java's compiler checks that every assignment's types actually line up — assigning a String where an int is expected is a compile error, not something caught later at runtime. This is genuinely what javac reports — captured from a real run, not written to look plausible:

public class Main {
    public static void main(String[] args) {
        int age = "thirty";
        System.out.println(age);
    }
}
Output
Main.java:3: error: incompatible types: String cannot be converted to int
        int age = "thirty";
                  ^
1 error

Nothing runs at all — no output, just the error. Catching this at compile time instead of runtime is one of the main benefits of Java's static typing.

Next: operators and control flow — if/else, for, while, and switch.

Practice exercise

Declare a variable temperature of type double set to 72.5 and a variable isSunny of type boolean set to true. Print them together separated by a space.