Java Variables and Data Types: A Beginner’s Guide

admin5 min read
In this tutorial
  1. What is a variable?
  2. The eight primitive types
  3. Reference types
  4. Type casting
  5. Local variable type inference with var
  6. Constants with final
  7. Common mistakes
  8. Quick practice
  9. Summary

Every Java program you write stores and moves data around: a student’s name, a bank balance, whether a user is logged in. Before you can do anything useful, you need to know where that data lives and what kind of data it is. That is what variables and data types are for.

In this tutorial you will learn how to declare variables, the eight primitive types, how reference types differ, how to convert between types, and the mistakes that trip up most beginners.

What is a variable?

A variable is a named box that holds a value. In Java, every box has a fixed type, and the compiler will not let you put the wrong kind of value in it. That strictness is one of the reasons Java catches so many bugs before your program even runs.

You declare a variable by writing its type, then its name, and optionally an initial value:

int age = 25;
String name = "Ada";
boolean isEnrolled = true;

You can declare first and assign later, but Java will refuse to compile code that reads a local variable before it has been given a value:

int score;
// System.out.println(score); // compile error: variable score might not have been initialized
score = 90;
System.out.println(score);   // 90

Naming rules and conventions

  • Names can contain letters, digits, _ and $, but cannot start with a digit.
  • Names are case-sensitive: total and Total are different variables.
  • You cannot use reserved words such as class, int or public.
  • By convention, use camelCase for variables (monthlySalary) and UPPER_SNAKE_CASE for constants (MAX_RETRIES).

Good names save you hours later. d tells a reader nothing; daysUntilDeadline tells them everything.

The eight primitive types

Primitive types hold simple values directly in memory. Java has exactly eight of them:

  • byte: 8-bit whole number, from -128 to 127. Useful for raw binary data.
  • short: 16-bit whole number, from -32,768 to 32,767. Rarely used today.
  • int: 32-bit whole number, about ±2.1 billion. The default choice for whole numbers.
  • long: 64-bit whole number. Use it for very large values such as timestamps in milliseconds. Add an L suffix: long views = 9_000_000_000L;
  • float: 32-bit decimal. Needs an f suffix: float ratio = 0.75f;
  • double: 64-bit decimal. The default choice for decimals.
  • char: a single 16-bit Unicode character in single quotes: char grade = 'A';
  • boolean: either true or false.

Here they all are in one runnable program:

public class PrimitiveTypes {
    public static void main(String[] args) {
        byte level = 7;
        short year = 2025;
        int population = 223_800_000;
        long distanceToSunKm = 149_600_000L;
        float discount = 0.15f;
        double price = 4_999.99;
        char initial = 'K';
        boolean isOpen = true;

        System.out.println("Level: " + level);
        System.out.println("Year: " + year);
        System.out.println("Population: " + population);
        System.out.println("Distance to sun (km): " + distanceToSunKm);
        System.out.println("Discount: " + discount);
        System.out.println("Price: " + price);
        System.out.println("Initial: " + initial);
        System.out.println("Open now? " + isOpen);
    }
}

The underscores in 223_800_000 are just for readability. The compiler ignores them.

Reference types

Anything that is not one of the eight primitives is a reference type: String, arrays, ArrayList, and every class you write yourself. A reference variable does not hold the object itself; it holds a reference (an address) pointing to the object somewhere in memory.

String city = "Lagos";
int[] scores = {70, 85, 92};

Two important consequences follow:

  1. A reference variable can be null, meaning it points to nothing. Calling a method on null throws a NullPointerException.
  2. Copying a reference copies the address, not the object. Both variables then point to the same object.
int[] a = {1, 2, 3};
int[] b = a;      // b points to the same array as a
b[0] = 99;
System.out.println(a[0]); // 99, because a and b share one array

With primitives, assignment copies the value itself, so changing one variable never affects the other.

Type casting

Sometimes you need to convert a value from one type to another.

Widening (small type to bigger type) happens automatically because no information is lost:

int items = 42;
double asDouble = items; // 42.0

Narrowing (bigger type to smaller type) needs an explicit cast, because you might lose information:

double average = 87.9;
int rounded = (int) average; // 87, the decimal part is cut off, not rounded

If you actually want rounding, use Math.round(average), which returns a long.

Watch out for integer division

This is one of the most common beginner bugs:

int total = 7;
int count = 2;
double wrong = total / count;          // 3.0, integer division happens first
double right = (double) total / count; // 3.5

When both operands are int, Java performs integer division and throws away the remainder before the result is stored in the double. Cast one operand first.

Local variable type inference with var

Since Java 10 you can let the compiler infer the type of a local variable with var:

var message = "Hello";        // String
var count = 10;               // int
var prices = new double[5];   // double[]

The variable is still strongly typed; you just do not have to repeat the type. Use var when the type is obvious from the right-hand side, and spell the type out when it is not.

Constants with final

Mark a variable final when its value must never change:

final double VAT_RATE = 0.075;
// VAT_RATE = 0.08; // compile error: cannot assign a value to final variable

Constants make your code safer and self-documenting.

Common mistakes

  • Overflow. int silently wraps around when it goes past its maximum. Integer.MAX_VALUE + 1 becomes -2147483648. Use long for large counts, or Math.addExact if you want an exception instead of a wrong answer.
  • Using double for money. 0.1 + 0.2 is 0.30000000000000004 in floating point. For currency, use BigDecimal or store amounts in the smallest unit (kobo or cents) as a long.
  • Comparing strings with ==. == compares references, not text. Use name.equals("Ada").
  • Forgetting the L or f suffix. long big = 9000000000; will not compile because the literal is treated as an int.

Quick practice

Try these before moving on:

  1. Declare variables for a product’s name, price, quantity in stock and whether it is on sale. Print a sentence using all four.
  2. Calculate the average of three int test scores and print it with decimals.
  3. Find out what happens when you add 1 to Byte.MAX_VALUE and store the result in a byte using a cast.

Summary

  • A variable is a named, typed container for a value.
  • Java has eight primitive types; int, double, boolean and char are the ones you will use most.
  • Everything else is a reference type, which can be null and can be shared between variables.
  • Widening conversions are automatic; narrowing needs a cast and may lose data.
  • Use var for obvious types, final for constants, and BigDecimal for money.

Next, learn how to combine these values with Java operators.

Ask a question or leave a comment

Your email address will not be published. Required fields are marked *