Nearby lessons
11 of 125Java - Variables and Data Types
📌 What You Will Learn
- The small building blocks of Java: tokens
- All 8 primitive data types with their ranges
- Type casting — implicit and explicit
- Control statements: if, switch, loops
- Arrays — single, double and jagged
- Variable length arguments (var-args)
Variables and Data Types is a core concept of the Java language. This lesson explains Data Types with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Data Types
A data type tells the computer what kind of value a variable can hold and how much memory it needs. Java data types are of two big categories:
- Primitive types — 8 basic types built into the language (int, float, boolean, etc.).
- Reference (non-primitive) types — types made from classes and interfaces (String, arrays, user-defined classes).
The 8 primitive types with their sizes and ranges:
| Data type | Size | Range (simple words) |
|---|---|---|
| byte | 1 byte | -128 to 127 |
| short | 2 bytes | -32,768 to 32,767 |
| int | 4 bytes | -2,147,483,648 to 2,147,483,647 (approx -214 crores to +214 crores) |
| long | 8 bytes | very big range (approx -922 lakh crore to +922 lakh crore) |
| float | 4 bytes | up to 7 decimal digits (approx) |
| double | 8 bytes | up to 15 decimal digits (approx) — default for decimals |
| char | 2 bytes | 0 to 65,535 (holds one UNICODE character) |
| boolean | 1 bit (size depends) | true or false only |
Example01
📝 Key Takeaways
- Tokens are the smallest pieces of a program: identifiers, literals, keywords, operators, separators.
- Java has 8 primitive types: byte, short, int, long, float, double, char, boolean.
- Widening casting is automatic and safe; narrowing casting needs brackets and may lose data.
- if / switch decide which path runs; for / while / do-while repeat code; break and continue control loops.
- Arrays hold many same-type values; index starts at 0; size is fixed; for-each loop reads them simply.
- Var-args (int... x) lets a method take any number of arguments.
🧠 Test Your Knowledge
1 QuestionsProgress: 0 / 1