Variables in Java
Declare, initialize and use variables in Java. Primitive types, default values and variable scope.
Learning objectives
- βDeclare and initialize primitive variables
- βKnow the 8 primitive types and their sizes
- βUnderstand local, instance and static variables
π‘ Key points
- Java is statically typed β every variable has a declared type known at compile time.
- Eight primitive types: byte, short, int, long, float, double, char, boolean.
- Local variables MUST be initialized before use. Instance/static variables get default values.
- Use final to declare a constant β value cannot change after initialization.
π» Code examples(3)
int age = 21;
double price = 99.99;
char grade = 'A';
boolean isActive = true;
String name = "Rohan"; // String is a class, not a primitive
final double PI = 3.14159; // constant
public class Player {
int score; // defaults to 0
double health; // defaults to 0.0
boolean alive; // defaults to false
String name; // defaults to null
}
public class ScopeDemo {
static int shared = 10; // class scope
int perObject = 5; // instance scope
void method() {
int localVar = 3; // method scope
System.out.println(localVar);
}
}
π― Practice
Q1. What is the difference between int and Integer in Java?+
int is a primitive (holds a raw value). Integer is a wrapper class (an object). Integer can be null and used in collections; int cannot.
Q2. Will this compile: int x; System.out.println(x); ?+
No. x is a local variable and must be explicitly initialized before use, otherwise the compiler rejects it.
Q3. Declare a final constant TAX_RATE with value 0.18.+
final double TAX_RATE = 0.18;
π Notes
Primitive types cheat sheet
| Type | Size | Range / Example |
|---|---|---|
| byte | 8-bit | β128 to 127 |
| short | 16-bit | β32,768 to 32,767 |
| int | 32-bit | ~Β±2.1 billion (default for whole numbers) |
| long | 64-bit | very large integers, suffix L |
| float | 32-bit | decimal, suffix f |
| double | 64-bit | decimal (default for decimals) |
| char | 16-bit | single Unicode character 'A' |
| boolean | JVM-dependent | true / false |
Naming rules
- Start with a letter,
_or$; then letters/digits. - Case-sensitive:
ageandAgeare different. - Cannot be a reserved keyword (
class,int,if, β¦). - Convention:
camelCasefor variables,SCREAMING_SNAKE_CASEfor constants.