Variables and Assignment
In the last chapter, you wrote a program that printed text to the screen. That program always did the same thing. The output was fixed because everything in the program was fixed, the exact text was written directly into the code.
Real programs aren’t like that. A program that calculates your tax bill needs to work with your numbers, not numbers chosen by the programmer. A weather app needs to display today’s temperature, not a temperature someone typed in six months ago. For programs to be useful, they need to work with values that can vary: values that come from users, from files, from sensors, from the internet.
That’s what this chapter is about: how Java lets us store, name, and work with values.
Literals: Raw values in code
Before anything else, there’s a term worth knowing. When you write a value directly in your code (a number, some text, true or false) that’s called a literal.
You’ve already used one. In the previous lesson, "Hello, World!" was a string literal. Here are a few more:
Literals work fine for one-off output. But they have a real limitation: they carry no meaning on their own. When you see 42 in the middle of a calculation, you have no idea what it represents. Is it someone’s age? A score limit? A number of days? And if that value appears in ten places and needs to change, you have to find and update every single occurrence.
Variables solve both problems.
Variables: Giving values a name
A variable is a named storage location in memory that holds a value. Instead of writing the same literal in ten places, you store it once and refer to it by name whenever you need it.
Here’s what a variable declaration looks like:
int passingScore = 42;There are three things on this line.
intis the type: it tells Java what kind of value this variable can hold.passingScoreis the name: it’s how you’ll refer to the variable.=is an assignment: it stores the value on the right into the variable. This is not the equals sign from math. It doesn’t ask whether two things are equal. It’s an instruction: “store this value here.”
Once declared, you refer to the variable by name instead of repeating the value.
Declaration and assignment are actually two separate acts. The line above does both at once, which is the most common form. But you can also do them separately:
int passingScore; // declaration onlypassingScore = 42; // assignmentEither way, Java has one rule: you must assign a value before you read from it. The two-step form comes up when the value isn’t known at declaration time, like when it depends on user input or a condition. You’ll see that in later lessons.
Java refuses to compile this. Some languages silently give uninitialized variables a default value. Java doesn’t. Assign before you read:
The four basic types
Java has many types, but four are enough to get started. Here are those same literals from before, each stored in a properly typed variable:
int passingScore = 42;double pi = 3.14;String city = "Karachi";boolean isOnline = true;Each line uses a different type. int passingScore = 42 stores a whole number: no decimal point, just an integer. double pi = 3.14 stores a number with a decimal point. String city = "Karachi" stores text, always in double quotes. boolean isOnline = true stores a yes-or-no value: it can only ever be true or false.
You’ll use these constantly. The next lesson covers types in much more depth, including some behaviors that will surprise you.
One thing worth noticing:
Stringis capitalized, whileint,double, andbooleanare not. That difference is meaningful in Java:Stringis a different kind of type than the others. You’ll understand exactly why in a later chapter. For now, just remember:Stringgets a capital S.
Naming your variables
Java has a few hard rules for variable names: they must start with a letter, they can’t contain spaces, and they can’t be a word Java already uses for something else (like int or true).
Beyond those rules, everyone follows the camelCase convention: start with a lowercase letter, and capitalize the first letter of each new word.
int numberOfStudents = 30;double accountBalance = 1450.75;String firstName = "Maya";boolean isGameOver = false;Good names describe what the variable contains. userAge is better than x. monthlyRevenue is better than n. The name is documentation. It tells the next reader (often future you) what the value means without them having to trace through the logic.
One thing that trips people up: Java is case-sensitive. score, Score, and SCORE are three completely different variables as far as Java is concerned. By convention, regular variables start with a lowercase letter. You’ll see all-caps names like MAX_SCORE used for constants later in this chapter.
Reassigning a variable
Once a variable is declared, you can change its value with = again. You don’t repeat the type:
Each assignment replaces whatever was there before. But you can’t change the type of value a variable holds:
Java enforces types strictly. If you declared something as an int, it holds integers for its entire life. This strictness is one of Java’s defining characteristics: it catches a whole class of bugs before your program even runs, at the cost of requiring you to be more explicit upfront.
Checkpoint
What is a literal in Java?
Given this code, what is printed?
String city = "Lahore";
city = "Karachi";
System.out.println(city);Which of the following will Java refuse to compile, and why?