Beginner 9 min

Variables and types

Declare a Java variable and see how its type determines which values it can accept.

Declare the type and name

In int tickets = 3;, int is the type, tickets is the name, and 3 initializes the variable. The compiler checks assignments and operations against the declared type. An int holds a signed 32-bit integer, while boolean holds true or false.

How it works

Start by asking what kind of data you want to store. An int is suitable for a whole ticket count. A boolean answers a yes-or-no question. Declaring the type tells the compiler which values and operations make sense, so it can catch a mismatched assignment before the program runs.

Update and observe

When tickets = tickets + 2; runs, the addition uses the old value, then writes the new value to tickets. If you previously assigned int original = tickets;, original contains a copy of the primitive value and stays the same.

Interpret division

Integer division drops the fractional part toward zero. 5 / 2 evaluates to 2, even if you then store the result in a double. Make an operand a floating-point value first, for example 5.0 / 2, to get 2.5.

Code example

public class Main {
    public static void main(String[] args) {
        int tickets = 3;
        int original = tickets;
        tickets = tickets + 2;
        System.out.println(original);
        System.out.println(tickets);
    }
}

Check your understanding

Print the number of full pairs and the remaining tickets as two lines. For 5 tickets, there are 2 pairs and 1 ticket left.

See the example and explanation
Example 1
Given 5
Answer 2 1
Example 2
Given 8
Answer 4 0

Divide two integers by computing tickets / 2. Use tickets % 2 to find whether one ticket is left over.

Open practice problem
Next lessonStrings and text comparisons