[!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).