Declaring Variables
In Java, every variable must have a declared type. The syntax is: type variableName = value;
int age = 25;
double price = 9.99;
boolean isActive = true;
String name = "Alice";
Primitive Types
| Type | Size | Range / Example |
|---|---|---|
| byte | 1 byte | -128 to 127 |
| short | 2 bytes | -32,768 to 32,767 |
| int | 4 bytes | -2^31 to 2^31-1 |
| long | 8 bytes | -2^63 to 2^63-1 |
| float | 4 bytes | 3.14f |
| double | 8 bytes | 3.14159 |
| char | 2 bytes | 'A' |
| boolean | 1 bit | true / false |
Constants with final
final double PI = 3.14159265;
final int MAX_SIZE = 100;
// PI = 3; // ❌ compilation error
Type Casting
// Widening (implicit)
int i = 42;
double d = i; // 42.0 — OK automatically
// Narrowing (explicit)
double x = 9.99;
int n = (int) x; // 9 — decimal part is lost
String Basics
String greeting = "Hello, " + "World!";
int length = greeting.length(); // 13
String upper = greeting.toUpperCase(); // "HELLO, WORLD!"
boolean starts = greeting.startsWith("Hello"); // true
var (Java 10+)
var count = 10; // inferred as int
var message = "Hi"; // inferred as String
// var x; // ❌ must be initialized