Concepts / Understanding Variables and Primitive Types in Java

Understanding Variables and Primitive Types in Java

An identifier is a sequence of one or more characters used to name classes, variables, and subroutines.

  • Programming
Interactive lab

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

  1. 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.
  2. For each assignment, evaluate the complete right side first, looking every name up in the variable table as it is now.
  3. 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).
  4. 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.
  5. 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.
  6. 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.

Educational simulation

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?

  • All three

  • Only score_2

  • Only my score and score_2

  • None of them

Reveal answer
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

Definition

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.

  1. 1
    Check the first character. It must be a letter or an underscore. A digit is not allowed here.
  2. 2
    Check every remaining character. Each must be a letter, a digit, or an underscore.
  3. 3
    Check 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.
  4. 4
    If every check passes, the sequence is a valid identifier.
_underscore may begin a nametotalletters are allowed afterthe start2digits are allowed afterthe first character
Which parts of an identifier are allowed in which positions? This strip annotates each part of the valid identifier _total2.

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.

java
Notes on the code
  • 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.
Key point

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.

java
Notes on the code
  • 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.

scorevariable nameMemory location10current valuerefers tocurrently holds
What does a variable's memory location look like, and how is the name separate from the value currently stored there?

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.

Pattern
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.

  1. 1
    Evaluate the expression on the right side of the equals sign and produce a single result.
  2. 2
    Identify the location named by the variable on the left side.
  3. 3
    Store the result in that location, replacing any value it held before.
  4. 4
    The statement is finished, and the variable now holds the new value until another assignment changes it.
Worked example

Tracing total = price + tax

Suppose price holds 5 and tax holds 2. What does total hold after the statement total = price + tax; runs?

  1. 1
    Evaluate the right side

    The expression price + tax is evaluated first. Java needs the current contents of price and tax.

  2. 2
    Read the variables

    price provides its stored value, 5. tax provides its stored value, 2.

  3. 3
    Compute the result

    5 + 2 produces the result 7.

  4. 4
    Store on the left

    The location named total receives 7. If total held something before, that old value is replaced.

Result

total now holds 7. The values of price and tax are unchanged, because the statement only wrote to total.

Evaluate price +taxprice gives 5tax gives 25 + 2 gives 7Store 7 in total
What happens step by step when Java executes total = price + tax, and how does the stored value change over time?
Output
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.

java
Notes on the code
  • 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.

Before
count = count + 1;

count holds 3 when this line begins

After
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 like
    int my score = 10;
    Why it fails

    Identifiers cannot contain spaces, so the compiler reads my and score as two separate pieces.

    Do this instead

    Use score, or join the words with an underscore, as in my_score.

  • Common mistake

    Starting a name with a digit

    What it looks like
    int 2score = 5;
    Why it fails

    An identifier must begin with a letter or underscore, and a digit is not allowed first.

    Do this instead

    Start with a letter or underscore, as in score2 or _2score.

  • Common mistake

    Assuming capitalization does not matter

    What it looks like
    int score = 2; then printing SCORE
    Why it fails

    Score, score, and SCORE are three different identifiers, so SCORE does not refer to the variable declared as score.

    Do this instead

    Use 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 like
    total = price + tax; assumed to change price
    Why it fails

    Java evaluates the right side first and writes only to the location on the left. Price and tax are read, not changed.

    Do this instead

    Trace 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 like
    count = count + 1; read as a statement that count equals count plus one
    Why it fails

    An assignment is an instruction carried out at a particular time, not a permanent claim that both sides stay equal.

    Do this instead

    Read the statement as: evaluate the right side with current values, then store the result in the left-hand variable.

Tracing Variables by Hand

MEDIUM

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.