JOOPs Through Java
All lessons

Unit 2 · Java Fundamentals · 9 min

Variables and data types

A variable is a named box in memory that holds a value. In Java you must say what kind of value the box will hold — that is its data type.

Why this matters

Choosing the right type prevents wrong results (like losing the decimal part of a marks average) and is the base of everything that follows.

Real-life analogy

A variable is a labelled container in your kitchen. The label says both the name (sugar) and the kind of thing it holds (powder, not liquid).

Syntax

Syntax
dataType variableName = value;

Example

Java
public class Types {
    public static void main(String[] args) {
        int age = 19;
        double percentage = 78.5;
        char grade = 'A';
        boolean isPassed = true;
        String name = "Ananya Rao";

        System.out.println(name + " is " + age + " years old");
        System.out.println("Percentage: " + percentage + ", Grade: " + grade);
        System.out.println("Passed? " + isPassed);
    }
}

Output

Ananya Rao is 19 years old
Percentage: 78.5, Grade: A
Passed? true

Step by step

  1. 1`int age = 19;` stores a whole number. int holds values roughly between -2 billion and 2 billion.
  2. 2`double percentage = 78.5;` stores a decimal number.
  3. 3`char grade = 'A';` stores one character in single quotes.
  4. 4`boolean isPassed = true;` stores only true or false.
  5. 5`String name = "Ananya Rao";` stores text in double quotes. String is a class, not a primitive type.
  6. 6The `+` operator joins text with values when one side is a String.

Key points

  • 8 primitive types: byte, short, int, long, float, double, char, boolean
  • String is a class (non-primitive) but is used constantly
  • Use single quotes for char, double quotes for String
  • A variable must be declared before it is used

Common mistakes

  • Writing `int marks = 78.5;` — a decimal cannot fit in an int
  • Using double quotes for a char value
  • Using a variable before giving it a value

Try it yourself

  • Declare variables for a student's name, roll number, marks and pass status, then print them.
  • Try storing 10/3 in an int and in a double, and compare the results.
Open the practice notebook