CodeMIRAI
0 XP

Variables and types

2 min read 4 runnable examples Quiz included

Java is statically typed: every variable's type is declared and checked by the compiler.

Primitive types

TypeHoldsExample
intwhole numbers (about ±2.1 billion)int age = 21;
longvery large whole numberslong views = 8_000_000_000L;
doubledecimal numbersdouble price = 19.99;
booleantrue or falseboolean active = true;
charone characterchar grade = 'A';

There are also byte, short and float for special cases.

Java
public class Main {
    public static void main(String[] args) {
        int age = 21;
        double height = 1.65;
        boolean isStudent = true;
        char initial = 'A';
        long worldPopulation = 8_100_000_000L;

        System.out.println(age + " " + height + " " + isStudent + " " + initial);
        System.out.println(worldPopulation);
    }
}

String

Text is a String, written in double quotes. It's not a primitive but a class, which is why it starts with a capital letter:

Java
public class Main {
    public static void main(String[] args) {
        String name = "Mei";
        System.out.println(name.toUpperCase());
        System.out.println(name.length());
        System.out.println("Hello, " + name + "!");
    }
}

var

Since Java 10, var lets the compiler infer the type of a local variable from its value:

Java
var count = 10;          // int
var message = "Hi";      // String

The type is still fixed; var just saves typing.

Constants

final makes a variable unchangeable after it's assigned:

Java
public class Main {
    public static void main(String[] args) {
        final double TAX_RATE = 0.18;
        double price = 250;
        System.out.println("Total: " + price * (1 + TAX_RATE));
    }
}

Integer division and casting

Java
public class Main {
    public static void main(String[] args) {
        int a = 7, b = 2;
        System.out.println(a / b);            // 3
        System.out.println(a % b);            // 1
        System.out.println((double) a / b);   // 3.5
        double d = 9.99;
        int whole = (int) d;                  // 9: casting truncates
        System.out.println(whole);
    }
}
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.