Variables and arithmetic

A variable is a named place for a value. In Java every variable has a type, written before its name, and the type decides what the variable can hold:

  • int holds whole numbers: int age = 15;
  • double holds numbers with a fraction: double price = 2.50;
  • String holds text: String name = "Ada";

The = sign does not mean "equals" here: it assigns the value on the right to the variable on the left. You can assign again later, and the old value is replaced.

1 Width times height Area.java ● in the editor

public class Area {
    public static void main(String[] args) {
        int width = 7;
        int height = 6;
        int area = width * height;
        System.out.println("Area: " + area);
    }
}

+ adds numbers, but when one side is a String it joins text: "Area: " + 42 is "Area: 42". The other operators are -, *, / and % (the remainder of a division: 17 % 5 is 2).

Dividing whole numbers

When both sides of / are int, Java divides without the fraction: 7 / 2 is 3, not 3.5. The result is an int even if you store it in a double. To get the fraction, make one side a double: 7 / 2.0 is 3.5.

This program should print the average of three test scores, Average: 6.666666666666667, but it prints Average: 6.0. Fix the division.

2 Exercise: the average Average.java ○ to do

public class Average {
    public static void main(String[] args) {
        int a = 4;
        int b = 7;
        int c = 9;
        double average = (a + b + c) / 3;
        System.out.println("Average: " + average);
    }
}
Terminal

Editor.sh · Learn to program by writing and running real code in your browser. Nothing to install; your work stays in this browser.

© 2026 xuwaters.com

Step 1 of 2Width times height