Java Variables
Table of Contents + β
In the last lesson you learned about Java garbage collection. Now your program needs to remember values, a score, a name, a price. That is what a variable is for.
π€ Why do we need variables?
Picture a small game where the player keeps scoring points. Without a place to keep that number, you would type the same value again and again.
- Name a value once, then use the name everywhere else.
- Change it in one place, and the new value flows through your whole program.
- No hunting down copies to fix by hand.
π¦ What is a variable really?
A variable is a labelled box in memory that holds one value at a time.
- A name, so you can find it again.
- A value, the thing stored inside.
- A type, which says what kind of value is allowed in.
That type part is special to Java. Easier languages like Python skip it, but Java makes you say what kind of value the box holds, then it guards the box and lets only that kind in.
Here is the shape. The type comes first, then the name, then the value.
type name = value;This stores the whole number 10 in a box called score.
int score = 10;System.out.println(score);Read it left to right.
intis the type, short for integer, which means a whole number.scoreis the name we chose.= 10puts the value 10 into the box.- The
;ends the statement.
Output
10Java always wants the type up front. It feels strict, but it catches many mistakes before your program even runs.
βοΈ Declaration vs initialization
Two simple steps, done together or apart.
- Declaration creates the box: type and name.
int score;makes an emptyscorebox. - Initialization puts the first value in.
score = 10;fills it. - One line like
int score = 10;does both at once.
Here we split them, declaring first and giving the value later. The type appears only on the declaration.
int score; // declaration: make the box, no value yetscore = 10; // initialization: put the first value inSystem.out.println(score);Java is happy because by the time we read score, it has a value.
Output
10π Reading and changing a variable
To read a variable, just write its name. Java swaps in whatever is inside the box.
String player = "Alex";System.out.println("Welcome, " + player);System.out.println("Good luck, " + player);Stringis the type for text.- Each time we write
player, Java gives back"Alex". - The
+joins the text pieces together.
Output
Welcome, AlexGood luck, AlexYou can also change what is in the box later. This is reassignment. You do not repeat the type, since the box already exists.
int score = 0;System.out.println(score);
score = score + 10;System.out.println(score);
score = score + 10;System.out.println(score);score = score + 10 looks odd with score on both sides. Here is what Java does.
- It works out the right side first: current value plus 10.
- It puts that result back into the
scorebox. - The old value is thrown away, since a box holds one value at a time.
Output
01020A handy short form
score = score + 10 is so common that Java gives you a shortcut: score += 10. It does the exact same thing. You will see +=, -=, and *= everywhere, so it is good to know early.
π« What if a local variable has no value?
A local variable, the kind you make inside a method like main, will not let you read it until you give it a value. Java refuses to compile.
int score; // β declared but never given a valueSystem.out.println(score); // error: variable score might not have been initializedOutput
error: variable score might not have been initialized System.out.println(score); ^- Reading an empty box would give a meaningless value, a classic source of hard bugs.
- So Java stops you now rather than let a mystery value slip through.
- The fix: give a value before reading, usually right at declaration.
int score = 0; // β
given a value before it is readSystem.out.println(score);Output
0So a local variable must be initialized before you use it. Declaration alone is not enough.
π·οΈ Naming your variables
Some are strict rules Java forces on you. Others are habits that keep code readable.
The strict rules Java enforces.
- Start with a letter,
_, or$. No leading digit, soscore1works but1scoreis an error. - No spaces or special signs. Letters, digits,
_, and$only.high scorefails. - No reserved words. You cannot use
intorclass, since Java owns those. - Case sensitive.
scoreandScoreare two different variables.
The habits good developers follow.
- Use camelCase. Start lowercase, capitalise each new word, like
highScore. Other developers expect it. - Name for what it holds.
playerNametells the reader everything;xtells them nothing.
Here is good camelCase next to names to avoid, with the reason in each comment.
// β
Good namesint highScore = 100;String playerName = "Riya";
// β Avoid: meaningless or wrongly styledint x = 100; // what does x even hold?int High_Score = 100; // not Java's camelCase styleπ§± Kinds of variables and scope
Java sorts variables by where they live. Where a variable lives is its scope, the part of the program where it exists and can be used. Just recognise the names for now.
- Local variables live inside a method like
main, and vanish when the method finishes. Most of yours start here. - Instance variables belong to an object, and each object gets its own copy. More when we study classes.
- Static variables belong to the class itself and are shared by every object. The keyword
staticmarks them.
Here is a quick look so the words are not strangers later.
public class Player { static int playerCount = 0; // static: shared by all players String name; // instance: each player has their own
public static void main(String[] args) { int score = 50; // local: lives only inside main System.out.println(score); }}The big idea about scope: a local variable made inside main cannot be seen from outside main. So two methods can each have their own score without clashing. For now, almost everything you write is local.
π§ A fuller example, line by line
A small shopping example that tracks a price, applies a discount, and prints the result.
public class Cart { public static void main(String[] args) { String item = "Headphones"; // text: the product name int price = 100; // whole number: starting price int discount = 30; // whole number: amount off
int finalPrice = price - discount; // work out what to charge
System.out.println("Item: " + item); System.out.println("Final price: " + finalPrice); }}The walkthrough, line by line.
String item = "Headphones";declares a text box and stores the product name.int price = 100;declares a whole-number box and puts 100 in it.int discount = 30;declares another box for the amount we take off.int finalPrice = price - discount;readsprice(100) anddiscount(30), subtracts to get 70, then stores 70.- The two
printlnlines readitemandfinalPriceby name and print them, joining with+.
Output
Item: HeadphonesFinal price: 70Each variable has a clear name and one clear job, so the code reads almost like a sentence.
β οΈ Common Mistakes
A few things catch people out early.
Forgetting the type when you first declare. Java needs the type the first time. score = 10; alone fails if score was never declared.
// β Avoid: no type on the first usescore = 10;
// β
Good: declare with a type firstint score = 10;Putting the wrong kind of value in a box. A box declared as int holds whole numbers only. Putting text in it is an error. Java checks this for you.
// β Avoid: text in an int boxint score = "ten";
// β
Good: a whole number in an int boxint score = 10;Reading a local variable before giving it a value. As you saw, Java refuses to compile this.
// β Avoid: never initialized, then readint total;System.out.println(total);
// β
Good: give a value firstint total = 0;System.out.println(total);Repeating the type on reassignment. You write the type only once, when you first declare. After that, just use the name.
int score = 0; // declare with typescore = 5; // β
reassign, no type// int score = 5; // β this re-declares and causes an errorβ Best Practices
Small habits that keep your variables clean and clear.
- Name for meaning.
totalPricebeatstp. - Use camelCase. The agreed Java style, so your code matches everyone elseβs.
- Initialize when you declare.
int score = 0;on one line avoids the βnot initializedβ error. - One job per variable. Do not reuse the same box for unrelated values.
π§© What Youβve Learned
A quick recap.
- β A variable is a named box in memory that holds one value at a time, made of a name, a value, and in Java a type.
- β
The shape is
type name = value;, likeint score = 10;. - β Declaration makes the box and initialization puts the first value in; you can do both on one line or split them.
- β You read a variable by its name and change it by reassignment, without repeating the type.
- β A local variable must be initialized before you read it, or Java will not compile.
- β Names follow rules (no leading digit, no spaces, case sensitive) and a style habit (camelCase, meaningful names).
- β Java has local, instance, and static variables, and scope is where each one lives. At first, almost all of yours are local.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What is the correct way to declare a whole-number variable in Java?
Why: Java needs the type first when you declare, so int score = 10; is correct.
- 2
What is the difference between declaration and initialization?
Why: Declaration creates the variable with its type and name. Initialization gives it its first value.
- 3
What happens if you read a local variable that was never given a value?
Why: A local variable must be initialized before it is read, or the program will not compile.
- 4
Which name follows Java's standard style?
Why: Java uses camelCase: start lowercase and capitalise each new word, like highScore.
π Whatβs Next?
You can make a variable now, but you only met int and String so far. Java has a whole set of types for numbers, characters, and true/false values. Letβs go through them next.