Algorithms

Variables and constants: the labeled box of programming

Cover of the article Variables and constants: the labeled box of programming
Focused reading

Understand the context.
Put it into practice.

Leia este artigo em português

In this article
  1. What is a variable?
  2. What does the equals sign mean in programming?
  3. How do you create and use variables in Python, PHP, C and Java?
  4. What is a strongly typed language?
  5. What is Java’s var?
  6. How do you swap the values of two variables?
  7. What is a constant and why use one?
  8. What are the rules for naming a variable?
  9. Now you ask: what if I use a variable that hasn’t received a value yet?
  10. What are the most common mistakes with variables?
  11. Now it’s your turn!

A variable is a name the program gives to a place in memory where it stores a value, and that value can be changed while the program runs. A constant is a name for a value that stays the same from start to finish.

A program is a sequence of steps, and variables are what those steps work with. They show up in every article here, from functions to arrays and matrices. This is the article to come back to whenever the foundation feels shaky.

Think of a box with a label stuck on it. The label says “age”. Inside the box there’s a paper with the number 20. When you need the age, you look at the paper. When the age changes, you throw the paper away and put in another one, with 21. The label stays the same. The box is the variable, the label is the name and the paper is the value.

Three-panel comic: a box with the label age holds a paper with the number 20, the paper is swapped for another one with 21, and the label stays the same
The variable as a box: the value changes, the name stays the same.

What is a variable?

Every variable has a name and a value. When the program creates a variable, it reserves a space in the computer’s memory and associates that space with the name you chose. From then on, you use the name, and the computer takes care of finding the place.

In some languages, the variable also has a declared type, which says what kind of value fits there. In C and Java, you have to state the type and the name before you use the variable. In Python and PHP, you don’t write the type: the variable comes into existence when it gets its first value.

What does the equals sign mean in programming?

Here’s the first catch. In math, the equals sign states that both sides are worth the same. In programming, it’s an order called assignment: calculate what’s on the right and store it in the variable on the left.

That’s why the line age = age + 1 makes sense in a program, even though it looks absurd in an equation. The computer reads the current value, adds 1 and stores the result in the same variable. The old value is replaced.

Three steps of the line age = age + 1: read the value 20 stored in the variable, calculate 20 + 1 and store 21 in the same variable
Assignment has a direction: first the right side is calculated, then the result is stored in the name on the left side.

Got it? The variable stores one value at a time. Once it stored the 21, the 20 stopped existing.

How do you create and use variables in Python, PHP, C and Java?

The program below does the same thing in the four languages: it creates variables, updates one of them, uses a constant in a calculation, shows that uppercase and lowercase matter, swaps two values and makes a copy.

Python:

# Variables and constants: store, read, update and swap values

DELIVERY_FEE = 7.5              # constant by convention: name in uppercase

age = 20                        # creates the variable age and stores 20
print("age:", age)

age = age + 1                   # reads 20, adds 1 and stores 21 in place of the 20
print("age after the birthday:", age)

price = 19.9
quantity = 3
total = price * quantity + DELIVERY_FEE
print("order total: %.2f" % total)

name = "Ana"
Name = "Bia"                    # uppercase and lowercase make a difference
print("name and Name are different variables:", name, Name)

a = 5
b = 8
print("before the swap: a = %d, b = %d" % (a, b))
aux = a                         # keeps the 5 before it gets erased
a = b
b = aux
print("after the swap:  a = %d, b = %d" % (a, b))

a = b                           # copy: a gets the value that is in b
b = 100                         # changing b afterwards doesn't change a
print("after the copy:  a = %d, b = %d" % (a, b))

PHP:

<?php
// Variables and constants: store, read, update and swap values

const DELIVERY_FEE = 7.5;       // constant: the value can't change

$age = 20;                      // creates the variable $age and stores 20
echo "age: $age\n";

$age = $age + 1;                // reads 20, adds 1 and stores 21 in place of the 20
echo "age after the birthday: $age\n";

$price = 19.9;
$quantity = 3;
$total = $price * $quantity + DELIVERY_FEE;
printf("order total: %.2f\n", $total);

$name = "Ana";
$Name = "Bia";                  // uppercase and lowercase make a difference
echo "name and Name are different variables: $name $Name\n";

$a = 5;
$b = 8;
printf("before the swap: a = %d, b = %d\n", $a, $b);
$aux = $a;                      // keeps the 5 before it gets erased
$a = $b;
$b = $aux;
printf("after the swap:  a = %d, b = %d\n", $a, $b);

$a = $b;                        // copy: $a gets the value that is in $b
$b = 100;                       // changing $b afterwards doesn't change $a
printf("after the copy:  a = %d, b = %d\n", $a, $b);

C:

/* Variables and constants: store, read, update and swap values */
#include <stdio.h>

#define DELIVERY_FEE 7.5        /* constant: the value can't change */

int main(void) {
    int age = 20;               /* creates the variable age, of type int, and stores 20 */
    printf("age: %d\n", age);

    age = age + 1;              /* reads 20, adds 1 and stores 21 in place of the 20 */
    printf("age after the birthday: %d\n", age);

    double price = 19.9;
    int quantity = 3;
    double total = price * quantity + DELIVERY_FEE;
    printf("order total: %.2f\n", total);

    const char *name = "Ana";
    const char *Name = "Bia";   /* uppercase and lowercase make a difference */
    printf("name and Name are different variables: %s %s\n", name, Name);

    int a = 5;
    int b = 8;
    int aux;
    printf("before the swap: a = %d, b = %d\n", a, b);
    aux = a;                    /* keeps the 5 before it gets erased */
    a = b;
    b = aux;
    printf("after the swap:  a = %d, b = %d\n", a, b);

    a = b;                      /* copy: a gets the value that is in b */
    b = 100;                    /* changing b afterwards doesn't change a */
    printf("after the copy:  a = %d, b = %d\n", a, b);
    return 0;
}

Java:

// Variables and constants: store, read, update and swap values
public class Main {
    static final double DELIVERY_FEE = 7.5; // constant: the value can't change

    public static void main(String[] args) {
        int age = 20; // creates the variable age, of type int, and stores 20
        System.out.println("age: " + age);

        age = age + 1; // reads 20, adds 1 and stores 21 in place of the 20
        System.out.println("age after the birthday: " + age);

        double price = 19.9;
        int quantity = 3;
        double total = price * quantity + DELIVERY_FEE;
        System.out.printf("order total: %.2f%n", total);

        String name = "Ana";
        String Name = "Bia"; // uppercase and lowercase make a difference
        System.out.println("name and Name are different variables: " + name + " " + Name);

        int a = 5;
        int b = 8;
        System.out.printf("before the swap: a = %d, b = %d%n", a, b);

        int aux = a; // keeps the 5 before it gets erased
        a = b;
        b = aux;
        System.out.printf("after the swap:  a = %d, b = %d%n", a, b);

        a = b;   // copy: a gets the value that is in b
        b = 100; // changing b afterwards doesn't change a
        System.out.printf("after the copy:  a = %d, b = %d%n", a, b);
    }
}

Output:

age: 20
age after the birthday: 21
order total: 67.20
name and Name are different variables: Ana Bia
before the swap: a = 5, b = 8
after the swap:  a = 8, b = 5
after the copy:  a = 5, b = 100

The output is the same. What changes is the way you write it:

  • Python: just write the name, the equals sign and the value.
  • PHP: every variable name starts with a dollar sign ($). You don’t need to declare it beforehand either.
  • C: the variable is declared with the type in front, as in int age or double price. It can only be used after the declaration.
  • Java: as in C, the type comes in front, as in int age or String name. And the whole program lives inside a class.

One Java detail: the total line uses the number format configured on the computer. I ran the same program with Java set to Brazilian Portuguese, and it came out as 67,20, with a comma.

Focus on the concept, not the language! In all four, the idea is the same: a name, a value and the assignment that stores it.

Look at the last part of the output. After a = b, both variables store 5. When b gets 100, a keeps its 5. Assignment copies the value. It doesn’t tie one variable to the other.

What is a strongly typed language?

Go back to the program and compare the declarations. In Python and PHP, the same name can get a number now and a text later. I tested both: I stored 20 in age, then I stored the text “twenty”, and both printed twenty, without complaining. The PHP manual calls this dynamic typing: the variable’s type isn’t written, it’s decided while the program runs.

In Java, the rule is different. The language’s documentation says it’s statically typed: every variable has to be declared, with a type and a name, before it’s used. And it also says it’s strongly typed: the type limits the values the variable can hold and the operations that can be done with them. In practice, the type is glued to the name, and the one who checks it is the compiler, before the program runs. I repeated the test in Java, with int age = 20; and then age = "twenty";:

error: incompatible types: String cannot be converted to int

The program never even came to exist. That’s the trade a strongly typed language offers: you write more in the declaration, and the type error shows up at compile time, not in the middle of the run.

And C, which also requires the type in the declaration? I ran the same test with GCC 13. It compiled the line, with just a warning, and the program printed a meaningless number:

warning: assignment to 'int' from 'char *' makes integer from pointer without a cast [-Wint-conversion]

So declaring the type isn’t enough for the language to be strict about it. In this test, Java refused the mix, and C let it through with a warning. Got the difference?

What is Java’s var?

Writing the type in every declaration gets tiring, and it’s often obvious: in String name = "Ana", the value already shows that it’s a text. That’s why, since JDK 10, Java accepts the word var in place of the type, in local variables that are born with a value. The compiler looks at the initial value and works out the type by itself. This feature is called type inference.

public class Main {
    public static void main(String[] args) {
        var age = 20;     // the compiler infers int
        var price = 19.9; // infers double
        var name = "Ana"; // infers String

        age = age + 1; // age is still an int
        System.out.println(name + " is " + age + " years old and paid " + price);
    }
}

Output:

Ana is 21 years old and paid 19.9

IMPORTANT: var doesn’t turn Java into Python. The type is worked out only once, in the declaration, and stays fixed. The proposal that created the feature says so in plain words: the idea was to write less while keeping the type checking done by the compiler. I ran the test: I declared var age = 20; and then tried age = "twenty";. The error was the same as before:

error: incompatible types: String cannot be converted to int

And, since the type comes from the initial value, without an initial value there’s nothing to work out. The line var total; doesn’t compile:

error: cannot infer type for local variable total
  (cannot use 'var' on variable without initializer)

Java isn’t alone in this. The same proposal lists other statically typed languages that already had a similar feature: auto in C++, var in C# and the declaration with := in Go. In all of them, the programmer writes less, and the compiler still knows the type of every variable.

Is it worth using all the time? Oracle’s documentation answers with a warning: var can make code easier to read, when it removes repeated information, and harder to read, when it hides useful information. In var name = "Ana", the type is right there. In var result = calculate(), whoever reads it has to go after the function to find out what came back. While you’re learning, writing the type helps you see what each variable stores.

How do you swap the values of two variables?

You have a = 5 and b = 8 and you want to swap them. The first impulse is to write a = b and then b = a. It doesn’t work: the first line erases the 5, and both variables end up with 8.

The solution is the same as for swapping the contents of two glasses: you need a third glass. In programming, it’s called an auxiliary variable, also known as a temporary variable.

Table with the values of a, b and aux after each line of the swap: aux = a, a = b and b = aux, ending with a = 8 and b = 5
The auxiliary variable keeps the 5 before the line a = b erases it.
See the swap animation, with and without the auxiliary variable
Animation of swapping the values of two variables with and without an auxiliary variable
With the auxiliary, the swap works in three lines. Without it, the 5 is lost.

This three-line swap comes back in sorting algorithms, like bubble sort. It’s worth memorizing.

What is a constant and why use one?

In the program, the delivery fee is 7.5 and shouldn’t change. Instead of scattering the number 7.5 across the code, we gave it a name: DELIVERY_FEE. That brings two advantages. Whoever reads the code understands what the number means. And, if the fee changes, you change a single line.

Each language handles constants its own way:

  • PHP: the keyword const (or the define function) creates a constant. The name has no dollar sign, and the value can’t be redefined while the script runs.
  • C: the #define directive gives a name to a fixed value. Another way is to declare the variable with the keyword const.
  • Java: the keyword final prevents the variable from getting another value. The custom is to declare the constant with static final and write the name in uppercase.
  • Python: there’s no real constant. There’s a convention: names written in uppercase letters signal values that shouldn’t be changed.

I tried changing the constant in all four languages. In PHP, the line DELIVERY_FEE = 9.0; doesn’t even get to run:

Parse error: syntax error, unexpected token "="

In C, with const double DELIVERY_FEE = 7.5; followed by DELIVERY_FEE = 9.0;, the compiler refuses:

error: assignment of read-only variable 'DELIVERY_FEE'

In Java, with static final double DELIVERY_FEE = 7.5; and then DELIVERY_FEE = 9.0;, the compiler refuses too:

error: cannot assign a value to static final variable DELIVERY_FEE

In Python, the same attempt goes through without any warning, and the program prints 9.0. IMPORTANT: in Python, the uppercase letters are an agreement between programmers. The language doesn’t prevent the change.

There’s also a naming custom: variable names start in lowercase, and constant names go in uppercase. In Java and in Python, the words of a constant are separated by underscores, as in DELIVERY_FEE.

What are the rules for naming a variable?

RulePythonPHPCJava
How it startsa letter or an underscorea dollar sign, then a letter or an underscorea letter or an underscorea letter, an underscore or a dollar sign
Can it have digitsyes, but not at the startyes, but not right after the dollar signyes, but not at the startyes, but not at the start
Uppercase and lowercaseare differentare differentare differentare different
Forbidden namesthe 35 reserved words, like class and while$this can’t be assignedthe language’s reserved wordsthe reserved words, like class and while
Naming rules in the four languages.

When a rule is broken, the program doesn’t even start. In Python, the line 2grade = 7 produces:

SyntaxError: invalid decimal literal

And class = 5, which uses a reserved word, produces:

SyntaxError: invalid syntax

Besides the rules, there’s common sense. The computer accepts x1, aaa and thing. Whoever reads the code a month from now, and that someone is you, will thank you for final_grade, order_total and delivery_fee.

Now you ask: what if I use a variable that hasn’t received a value yet?

It depends on the language, and here the four behave in very different ways. I tested the same situation: showing the variable total without ever storing anything in it.

In Python, the program stops with an error:

NameError: name 'total' is not defined

In PHP, the program keeps going, the variable is null and a warning shows up:

Warning: Undefined variable $total

In C, declaring int total; reserves the space, but doesn’t put anything in it. The initial value is indeterminate: the variable holds whatever was already in that piece of memory. The compiler, with warnings turned on, alerts you:

warning: 'total' is used uninitialized [-Wuninitialized]

IMPORTANT: in C, local variables aren’t initialized automatically. Always give them an initial value, as in int total = 0;.

In Java, the program doesn’t even compile. With int total; followed by System.out.println(total);, the compiler stops at the second line:

error: variable total might not have been initialized

Java doesn’t give local variables an initial value, and it doesn’t let you read one of them before you store something in it either.

What are the most common mistakes with variables?

  • Reading the equals sign as equality. It’s an order to store, and it works from right to left.
  • Swapping two values without an auxiliary variable. The first assignment erases one of the values.
  • Getting uppercase and lowercase wrong. total, Total and TOTAL are three different names.
  • Forgetting the dollar sign in PHP or putting it on a constant. A variable takes a dollar sign, a constant doesn’t.
  • Using the variable before giving it a value. In Python it’s an error, in PHP it’s a warning, in C the value is unpredictable and in Java the program doesn’t compile.
  • Forgetting to declare the type in C or Java. Without the declaration, the program doesn’t compile.
  • Thinking the copy keeps a link. After a = b, changing b doesn’t change a.
  • Thinking Java’s var lets the variable change type. The type is worked out once, in the declaration, and doesn’t change.
  • Choosing names that say nothing. The program runs, but nobody understands it.

Now it’s your turn!

On paper:

  • Follow it line by line and give the final values: x = 3; y = x; x = x + 2; y = y * x.
  • Which of these names are valid in Python: grade1, 1grade, final_grade, final-grade, while?
  • Write the three lines that swap the values of p and q using the variable temp.

On the computer:

  • Create the variables width and height, calculate the area of a rectangle and show the result in the four languages.
  • Create the constant DAYS_PER_WEEK and use it to calculate how many days there are in 6 weeks.
  • Rotate the values of three variables: a gets the value of b, b gets the value of c and c gets the value of a. How many auxiliary variables do you need?

Try it on your own, without asking anyone for the ready-made answer, not even AI!

See you in the next article!

Stay confident!!!

Sources:

  • PHP, official manual. Variables: Basics, with the dollar sign, the naming rule, the difference between uppercase and lowercase, $this, which can’t be assigned, assignment by value and the warning for an undefined variable.
  • PHP, official manual. Constants, with the constant as a name for a value that can’t change while the script runs, and the convention of uppercase names.
  • PHP, official manual. Constants: Syntax, with the const keyword and the define() function, and the differences between constants and variables, among them the missing dollar sign and the ban on redefining.
  • PHP, official manual. Types: Introduction, with PHP described as a dynamically typed language, in which the type of a variable is determined at runtime.
  • Python, official documentation. Lexical analysis, with the characters a name can have, the digit that can’t be the first character, case that matters and the list of 35 keywords.
  • Python, PEP 8. Style Guide for Python Code, with constants written in capital letters with underscores between the words, and variable names in lowercase.
  • University of Vermont, CS 1210 (Clayton Cafiero). Names, variables, and assignment, with the constant as a variable whose value is left unchanged and the note that uppercase constant names aren’t enforced by Python.
  • UMBC, CMSC 201. Lab 3 pre-lab, with the variable seen as a box that stores a value, and the assignment operator, the equals sign, used to put the first value in it.
  • Princeton University, COS 126 (Sedgewick and Wayne). 1.2 Built-in Data Types, with declaration and assignment statements, variables that start uninitialized and the equals sign as assignment, not mathematical equality (PDF, lecture slides).
  • Oracle, The Java Tutorials. Primitive Data Types, with the definition of a statically typed language, the type that determines the values and the operations of a variable, and the compile-time error when an uninitialized local variable is read.
  • Oracle. The Java Language Specification, Java SE 21 Edition, chapter 4: Types, Values, and Variables, with the definition of a strongly typed language, in which types limit the values a variable can hold and the operations on those values.
  • Oracle, Java SE 21. Local Variable Type Inference, with var in JDK 10 and later, for local variables with an initializer, and the warning that it can make code more readable or less readable.
  • OpenJDK. JEP 286: Local-Variable Type Inference, with the goal of writing less while keeping static type safety, and the list of languages with a similar feature, among them C++, C# and Go.
  • Oracle, dev.java. Creating Variables and Naming Them, with the final keyword, which indicates a value that will never change, case-sensitive names and the convention for constants such as static final int NUM_GEARS = 6.
  • GNU, The GNU C Language Manual. Identifiers, with the C identifier as a sequence of letters, digits and underscores that doesn’t start with a digit.
  • GNU, The C Preprocessor. Object-like Macros, with #define used to give symbolic names to numeric constants and the convention of macro names in uppercase.
  • Carnegie Mellon University, SEI CERT C Coding Standard. EXP33-C. Do not read uninitialized memory, with local, automatic variables that take unexpected values when they’re read before being initialized.
  • The examples were run on Python 3.13, PHP 8.3, GCC 13 and Java 21.

Share this article

About the author

Walmir Silva

Hi! I'm Walmir, a software engineer with an MBA in Software Engineering, the mind behind GrowthCode and the author of the book "Além do Código" (in Portuguese).

If you think programming is just about writing code, get ready to broaden your horizons. Here, we go beyond the code and explore the fascinating intersections between technology, business, the arts and philosophy.

Are you looking for career growth? Do you want to stand out in a competitive market? Are you after a life richer in knowledge and fulfillment? Then you've come to the right place. At GrowthCode, we offer deep insights, proven strategies and a touch of philosophical wisdom to fuel your personal and professional growth.

See all articles →

Continue the conversation

Share your perspective

Your email address will not be published. Required fields are marked *

We keep the IP address and browser of commenters for 6 months, to block spam and because Brazil’s Marco Civil da Internet requires access records to be kept for that period. See how we handle your data (in Portuguese).

Find your next answer

What do you want to learn?

Cookie preferences

Optional cookies start off. You can change your choice at any time on this screen.

NecessaryAlways on

They store your cookie choice and its record code, and keep the site working. They are not used for advertising.

They count visits and show how the site is used: Google Analytics and Microsoft Clarity, loaded by Google Tag Manager.

They show Google AdSense ads without personalization. The cookies in this category limit how often ads repeat and measure their results.

Uses your browsing to choose ads and build ad audiences: Google ads chosen by your interests and Google signals in Analytics. When off, ads are shown without personalization. Requires Advertising.

You can also block cookies in your browser settings. Details in the Privacy policy (in Portuguese).