Learn Java Java: Variables and Types

Java: Variables and Types

⏱ 15 min read
A variable is a named container that stores a value. Java is a statically-typed language — you must declare what type of data a variable holds before you use it.

The 4 Most Important Primitive Types:

int — stores whole numbers (-2 billion to 2 billion)
Example: int age = 25;

double — stores decimal numbers (15 digits precision)
Example: double price = 9.99;

boolean — stores only true or false
Example: boolean isStudent = true;

char — stores a single character (use single quotes)
Example: char grade = 'A';

Other Primitive Types:
long — very large whole numbers, add L suffix. Example: long big = 9876543210L;
float — smaller decimal numbers, add f suffix. Example: float pi = 3.14f;
byte — tiny whole numbers (-128 to 127)
short — small whole numbers (-32768 to 32767)

The String Type:
String is not a primitive — it is a class. It stores text. Use double quotes.
Example: String name = "Alice";
Useful methods: name.length(), name.toUpperCase(), name.contains("li")

Constants with final:
Add the final keyword to make a variable unchangeable. Use ALL_CAPS names by convention.
Example: final double PI = 3.14159;

Naming Rules:
Variable names must start with a letter, $ or _. They cannot contain spaces or be Java keywords. Use camelCase: firstName, totalScore, isActive.
Code Example
public class Variables {

    public static void main(String[] args) {
        // Primitive types
        int age = 25;
        double price = 9.99;
        boolean isStudent = true;
        char grade = 'A';

        // Declare first, assign later
        int score;
        score = 100;

        System.out.println("Age: " + age);
        System.out.println("Price: $" + price);
        System.out.println("Is student: " + isStudent);
        System.out.println("Grade: " + grade);

        // String type
        String name = "Alice";
        String greeting = "Hello, " + name + "!";
        System.out.println(greeting);
        System.out.println("Name length: " + name.length());
        System.out.println("Uppercase: " + name.toUpperCase());
        System.out.println("Has 'li': " + name.contains("li"));

        // Constant
        final double PI = 3.14159;
        final int MAX_STUDENTS = 30;
        System.out.println("Pi = " + PI);
        System.out.println("Max students = " + MAX_STUDENTS);
    }

}

// Output:
// Age: 25
// Price: $9.99
// Is student: true
// Grade: A
// Hello, Alice!
// Name length: 5
// Uppercase: ALICE
// Has 'li': true
// Pi = 3.14159
// Max students = 30
← Java: Getting Started Operators and Math →

Log in to track your progress and earn badges as you complete lessons.

Log In to Track Progress