Variables & Data Types
Declaring a variable
type name = value;
int age = 20;
double price = 99.5;
char grade = 'A';
boolean isOnline = true;
String name = "Asha";
The 8 primitive types
| Type | Size | Example |
|---|---|---|
byte | 1 byte | 100 |
short | 2 bytes | 30000 |
int | 4 bytes | 2_000_000 |
long | 8 bytes | 9_000_000_000L |
float | 4 bytes | 3.14f |
double | 8 bytes | 3.14159 |
char | 2 bytes | 'J' |
boolean | – | true / false |
💡 Use int for whole numbers and double for decimals unless you have a reason not to. Underscores like 1_000_000 make big numbers readable.
Reference types
String, arrays and objects store a reference (an address) to data in memory. Their default value is null.
var (Java 10+)
var city = "Delhi"; → the compiler figures out the type is String. It works only for local variables that are given a value.
Constants
final double PI = 3.14159; → a final variable can't be reassigned. Name constants in UPPER_SNAKE_CASE.
Type casting
- Widening (automatic, safe):
byte → short → int → long → float → doubledouble d = 10; // 10.0 - Narrowing (manual, may lose data):
int x = (int) 9.99; // 9 — decimals are cut off, not rounded
Naming rules
Start with a letter, _ or $. No spaces, and no keywords like class. Use camelCase: totalMarks, isGameOver.
Example
public class Box {
public static void main(String[] args) {
int coins = 50;
double bonus = 1.5;
double total = coins * bonus; // int is widened to double
int rounded = (int) total; // narrowing cast
System.out.println(total); // 75.0
System.out.println(rounded); // 75
}
}