"Think of a variable as a storage box. If you want to store a book, you need a book-sized box. If you want to store a car, you need a garage. In Java, you can't put a 'Car' (String) into a 'Book Box' (int). You must pick the right size first!"
1. Comprehensive Syntax Examples
Here is how we handle different types of data in a real program:
public class VariableDemo {
public static void main(String[] args) {
// 1. Numeric Types
int studentId = 101; // Whole numbers
double gradePoint = 9.5; // Decimals
float temperature = 36.6f; // Note the 'f' for float!
// 2. Character and Boolean
char section = 'A'; // Single quotes for char
boolean isGraduated = false; // Only true or false
// 3. Text (Reference Type)
String schoolName = "Craby Academy"; // Double quotes for String
// Outputting values
System.out.println(schoolName + " ID: " + studentId);
}
}
2. Primitive Data Types Breakdown
Type
Size
Usage Example
byte
1 byte
Small numbers (-128 to 127)
long
8 bytes
Big numbers (e.g., 900L)
float
4 bytes
Simple decimals (e.g., 5.99f)
String
Varies
Text (e.g., "Hello World")
3. Java Type Casting
Sometimes, you need to convert a value from one type to another. There are two types of casting:
A. Widening Casting (Automatic)
Converting a smaller type to a larger type size. Java does this for you!
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
B. Narrowing Casting (Manual)
Converting a larger type to a smaller size. You must do this manually by placing the type in parentheses.
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int (result is 9)
Important Warning: In Narrowing Casting, you might lose data. For example, converting 9.78 to an int will remove the .78 entirely!
4. Constants in Java
If you don't want others (or yourself) to overwrite existing values, use the final keyword. This creates a "constant."
final int BIRTH_YEAR = 1998;
// BIRTH_YEAR = 2000; // This will cause an ERROR!