Tutorials / Java: From Zero to Advanced / Variables and data types

Variables and data types

13 min read java
Course contents (20 lessons)
  1. Getting started
  2. Installing JDK 21 and running Java code
  3. Your first program: how a Java file is built
  4. Language basics
  5. Variables and data types
  6. Strings, formatting and text blocks
  7. Control flow: if, switch expressions and loops
  8. Data and methods
  9. Arrays and the collections framework
  10. Methods, overloading and varargs
  11. Object-oriented Java
  12. Classes, objects and encapsulation
  13. Inheritance, abstract classes and interfaces
  14. Records, enums and sealed types
  15. Writing robust code
  16. Exceptions: checked, unchecked and try-with-resources
  17. Generics, bounded types and wildcards
  18. Files and the NIO.2 API
  19. Modern Java
  20. Lambdas and the Stream API
  21. Optional: handling missing values
  22. Concurrency: executors, CompletableFuture and virtual threads
  23. Tools, services and the final project
  24. Maven and Gradle basics
  25. Testing with JUnit 5
  26. A small REST service with the JDK HTTP server
  27. Final project: a library manager

Declaring a variable

Java is statically typed. Every variable has a type, and the type cannot change. You write the type, then the name, then optionally a value.

int age = 34;
String city = "Lahore";
double height = 1.78;
boolean student = false;

Primitive types

Java has eight primitive types. They hold simple values directly, and they always start with a lowercase letter.

TypeSizeHolds
byte8 bits-128 to 127
short16 bits-32,768 to 32,767
int32 bitsabout -2.1 billion to 2.1 billion
long64 bitsvery large whole numbers
float32 bitsdecimal numbers, low precision
double64 bitsdecimal numbers, the default choice
char16 bitsone character, such as 'A'
booleann/atrue or false

In practice you will use int, long, double and boolean nearly all of the time. Anything that is not a primitive is a reference type, such as String or any class. A reference variable holds a pointer to an object, and it can also hold null, which means no object.

A longer example

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main {

    public static void main(String[] args) {
        // Literals need the right suffix
        long population = 240_000_000L;      // underscores help reading
        float ratio = 0.5f;
        char grade = 'A';

        // var lets the compiler infer the type
        var count = 10;                      // int
        var message = "Types matter";        // String

        // final means the variable cannot be reassigned
        final double TAX_RATE = 0.17;

        // Integer division and casting
        System.out.println(7 / 2);           // 3
        System.out.println(7 / 2.0);         // 3.5
        double average = (double) 7 / 2;     // cast first, then divide
        System.out.println(average);
        int truncated = (int) 9.99;          // 9, the decimals are cut off
        System.out.println(truncated);

        // Overflow wraps around silently
        int big = Integer.MAX_VALUE;
        System.out.println(big + 1);         // -2147483648
        System.out.println(Math.addExact(5, 6));
        try {
            Math.addExact(big, 1);
        } catch (ArithmeticException e) {
            System.out.println("Overflow detected: " + e.getMessage());
        }

        // Floating point is not exact
        System.out.println(0.1 + 0.2);       // 0.30000000000000004

        // Use BigDecimal for money
        BigDecimal price = new BigDecimal("19.99");
        BigDecimal total = price.multiply(BigDecimal.valueOf(3));
        BigDecimal tax = total.multiply(BigDecimal.valueOf(TAX_RATE))
                              .setScale(2, RoundingMode.HALF_UP);
        System.out.println("Total " + total + ", tax " + tax);

        // char is a number underneath
        char next = (char) (grade + 1);
        System.out.println(next);            // B
        System.out.println(population + " " + ratio + " " + count + " " + message);
    }
}

Walking through it

A whole-number literal like 240_000_000 is an int by default. When the value is too big for an int, or when you want a long, add L. A decimal literal is a double. To make a float, add f. Underscores in numbers are ignored by the compiler and help you count zeros.

var arrives from Java 10. The compiler works out the type from the right-hand side. It only works for local variables that you initialise on the same line. It is still static typing, nothing becomes dynamic.

final on a variable means you can assign it once. The convention for constants is upper-case names. For a true constant shared by a class, you would write static final at class level.

The division lines repeat a trap from many languages. When both operands are int, the result is an int, and the fraction is thrown away. Make one operand a double, or cast one of them. In (double) 7 / 2 the cast applies to the 7 before the division. Casting from a larger type to a smaller one, like (int) 9.99, cuts off the decimals without rounding. Use Math.round if you want rounding.

Overflow is silent. Adding 1 to the largest int gives the smallest one. Java does not warn you. When it matters, use Math.addExact, multiplyExact and their relatives, which throw an ArithmeticException, or use long.

0.1 + 0.2 printing 0.30000000000000004 is a property of binary floating point and not a Java bug. For money, avoid double. BigDecimal stores exact decimal values. Create it from a string, as in new BigDecimal("19.99"), because new BigDecimal(19.99) would capture the inexact double. You must choose a rounding mode when you reduce the number of decimals.

Wrapper classes

Each primitive has a wrapper class: Integer, Long, Double, Boolean, Character. Collections such as List cannot hold primitives, so you write List<Integer>. Java converts automatically between int and Integer. This is called autoboxing. A wrapper can be null, and unboxing a null throws NullPointerException.

Common mistakes

  • Integer division when you wanted a decimal result.
  • Using double for money.
  • Assigning a long to an int without a cast. The compiler refuses, which is good.
  • Forgetting that char uses single quotes and String double quotes.
  • Relying on overflow not happening. Think about the largest value a variable can see.

Try it yourself

  1. Declare variables for a product: name, quantity, unit price (as BigDecimal) and in-stock flag. Print the total price.
  2. Compute the average of three int values correctly, as a double.
  3. Find out what Integer.MAX_VALUE * 2 prints, and explain it.
java
import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main {

    public static void main(String[] args) {
        // Literals need the right suffix
        long population = 240_000_000L;      // underscores help reading
        float ratio = 0.5f;
        char grade = 'A';

        // var lets the compiler infer the type
        var count = 10;                      // int
        var message = "Types matter";        // String

        // final means the variable cannot be reassigned
        final double TAX_RATE = 0.17;

        // Integer division and casting
        System.out.println(7 / 2);           // 3
        System.out.println(7 / 2.0);         // 3.5
        double average = (double) 7 / 2;     // cast first, then divide
        System.out.println(average);
        int truncated = (int) 9.99;          // 9, the decimals are cut off
        System.out.println(truncated);

        // Overflow wraps around silently
        int big = Integer.MAX_VALUE;
        System.out.println(big + 1);         // -2147483648
        System.out.println(Math.addExact(5, 6));
        try {
            Math.addExact(big, 1);
        } catch (ArithmeticException e) {
            System.out.println("Overflow detected: " + e.getMessage());
        }

        // Floating point is not exact
        System.out.println(0.1 + 0.2);       // 0.30000000000000004

        // Use BigDecimal for money
        BigDecimal price = new BigDecimal("19.99");
        BigDecimal total = price.multiply(BigDecimal.valueOf(3));
        BigDecimal tax = total.multiply(BigDecimal.valueOf(TAX_RATE))
                              .setScale(2, RoundingMode.HALF_UP);
        System.out.println("Total " + total + ", tax " + tax);

        // char is a number underneath
        char next = (char) (grade + 1);
        System.out.println(next);            // B
        System.out.println(population + " " + ratio + " " + count + " " + message);
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account