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.
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
- Underscores in numeric literals (
1_000_000) are ignored and improve readability. - Hex
0xFF, binary0b1010and octal017literals are allowed. - Constant names are UPPER_SNAKE_CASE by convention.
Code examples
The eight primitives and their ranges
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
Data Structures: 57/60 seats, fee 1250.5 Seats left: 3
More examples
Overflow, precision and references
int overflow: -2147483648 as long: 2147483648 0.1 + 0.2 = 0.30000000000000004 in cents: 0.30 a[0] = 99
Step-by-step explanation
big + 1is computed in 32-bitintarithmetic and wraps around to the minimum value — Java defines overflow as wrap-around, it does not throw.big + 1Lmakes the expressionlongbecause one operand is a long, so it is computed correctly.0.1 + 0.2shows 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, soaandbname the same array object and the change throughbis visible througha.
Expected output
Running “Overflow, precision and references” prints exactly:
Practical applications
- Counting users or bytes with
long - Storing prices as
longcents orBigDecimalin billing systems - Using
finalconstants for configuration values such as tax rates - Using
chararithmetic for simple text processing such as Caesar ciphers
Best practices
- Default to
intanddouble; switch tolongorBigDecimalwhen the range or exactness requires it. - Declare variables close to where they are used, with meaningful names.
- Use
varonly when the type is obvious from the right-hand side.
Common mistakes
Large literals without L
Avoid
Prefer
Without L the multiplication happens in int and overflows before the result is widened to long.
Using double for money
Avoid
Prefer
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 givesInfinityorNaN. Stringis not a primitive even though it has literal syntax; it is a class injava.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.
finalmakes constants;varinfers a local variable's type at compile time.
Try it yourself
- 1Compute the number of seconds in 100 years using long, and print it.
- 2Store 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?