Java Variables

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.

  • int is the type, short for integer, which means a whole number.
  • score is the name we chose.
  • = 10 puts the value 10 into the box.
  • The ; ends the statement.

Output

10

Java 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 empty score box.
  • 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 yet
score = 10; // initialization: put the first value in
System.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);
  • String is the type for text.
  • Each time we write player, Java gives back "Alex".
  • The + joins the text pieces together.

Output

Welcome, Alex
Good luck, Alex

You 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 score box.
  • The old value is thrown away, since a box holds one value at a time.

Output

0
10
20

A 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 value
System.out.println(score); // error: variable score might not have been initialized

Output

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 read
System.out.println(score);

Output

0

So 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, so score1 works but 1score is an error.
  • No spaces or special signs. Letters, digits, _, and $ only. high score fails.
  • No reserved words. You cannot use int or class, since Java owns those.
  • Case sensitive. score and Score are 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. playerName tells the reader everything; x tells them nothing.

Here is good camelCase next to names to avoid, with the reason in each comment.

// βœ… Good names
int highScore = 100;
String playerName = "Riya";
// ❌ Avoid: meaningless or wrongly styled
int 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 static marks 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; reads price (100) and discount (30), subtracts to get 70, then stores 70.
  • The two println lines read item and finalPrice by name and print them, joining with +.

Output

Item: Headphones
Final price: 70

Each 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 use
score = 10;
// βœ… Good: declare with a type first
int 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 box
int score = "ten";
// βœ… Good: a whole number in an int box
int score = 10;

Reading a local variable before giving it a value. As you saw, Java refuses to compile this.

// ❌ Avoid: never initialized, then read
int total;
System.out.println(total);
// βœ… Good: give a value first
int 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 type
score = 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. totalPrice beats tp.
  • 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;, like int 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. 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. 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. 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. 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.

Java Primitive Data Types

Share & Connect