Understanding Variables and Primitive Data Types in Java

Understanding Variables and Primitive Data Types in Java

6 min read

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.

Java
public class Main {    public static void main(String[] args) {        int age = 21;        System.out.println(age);        System.out.println("Age is " + age);    }}

Output

Code
21Age is 21

Notice: age without quotes prints the value inside the box. "age" with quotes would print the word age.

2. Declare, initialise, assign

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

What happens in memory as each line runs.

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

byte

Whole number

1 byte (8 bits)

-128 to 127

byte b = 100;

short

Whole number

2 bytes

-32,768 to 32,767

short s = 30000;

int

Whole number

4 bytes

about ±2.1 billion

int population = 1400000;

long

Whole number

8 bytes

about ±9.2 × 10^18

long distance = 9000000000L;

float

Decimal number

4 bytes

about 7 digits of precision

float price = 99.5f;

double

Decimal number

8 bytes

about 15 digits of precision

double pi = 3.14159;

char

A single character

2 bytes

one Unicode character

char grade = 'A';

boolean

true or false

not precisely defined

true / false

boolean isPassed = true;

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:

  • long values need L at the end if they're larger than int can hold: 9000000000L. Without it, Java treats the number as an int, which is too big, and gives an error.

  • float values need f: 99.5f. Without it, Java treats decimals as double.

  • char uses 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:

Java
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? Because String is 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: age and Age are different variables.

Conventions (followed by every professional):

  • Variables use camelCase: start lowercase, capitalise each new word: totalMarks, isLoggedIn, studentCount.

  • Use meaningful names: marks not m, isAdult not flag.

  • Booleans usually start with is, has or can: 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.

Java
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 word final also 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:

Java
var count = 10;       // Java infers intvar price = 45.5;     // Java infers double

The 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 an int box (error).

  • long big = 9000000000;: missing L.

  • 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 write a = 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

  1. easy Create variables for a student's name, roll number, percentage and whether they passed. Print them in sentences.

  2. 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.

  3. easy Which names are valid? _count, 2fast, my-name, $price, class, totalAmount, total amount.

  4. medium Predict the final values of a and b:

Java
int a = 10;int b = a;a = 20;b = b + a;
  1. medium Create a constant for the speed of light (299,792,458 m/s) using underscores and print it.

© 2026 Rohit Parihar. All rights reserved.

RP

Discussion

?