Command Palette

Search for a command to run...

Back to the lesson: Topic 1.1 — Variables: Named Boxes for Values
Core Java · Example 1 of 3

Declare, assign, reassign

A variable is a named place in memory that holds one value of a fixed type. You declare it once with a type and a name, give it a value before you read it, and can change that value later as long as the new value fits the type.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Declare variables for a rectangle's width (8) and height (5). Print its area and perimeter on separate labelled lines.

02

Start with int balance = 100;. Deposit 40, withdraw 25, then double it, printing the balance after each step.

03

Rotate three variables: with a = 1, b = 2, c = 3, end with a = 2, b = 3, c = 1 using exactly one temporary variable.

Explain it without notes

01

What is the difference between declaring, initializing and assigning a variable? Give one line of Java for each.

02

Why does Java refuse to compile a read of an uninitialized local variable when C happily compiles it?

03

Where does the value of int n = 5; live while main runs, and what happens to it when main returns?

04

Why does a = b; b = a; not swap two variables?

Declare, assign, reassign
Sign in to run this example in your browser.

Expected output

Start:  Asha has 3 lives and 50 coins
Later:  Asha has 2 lives and 75 coins
Switch: Ravi is playing now