Skip to main content

Lesson 2 of 5 15 min read

Variables, primitive data types and operators

Store values in variables, choose the right primitive type and calculate with arithmetic, assignment and comparison operators.

In this lesson you will

  • Declare, initialise and update variables
  • Choose an appropriate primitive type for a value
  • Use arithmetic, assignment and comparison operators and predict their results

Variables are labelled boxes

A variable is a named location in memory that holds a value. In Java you declare a variable with a type and a name, and usually give it a starting value:

Java
int age = 21;
double price = 499.50;
boolean isEnrolled = false;
char grade = 'A';
String name = "Priya";
Each variable is a named box holding one value of its type

age (int) holds 21; price (double) holds 499.50; isEnrolled (boolean) holds false; grade (char) holds 'A'; name (String) holds "Priya"

The type tells Java what kind of data the variable holds and how much memory it needs. Java is statically typed: once age is an int, it can only hold whole numbers.

You can change a variable's value later with the assignment operator =:

Java
int score = 10;
score = 15;          // replaces 10 with 15
score = score + 5;   // reads 15, adds 5, stores 20

The eight primitive types

TypeHoldsExample
byteWhole numbers from -128 to 127byte level = 3;
shortWhole numbers from -32,768 to 32,767short year = 2026;
intWhole numbers, about ±2.1 billionint students = 120;
longVery large whole numberslong views = 9_000_000_000L;
floatDecimal numbers, less precisefloat ratio = 0.75f;
doubleDecimal numbers, the default choicedouble gpa = 8.6;
charA single characterchar initial = 'D';
booleantrue or falseboolean passed = true;

For most programs, int for whole numbers, double for decimals and boolean for yes/no are enough. String is not a primitive: it is a class for text, written in double quotes.

Arithmetic operators

Java
int a = 17;
int b = 5;
System.out.println(a + b);   // 22
System.out.println(a - b);   // 12
System.out.println(a * b);   // 85
System.out.println(a / b);   // 3   (integer division drops the decimal part)
System.out.println(a % b);   // 2   (remainder)
System.out.println(17.0 / 5); // 3.4 (one double operand gives a double result)

Integer division surprises many beginners: when both operands are int, the result is an int and the fractional part is discarded. Make at least one operand a double to keep decimals.

The remainder operator % is very useful. For example, n % 2 == 0 tells you whether n is even.

Assignment shortcuts

Java
int count = 0;
count += 5;   // same as count = count + 5  -> 5
count -= 2;   // same as count = count - 2  -> 3
count *= 4;   // -> 12
count++;      // add one -> 13
count--;      // subtract one -> 12

Comparison operators

Comparisons produce a boolean:

OperatorMeaningExample (x = 7)
==equal tox == 7 is true
!=not equal tox != 7 is false
> / <greater / less thanx > 10 is false
>= / <=greater / less than or equalx <= 7 is true

Note the difference: = assigns a value, while == compares two values.

Putting it together

Java
public class Bill {
    public static void main(String[] args) {
        double mealCost = 850.0;
        int people = 4;
        double tipPercent = 10;

        double total = mealCost + mealCost * tipPercent / 100;
        double perPerson = total / people;

        System.out.println("Total: " + total);          // Total: 935.0
        System.out.println("Each pays: " + perPerson);  // Each pays: 233.75
    }
}

The + operator also joins text: "Total: " + total builds a single String.

Hands-on exercise

Write a program that stores the length and width of a rectangle (in metres) as double variables, then prints its area and perimeter. Next, store a number of minutes as an int (for example 135) and print it as hours and minutes ("2 hours 15 minutes") using / and %.

Knowledge check

3 questions • 70% to pass • Practice only, no certificate

  1. 1.What is printed?
    CODE
    int total = 10;
    total += 3;
    total++;
    System.out.println(total);
  2. 2.Which declaration is valid Java?
  3. 3.What is the result of 9 / 2 in Java when both values are int?
0 of 3 answered

Key concepts

  • A variable has a type, a name and a value; its type cannot change.
  • Use int for whole numbers, double for decimals, boolean for true/false and String for text.
  • Integer division drops the fractional part; % gives the remainder.
  • = assigns a value, == compares two values and produces a boolean.