Understanding Variables and Primitive Types in Java
An identifier is a sequence of one or more characters used to name classes, variables, and subroutines.
Try it: Assignment, Statement by Statement
How an assignment statement evaluates its right side first (using the names' current values) and only then binds the name on the left: updating x = x + 1, augmented operators like += and //=, chained a = b = 0, simultaneous a, b = b, a + b versus one-at-a-time assignment, rebinding a name to a value of another type, the NameError for a name that was never assigned, and the SyntaxError for a name that breaks the naming rules.
How it works
- Before anything runs, Python compiles the whole program; a name that breaks the rules (starts with a digit, contains a space or a dash, or is a keyword) is a SyntaxError and no line runs at all.
- For each assignment, evaluate the complete right side first, looking every name up in the variable table as it is now.
- Then bind the name(s) on the left to that value: a new name is added to the table, an existing one is replaced (even by a value of a different type).
- x += 5 reads x, applies the operator (+, -, *, //, %, **) and binds the result back to x; a = b = 0 evaluates 0 once and binds a, then b.
- a, b = b, a + b builds the whole right-hand tuple from the OLD values before binding a and b; two separate statements would use the new a in the second line.
- Reading a name that is not in the table raises NameError and the program stops at that line.
Default run (10 steps): A 4-line program. Python first compiles all of it, then runs it top to bottom. The variable table on the right starts empty. … Program finished. Final table: x = 16.
Simplified: The programs are fixed templates: you choose the template, its numbers, the operator and the variable name, never the code. The lab's own small Python tokenizer and parser (written for the statements these programs use: assignments, print calls, if / elif / else, for, while, def and return) checks the text; nothing is executed as real Python. Every program the lab can show was compiled by CPython 3.12 and the lab reproduces its exception type, message, line, caret columns and the printed report. A small interpreter written for the same statements then runs them (integers of any size, the str/float results these templates produce, and print); each program was also run in CPython 3.12 under sys.settrace, and the lab reproduces the variables after every line, the output and the error.
Loading the simulation…
Why Programs Need Names
A program is built from many pieces: classes, variables, and subroutines. To work with any of these pieces, the program must be able to refer to each one by name. In Java, these names are called identifiers. Choosing an identifier looks simple, but the language applies strict rules to every identifier, and a name that looks readable to a person may still be rejected by the compiler. This article builds the ideas you need to name things correctly, to understand what a variable actually is, and to trace what happens when Java runs an assignment.
What do you think happens?
Which of these are valid Java identifiers: my score, 2score, score_2?
Reveal answer
Only score_2 is valid.
my score contains a space, and identifiers cannot contain spaces. 2score begins with a digit, but an identifier must begin with a letter or underscore. score_2 begins with a letter and contains only letters, digits, and underscores, so it follows the rules.
What an Identifier Is
An identifier is a sequence of one or more characters used to name classes, variables, and subroutines.
The key word in that definition is sequence. An identifier is not limited to a single character, and it is not any text you happen to type. It is a particular kind of character sequence that Java is willing to accept as a name. The same naming system covers classes, variables, and subroutines, so a rule you learn for variable names also applies when you name other program parts.
A common misconception is that any readable text can become an identifier. It cannot. Java applies rules to the characters and to the structure of every identifier, so a name must satisfy those rules before the program can use it.
Character Rules for Valid Names
Java states two rules for the form of an identifier. First, an identifier must begin with a letter or an underscore. Second, after that first character, it must consist entirely of letters, digits, and underscores. Put simply, the first character has the fewest choices, and every later character may use letters, digits, or underscores.
- 1Check the first character. It must be a letter or an underscore. A digit is not allowed here.
- 2Check every remaining character. Each must be a letter, a digit, or an underscore.
- 3Check for spaces. An identifier cannot contain spaces at all, so a two-word name must be joined without a gap, or written with an underscore between the words.
- 4If every check passes, the sequence is a valid identifier.
The rule about the first character is the one that most often surprises beginners. A digit may appear later in a name, as in score_2, but it may never be the first character. The same letters arranged differently can therefore produce a valid name or an invalid one.
- The first line fails because identifiers cannot contain spaces.
- The second line fails because the first character is a digit.
- The third line follows both rules, so Java accepts score_2 as a name.
A valid identifier starts with a letter or underscore and uses only letters, digits, and underscores after that. Spaces are never allowed.
Case Sensitivity and Reserved Words
Uppercase and lowercase letters are different in Java, so capitalization changes an identifier. Score, score, and SCORE are three separate names. A program that declares one of them does not automatically declare the others, and a reference to SCORE will not find a variable declared as score. When you read code, check the capitalization of every name as carefully as its spelling.
- Each line declares a different name, because capitalization changes the identifier.
- After these lines run, the three names hold three independent values.
Reserved words are words the language already uses for its own purposes, such as the words that make up Java's statements. Because the language has claimed them, they cannot also be used as names for your classes, variables, or subroutines. A name that is spelled correctly and follows the character rules can still fail if it happens to be a reserved word, so it is worth checking a candidate name against the reserved list when a compiler rejects it.
A Variable Names a Location, Not Its Data
A common beginner belief is that a variable is simply another name for a piece of data. That idea is useful at first, but it hides an important distinction. In Java, a variable name refers to a location in memory that can hold data. The computer keeps track of the actual memory location, so the programmer can work with the name instead of a numerical address.
A helpful picture is a labeled container. The label identifies the container, while the data is what the container currently holds. The container stays the same even when its contents are replaced. This is why one variable can be associated with different values at different points during a program. The name stays fixed, the location stays fixed, and the value inside can change.
The diagram separates the three things that are easy to confuse. The name score is the label a program uses. The memory location is the container that the name refers to. The value 10 is the data the container holds right now. If the value is later replaced, the name and the location remain the same, and only the contents change. The name is therefore not the data itself.
How Java Carries Out an Assignment
An assignment is an instruction for the computer to carry out, not a permanent statement of fact. Its general form is a variable, followed by an equals sign, followed by an expression, and then a semicolon.
variable = expression;Execution follows a specific direction. Java does not look at the variable on the left first. It first evaluates the expression on the right, which produces a result. Then it places that result into the location identified by the variable on the left. If that location already holds data, the new result replaces the old data.
- 1Evaluate the expression on the right side of the equals sign and produce a single result.
- 2Identify the location named by the variable on the left side.
- 3Store the result in that location, replacing any value it held before.
- 4The statement is finished, and the variable now holds the new value until another assignment changes it.
Tracing total = price + tax
Suppose price holds 5 and tax holds 2. What does total hold after the statement total = price + tax; runs?
- 1Evaluate the right side
The expression price + tax is evaluated first. Java needs the current contents of price and tax.
- 2Read the variables
price provides its stored value, 5. tax provides its stored value, 2.
- 3Compute the result
5 + 2 produces the result 7.
- 4Store on the left
The location named total receives 7. If total held something before, that old value is replaced.
total now holds 7. The values of price and tax are unchanged, because the statement only wrote to total.
After total = price + tax; runs with price = 5 and tax = 2, the value of total is 7.Reading Values From Variables in Expressions
The same variable can play two different roles in one assignment. On the left side, the variable identifies the location that will receive a result. Inside the expression on the right side, a variable contributes the value currently stored in its location. The worked example above used price and tax only on the right, where each one supplied its current value. A variable on the left, such as total, was only a destination.
This rule means that the order of statements matters. A variable on the right is read at the moment the expression is evaluated, so the value it provides depends on the assignments that ran before. Tracing a program means keeping track of what each variable holds at each step, rather than assuming a variable holds the value you expected.
- After line 3, total holds 7.
- Line 4 replaces the value in price. The name and location stay the same, but the contents change.
- Line 5 reads the new value of price, so total is replaced with 12.
Assignment Is Not a Mathematical Equation
The equals sign in an assignment resembles the equals sign in a mathematical equation, but the two uses have different meanings. In Java, an assignment tells the computer to perform an operation at a particular time. It does not claim that the two sides will remain equal forever. The statement count = count + 1; would be a contradiction if read as an equation, since no number equals one more than itself. As an instruction, it is perfectly sensible: take the current value of count, add one, and store the result back in count.
count = count + 1;count holds 3 when this line begins
count = count + 1;count holds 4 after this line finishes
Mistakes With Names and Assignments
Common mistake Using a space inside a name
What it looks likeint my score = 10;Why it failsIdentifiers cannot contain spaces, so the compiler reads my and score as two separate pieces.
Do this insteadUse score, or join the words with an underscore, as in my_score.
Common mistake Starting a name with a digit
What it looks likeint 2score = 5;Why it failsAn identifier must begin with a letter or underscore, and a digit is not allowed first.
Do this insteadStart with a letter or underscore, as in score2 or _2score.
Common mistake Assuming capitalization does not matter
What it looks likeint score = 2; then printing SCOREWhy it failsScore, score, and SCORE are three different identifiers, so SCORE does not refer to the variable declared as score.
Do this insteadUse one consistent capitalization for each name, and check the capitalization of every reference.
Common mistake Reading the variable on the left as the source of the value
What it looks liketotal = price + tax; assumed to change priceWhy it failsJava evaluates the right side first and writes only to the location on the left. Price and tax are read, not changed.
Do this insteadTrace each statement by listing the values read on the right and the single location written on the left.
Common mistake Treating the assignment as a fixed equation
What it looks likecount = count + 1; read as a statement that count equals count plus oneWhy it failsAn assignment is an instruction carried out at a particular time, not a permanent claim that both sides stay equal.
Do this insteadRead the statement as: evaluate the right side with current values, then store the result in the left-hand variable.
Tracing Variables by Hand
Trace these four statements, keeping a table of what a and b hold after each line. Starting values: a = 4 and b = 9. Statements: a = b - a; then b = a + b; What are the final values of a and b?
Hints
- Before each line, write down the current values of a and b.
- For a = b - a, read b and a from the current table and write the result into a only.
- After line one, a should be 5. Then read the new a when you evaluate line two.
Key Takeaways
- An identifier is a sequence of characters used to name classes, variables, and subroutines. It must begin with a letter or underscore, use only letters, digits, and underscores, and cannot contain spaces.
- Uppercase and lowercase letters create distinct identifiers, so Score, score, and SCORE are three different names.
- A variable names a memory location that holds data. The name and the stored value are separate, and the value can change while the name keeps referring to the same location.
- An assignment is executed by evaluating the expression on the right, reading current variable values along the way, and then storing the result in the variable on the left.
- An assignment is an instruction carried out at a particular time, not a mathematical equation, so count = count + 1 is meaningful as an update.