1. Why variables?
So far our programs only print fixed text. Real programs need to remember things: a user's age, a bank balance, a score. A variable is a named storage location in memory (RAM) that holds a value.
Real-life analogy: Labelled boxes
Imagine a shelf of boxes (dabbas) in a kitchen, each with a label: "sugar", "salt", "rice". Each box holds one kind of thing, and you find it by its label. A variable is a labelled box in memory. The type says what kind of thing the box can hold, the name is the label, and the value is what's inside.
public class Main { public static void main(String[] args) { int age = 21; System.out.println(age); System.out.println("Age is " + age); }}Output
21Age is 21Notice: age without quotes prints the value inside the box. "age" with quotes would print the word age.
2. Declare, initialise, assign
public class Main { public static void main(String[] args) { int score; // declaration: create a box named score that holds whole numbers score = 50; // assignment: put 50 in the box int lives = 3; // declaration + initialisation in one line score = 75; // re-assignment: the old value 50 is gone score = score + 10; // read the current value, add 10, store the result back System.out.println(score); // 85 System.out.println(lives); // 3 }}
3. The 8 primitive data types
Java is statically typed: every variable has a fixed type, decided when you write the code. Java has exactly 8 primitive types built into the language.
|
Type |
Stores |
Size |
Range (approx.) |
Example |
|---|---|---|---|---|
|
|
Whole number |
1 byte (8 bits) |
-128 to 127 |
|
|
|
Whole number |
2 bytes |
-32,768 to 32,767 |
|
|
|
Whole number |
4 bytes |
about ±2.1 billion |
|
|
|
Whole number |
8 bytes |
about ±9.2 × 10^18 |
|
|
|
Decimal number |
4 bytes |
about 7 digits of precision |
|
|
|
Decimal number |
8 bytes |
about 15 digits of precision |
|
|
|
A single character |
2 bytes |
one Unicode character |
|
|
|
true or false |
not precisely defined |
|
|
The everyday defaults: use int for whole numbers, double for decimals, boolean for yes/no, char for single characters. Use long when numbers can exceed about 2 billion (phone numbers, timestamps, bank amounts in paise).
Important details:
-
longvalues needLat the end if they're larger thanintcan hold:9000000000L. Without it, Java treats the number as anint, which is too big, and gives an error. -
floatvalues needf:99.5f. Without it, Java treats decimals asdouble. -
charuses single quotes'A'; text uses double quotes"A". -
You can write big numbers with underscores for readability:
int salary = 1_20_000;Java ignores the underscores.
4. Text: String
Text isn't a primitive type, but we need it constantly:
public class Main { public static void main(String[] args) { String name = "Aarav"; String city = "Pune"; System.out.println(name + " lives in " + city); }}Note the capital S in String. It's capitalised for a reason.
We will open this box properly later
String: for now, "the type for storing text; note the capital S." Why capital? BecauseStringis not a primitive; it's a class, and every piece of text is an object. That sentence will make full sense in Session 14. We'll study Strings in depth in Session 12.
5. Naming rules and conventions
Rules (break them and the code won't compile):
-
Names can contain letters, digits,
_and$, but cannot start with a digit.2ndPlace✗,place2✓. -
No spaces.
my age✗. -
Cannot be a keyword (a word reserved by Java) such as
int,class,void,if,for,new,static. -
Case-sensitive:
ageandAgeare different variables.
Conventions (followed by every professional):
-
Variables use camelCase: start lowercase, capitalise each new word:
totalMarks,isLoggedIn,studentCount. -
Use meaningful names:
marksnotm,isAdultnotflag. -
Booleans usually start with
is,hasorcan:isValid,hasTicket.
6. Constants with final
Some values should never change after they're set, such as the number of days in a week or a maximum limit.
public class Main { public static void main(String[] args) { final int DAYS_IN_WEEK = 7; final double GST_RATE = 0.18; // DAYS_IN_WEEK = 8; // compile error: cannot assign a value to final variable System.out.println(DAYS_IN_WEEK * 4); }}Constants use UPPER_SNAKE_CASE by convention.
We will open this box properly later
final: for now, "a variable that can be assigned only once." The wordfinalalso works on methods and classes, with related meanings. We'll see that in Session 22.
7. A quick look at var
Java can work out the type for local variables:
var count = 10; // Java infers intvar price = 45.5; // Java infers doubleThe variable is still strongly typed; count is an int forever. For now, write the types explicitly. It builds a better understanding of types. var is handy later with long type names.
Common mistakes
-
Using a variable before giving it a value:
int x; System.out.println(x);gives "variable x might not have been initialized". -
int price = 99.99;: a decimal doesn't fit in anintbox (error). -
long big = 9000000000;: missingL. -
char c = "A";: double quotes make it a String, not a char. -
Declaring the same variable twice:
int a = 5; int a = 6;is an error. The second time, just writea = 6;.
Interview questions
How many primitive data types does Java have? Name them.
Eight: byte, short, int, long, float, double, char, boolean.
Is String a primitive type?
No. String is a class in the java.lang package; string values are objects.
Why does a char take 2 bytes in Java, when it takes 1 byte in C?
Java uses Unicode (UTF-16) so a char can represent characters from many languages, like Hindi, Tamil or Chinese, not just English. That needs 16 bits.
What is the default type of a decimal literal like 3.5?
double. To make it a float you must add f: 3.5f.
Practice
-
easy Create variables for a student's name, roll number, percentage and whether they passed. Print them in sentences.
-
easy Pick the best type for each: age of a person, population of India, price of a pizza, first letter of your name, whether it's raining, number of stars in a galaxy.
-
easy Which names are valid?
_count,2fast,my-name,$price,class,totalAmount,total amount. -
medium Predict the final values of
aandb:
int a = 10;int b = a;a = 20;b = b + a;-
medium Create a constant for the speed of light (299,792,458 m/s) using underscores and print it.

Discussion