Java Variables & Data Types

Primitive and reference types.

✍️ 2 exercises in this lesson

Java is statically typed: every variable has a type: type name = value;

Primitive types

  • byte, short, int, long: whole numbers
  • float, double: decimals
  • boolean: true / false
  • char: a single character, in single quotes

Reference types include String, arrays and classes. final makes a variable a constant. var (Java 10+) lets the compiler infer the type.

Key Takeaways: Java Variables & Data Types

Mastering Java Variables & Data Types helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Java Variables & Data Types Code Example

Java
public class Main {
    public static void main(String[] args) {
        int age = 25;
        long population = 241_000_000L;
        double price = 2000.0;
        boolean active = true;
        char grade = 'A';
        String name = "Sara";
        final double TAX = 0.18;
        var city = "Lahore";

        System.out.println(name + " (" + age + ") from " + city);
        System.out.println("Grade " + grade + ", active: " + active);
        System.out.println("With tax: " + price * (1 + TAX));
        System.out.println("Population: " + population);
    }
}
Output
Sara (25) from Lahore
Grade A, active: true
With tax: 2360.0
Population: 241000000
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Java Variables & Data Types Practice Exercises

Check what you learned in “Java Variables & Data Types”.

/ 2 solved
Fill in the blank

Declare a whole-number variable.

 age = 25;
✓ Correct! Not quite. Try again.
Multiple choice

Which type holds a single character?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services