Skip to content

Module 2 · Java Basics — topic 1 of 5

Variables and Data Types

Declaring variables, the eight primitive types and their ranges, reference types, literals, constants with final, and local type inference with var.

Beginner 15 min read·Lesson 4 of 39 in Java Programming

Learning objectives

  • Choose the right primitive type for a value
  • Write integer, floating-point, character and boolean literals
  • Use final for constants and var for local type inference

Definition

A variable is a named storage location with a fixed type. Java has eight primitive types (byte, short, int, long, float, double, char, boolean) that hold values directly, and reference types (classes, arrays, interfaces) whose variables hold references to objects.

Introduction

Programs work with data: a student's age, a price, a name, whether a payment succeeded. A variable gives a piece of data a name and a type, and the type decides what values it may hold and which operations make sense.

Unlike C, the size of every Java primitive type is fixed by the language specification. An int is always 32 bits, whether the program runs on a phone or a server — one reason Java programs behave the same everywhere.

Why it matters

Picking the wrong type causes real bugs: an int overflows above about 2.1 billion, and double cannot represent 0.1 exactly, which matters for money.

Every later topic — arrays, classes, collections — builds on knowing the difference between primitives and references.

Detailed explanation

Integers. byte (8 bits, −128 to 127), short (16 bits), int (32 bits, about ±2.1 billion) and long (64 bits, about ±9.2 × 10¹⁸). Use int by default and long for large counts, file sizes and timestamps. Write long literals with an L suffix: 9_000_000_000L.

Floating point. float (32 bits, about 7 significant digits) and double (64 bits, about 15–16 digits). Use double by default; a float literal needs an f suffix: 3.14f. Neither can represent most decimal fractions exactly, so use long cents or java.math.BigDecimal for money.

char and boolean. char is a 16-bit Unicode code unit written in single quotes ('A', '\n', '\u00e9'). boolean is only true or false — unlike C, numbers are not booleans, so if (1) does not compile.

Reference types. Everything else — String, arrays, your own classes — is a reference type. The variable holds a reference to an object on the heap, or the special value null. Two reference variables can refer to the same object.

Initialisation. Local variables must be assigned before use; the compiler checks this. Fields of objects and elements of arrays get default values: 0, 0.0, false, '\u0000' or null.

final and var. final makes a variable assignable only once, which is how constants are written: static final int MAX_STUDENTS = 60;. Since Java 10, var lets the compiler infer a local variable's type from its initialiser: var total = 0L; is a long. The type is still fixed — var is not dynamic typing.

Syntax

Java
int count = 10;
long population = 1_400_000_000L;
double price = 99.95;
float ratio = 0.75f;
char grade = 'A';
boolean passed = true;
String name = "Asha"; // reference type
final double GST_RATE = 0.18; // constant
var marks = new int[5]; // inferred: int[]
  • Underscores in numeric literals (1_000_000) are ignored and improve readability.
  • Hex 0xFF, binary 0b1010 and octal 017 literals are allowed.
  • Constant names are UPPER_SNAKE_CASE by convention.

Code examples

The eight primitives and their ranges

Java
public class Types {
public static void main(String[] args) {
System.out.println("byte: " + Byte.MIN_VALUE + " to " + Byte.MAX_VALUE);
System.out.println("short: " + Short.MIN_VALUE + " to " + Short.MAX_VALUE);
System.out.println("int: " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);
System.out.println("long: " + Long.MAX_VALUE);
System.out.println("char: " + (int) Character.MAX_VALUE);
System.out.println("double max: " + Double.MAX_VALUE);
boolean ok = true;
System.out.println("boolean: " + ok + " or " + !ok);
}
}
Output
byte:  -128 to 127
short: -32768 to 32767
int:   -2147483648 to 2147483647
long:  9223372036854775807
char:  65535
double max: 1.7976931348623157E308
boolean: true or false

var and final

Java
public class VarFinal {
public static void main(String[] args) {
final int SEATS = 60;
var enrolled = 57; // int
var fee = 1250.50; // double
var name = "Data Structures"; // String
System.out.println(name + ": " + enrolled + "/" + SEATS + " seats, fee " + fee);
System.out.println("Seats left: " + (SEATS - enrolled));
}
}
Output
Data Structures: 57/60 seats, fee 1250.5
Seats left: 3

More examples

Overflow, precision and references

Java
public class Pitfalls {
public static void main(String[] args) {
int big = Integer.MAX_VALUE;
System.out.println("int overflow: " + (big + 1));
long safe = big + 1L;
System.out.println("as long: " + safe);
System.out.println("0.1 + 0.2 = " + (0.1 + 0.2));
long cents = 10 + 20;
System.out.println("in cents: " + cents / 100 + "." + cents % 100);
int[] a = {1, 2, 3};
int[] b = a; // copies the reference, not the array
b[0] = 99;
System.out.println("a[0] = " + a[0]);
}
}
Output
int overflow: -2147483648
as long: 2147483648
0.1 + 0.2 = 0.30000000000000004
in cents: 0.30
a[0] = 99

Step-by-step explanation

  • big + 1 is computed in 32-bit int arithmetic and wraps around to the minimum value — Java defines overflow as wrap-around, it does not throw.
  • big + 1L makes the expression long because one operand is a long, so it is computed correctly.
  • 0.1 + 0.2 shows binary floating-point rounding: neither 0.1 nor 0.2 can be stored exactly.
  • Working in whole cents (10 + 20 = 30) keeps money exact; dividing and taking the remainder formats it.
  • int[] b = a; copies the reference, so a and b name the same array object and the change through b is visible through a.

Expected output

Running “Overflow, precision and references” prints exactly:

TextOutput
int overflow: -2147483648
as long: 2147483648
0.1 + 0.2 = 0.30000000000000004
in cents: 0.30
a[0] = 99

Practical applications

  • Counting users or bytes with long
  • Storing prices as long cents or BigDecimal in billing systems
  • Using final constants for configuration values such as tax rates
  • Using char arithmetic for simple text processing such as Caesar ciphers

Best practices

  • Default to int and double; switch to long or BigDecimal when the range or exactness requires it.
  • Declare variables close to where they are used, with meaningful names.
  • Use var only when the type is obvious from the right-hand side.

Common mistakes

Large literals without L

Avoid

long ms = 30 * 24 * 60 * 60 * 1000;

Prefer

long ms = 30L * 24 * 60 * 60 * 1000;

Without L the multiplication happens in int and overflows before the result is widened to long.

Using double for money

Avoid

double total = 0.1 + 0.2; // 0.30000000000000004

Prefer

long totalCents = 10 + 20; // exactly 30

Binary floating point can't represent most decimal fractions exactly; use integer cents or BigDecimal.

Important notes

  • Integer division by zero throws ArithmeticException, but floating-point division by zero gives Infinity or NaN.
  • String is not a primitive even though it has literal syntax; it is a class in java.lang.

Key takeaways

  • Java has eight primitives with fixed sizes; everything else is a reference type.
  • int overflow wraps silently — use long when values can be large.
  • final makes constants; var infers a local variable's type at compile time.

Try it yourself

  1. 1
    Compute the number of seconds in 100 years using long, and print it.
  2. 2
    Store a price of ₹1,299.99 in cents and print it back in rupees with two decimals.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

8 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerHow many bits does a Java int always have?
  • BeginnerWhich declaration does NOT compile?
  • BeginnerWhat is printed?
Practise this topic