Variable declarations and assignment
What you will learn
A variable is a named storage location with a type. A declaration introduces the name and type; initialization supplies its first value. Assignment can replace the stored value.
public class Main { public static void main(String[] args) { int quantity = 6; quantity = 9; System.out.println(quantity); }}Expected output:
9The second assignment replaces the initial value.
How it works
Use int quantity = 6; to declare and initialize a local integer. Later, quantity = 9; assigns a new value without redeclaring the name. Identifiers are case-sensitive. A local variable must be definitely assigned before its value is read. A declaration is not a request for the compiler to display the value.
public class Main { public static void main(String[] args) { int morning = 12; int afternoon = 8; int total = morning + afternoon; System.out.println(total); }}Expected output:
20The total receives the evaluated sum of the two variables.
Common mistakes
Writing int quantity = 9; again in the same local scope is a duplicate declaration, not an update. Use quantity = 9;.
Try it yourself
Store 25 available tickets, assign the remaining count after selling 7, and print it.
These are local Java practice tasks, not automatically graded ByteMind exercises. Use a patched JDK; no network or third-party dependency is needed.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Variable declarations and assignment — knowledge check
Check your understanding of variable declarations and assignment.
What is printed after `int x = 4; x = 7;` and printing x?
Which line updates an existing local int named count?