Java · Module 2 · Lesson 11 min read

Variables & Data Types

Declaring a variable

type name = value;

Java
int age = 20;
double price = 99.5;
char grade = 'A';
boolean isOnline = true;
String name = "Asha";

The 8 primitive types

TypeSizeExample
byte1 byte100
short2 bytes30000
int4 bytes2_000_000
long8 bytes9_000_000_000L
float4 bytes3.14f
double8 bytes3.14159
char2 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 → double double 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

Java
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
    }
}