[!NOTE] Variables are named containers holding data in the computer's memory. In Java, every container is strictly labeled with the exact type of data it's allowed to hold.
Statically Typed vs Dynamically Typed
If you are coming from Python or JavaScript, you are used to Dynamic Typing. You can create a variable x = 5 and later change your mind and say x = "Hello".
Java is Statically Typed. When you create a variable, you must explicitly declare its type upfront. Once declared, that variable can never hold a different type of data. If you try to put text inside an integer variable, the code simply will not compile.
Why go through the trouble?
Static typing catches 90% of your bugs at compile-time before the application even starts. In JavaScript, you might not realize an error occurred until a user clicks a button and the app crashes in production. By forcing you to declare types, Java acts as your personal safety net.
Primitive Data Types
Java has 8 foundational "Primitive" types. These are raw values, not objects. They are extremely fast and efficient, living directly on the call stack execution memory.
- Integral Numbers
| Type | Size | Range | Example Use Case |
|---|---|---|---|
| byte | 8-bit | -128 to 127 | Saving memory in enormous 2D arrays. |
| short | 16-bit | -32,768 to 32,767 | Rarely used in modern Java. |
| int | 32-bit | ~ ±2 Billion | Default choice for whole numbers. |
| long | 64-bit | ~ ±9 Quintillion | Extremely large counts (e.g., global population). Append 'L'. |
int currentScore = 1500;
long viewCount = 8000000000L;
- Floating-Point Numbers
| Type | Size | Precision | Example Use Case |
|---|---|---|---|
| float | 32-bit | ~7 Decimal Digits | Saving memory for 3D graphics. Append 'f'. |
| double | 64-bit | ~15 Decimal Digits | Default choice for decimals. |
double bankBalance = 1542.89;
float pi = 3.14159f;
- Characters & Booleans
- char: A single 16-bit Unicode character. Must be surrounded by single quotes.
- boolean: Simply
trueorfalse.
char grade = 'A'; // Single quotes!
boolean isGameOver = false;
Non-Primitive Data Types (Objects)
Primitives just hold values. Non-primitive types (also called Reference Types) map to fully featured Objects built in the Heap memory. They have methods you can call on them.
The most famous is String. A String is a sequence of characters, enclosed in double quotes.
String playerUsername = "DragonSlayer99";
int usernameLength = playerUsername.length(); // Calling a method on the Object
String upperCaseName = playerUsername.toUpperCase();
Strings are fundamentally different from primitives. int starts with a lowercase letter because it's baked into the language. String starts with a capital letter because it is actually a Class definition located in the java.lang package!
[!IMPORTANT] Variable Naming Conventions: In Java, variables should use
camelCase. They should start with a lowercase letter, and every subsequent word should be capitalized (e.g.,myFirstVariable).
Choosing the Right Type in Real Code
Types are not only syntax. They describe what kind of value your program expects. Good type choices make code easier to read, safer to change, and easier for the compiler to protect.
For ordinary whole numbers, use int. For very large counts, use long. For decimal measurements, use double. For money, do not use double in serious applications because floating-point values can introduce rounding surprises. Use BigDecimal when exact decimal precision matters.
Better Variable Names
// Weak: the type is visible, but the meaning is not clear
int x = 18;
double y = 499.99;
// Better: the variable name explains the business meaning
int minimumAge = 18;
double cartTotal = 499.99;
Primitive Defaults vs Local Variables
Fields get default values, but local variables inside methods must be assigned before use. This rule prevents accidental reads from uninitialized local data.
class ScoreCard {
int score; // field default is 0
void printScore() {
int bonus;
// System.out.println(bonus); // compile error: bonus not initialized
bonus = 10;
System.out.println(score + bonus);
}
}
Common Mistakes
- Using
Stringfor numbers that must be calculated later. - Forgetting the
Lsuffix on very largelongliterals. - Comparing decimal values as if they are always exact.
- Naming variables by type only, such as
str,num, ordata.
Mini Practice
Create variables for a product name, quantity, price, in-stock flag, and rating. Print a one-line invoice summary. Then change the quantity type from int to String and notice which calculations stop compiling.
Practice Lab: Build a Bill Summary
Create variables for a small shopping bill and print a clean summary.
- Create variables for product name, quantity, price per item, tax percentage, and whether the item is in stock.
- Calculate subtotal and final total.
- Print the result in one readable sentence.
- Try changing quantity from
inttoStringand observe what breaks.
Goal: Understand why choosing correct types matters before calculations begin.
Revision Checkpoint
- Static typing: Java checks variable types at compile time.
- Primitive types: Store raw values such as
int,double,boolean, andchar. - Reference types: Point to objects such as
String, arrays, and custom classes. - Default integer: Use
intfor ordinary whole numbers. - Money warning: Prefer exact decimal handling such as
BigDecimalfor serious money calculations.
Before the quiz: Decide whether each value should be int, long, double, boolean, char, or String.