Definite assignment follows every branch
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.
Declare variables for a rectangle's width (8) and height (5). Print its area and perimeter on separate labelled lines.
Start with int balance = 100;. Deposit 40, withdraw 25, then double it, printing the balance after each step.
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
What is the difference between declaring, initializing and assigning a variable? Give one line of Java for each.
Why does Java refuse to compile a read of an uninitialized local variable when C happily compiles it?
Where does the value of int n = 5; live while main runs, and what happens to it when main returns?
Why does a = b; b = a; not swap two variables?
Expected output
It is 31 degrees: drink water