Skip to content
wannacode

Variables and types

Problem

The price is in three places

In an online shop one price shows up in several places: in the catalog, in the cart and at checkout. If it is written as a number everywhere, here is what happens:

System.out.println("Headphones: €49.90");
System.out.println("In the cart: headphones, €49.90");
System.out.println("To pay: €49.90");

Tomorrow the headphones are on sale. You have to find and fix every 49.90. Miss one, and the customer sees two different prices.

The idea

A variable: a name for a value

Write the price once and give it a name. Then write the name everywhere.

double price = 49.90;
System.out.println("Headphones: €" + price);
System.out.println("In the cart: headphones, €" + price);
System.out.println("To pay: €" + price);
Output
Headphones: €49.9
In the cart: headphones, €49.9
To pay: €49.9

double price = 49.90; creates a variable: a place in memory with a name (price), a type (double, a decimal number) and a value (49.90). Wherever the code says price, the program takes the value from there.

+ between text and a value glues them into one text. That is why the spaces are inside the quotes.

The zero at the end disappeared: 49.90 came out as 49.9. For the number it is the same thing. You will see how to show the price with two digits after the decimal point in the lesson on input and output.

More precisely, if you are curious
  • A name starts with a letter and has no spaces. Write it in lowercase, and start each next word with a capital letter: price, pricePerNight. Uppercase and lowercase letters matter: price and Price are two different names.
  • The language also allows names with letters outside English (café), but do not do it. Code all over the world uses plain Latin names, and that is how your colleagues will write too.
  • A variable you have not given a value yet cannot be used. The compiler stops with an error.

The idea

Kinds of values

The type says what the variable can hold. Here are the main ones:

String name = "Backpack";
double price = 39.90;
int stock = 12;
boolean onSale = true;
char size = 'M';
System.out.println(name + ", size " + size);
System.out.println("Price: €" + price);
System.out.println("In stock: " + stock + " items");
System.out.println("On sale: " + onSale);
Output
Backpack, size M
Price: €39.9
In stock: 12 items
On sale: true
  • int: a whole number, for example a count.
  • double: a decimal number, for example a price or a weight. In code the decimal separator is a point: 39.90.
  • boolean: yes or no, true or false.
  • char: one character, in single quotes: 'M'.
  • String: text, in double quotes: "Backpack". This is a string, a sequence of characters.
More precisely, if you are curious

String has a capital letter because it is not a simple type like int, but a class. The simple types (int, double, boolean, char and so on) hold the value itself. String is a reference type: the variable holds a link to the text. The difference will matter in the "Classes and objects" module.

All the simple types in Java:

Type Size Values
byte 1 byte from -128 to 127
short 2 bytes from -32,768 to 32,767
int 4 bytes from -2,147,483,648 to 2,147,483,647
long 8 bytes from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 4 bytes decimal, up to about ±3.4 · 10³⁸, about 7 significant digits
double 8 bytes decimal, up to about ±1.8 · 10³⁰⁸, about 15 to 16 significant digits
char 2 bytes one Unicode character, codes from 0 to 65,535
boolean not defined true or false

A number in code is an int or a double, unless you say otherwise. L at the end makes a number a long, f makes it a float. Underscores between digits only make it easier to read:

long population = 8_100_000_000L;
float weight = 1.5f;
byte level = 120;
System.out.println(population + " " + weight + " " + level);
Output
8100000000 1.5 120

Java has no decimal. For money, real programs use the BigDecimal class. In this course, to keep it short, we write prices as double.

Try it

Find the bug

The program should print one purchase. It does not compile. Which line is the bug on?

Pick the line with the bug.

The idea

= stores a copy

The = sign is not "equals" as in math. It means: take the value on the right and store it in the variable on the left. This is called assignment. The variable's old value is gone.

When there is another variable on the right, a copy of its value at that moment is stored. The two variables do not stay connected:

int seats = 40;
int seatsAtStart = seats;
seats = 37;
System.out.println("At the start: " + seatsAtStart);
System.out.println("Now: " + seats);
Output
At the start: 40
Now: 37

seatsAtStart gets 40. Then seats becomes 37, but the copy in seatsAtStart stays 40.

Try it

Which value stays?

What will the program print?

int roomA = 12;
int roomB = 20;
roomA = roomB;
roomB = 25;
System.out.println(roomA + " and " + roomB);
Answer

Problem

The sizes are swapped

A photo printing program gets the sizes swapped: width 120 and height 80, when they should be 80 x 120. It looks like you just need to store one in the other and back again:

int width = 120;
int height = 80;
width = height;
height = width;
System.out.println(width + " x " + height);
Output
80 x 80

You got 80 x 80. Where did 120 go?

See it

Swapping with a helper variable

int width = 120;
int height = 80;
int temp = width;
width = height;
height = temp;
System.out.println(width + " x " + height); // 80 x 120
Step by step, in words
  1. The width and the height were entered swapped: 120 and 80.
  2. temp = width: a copy of 120 goes into temp. width still holds 120.
  3. width = height: a copy of 80 goes into width. The old 120 is gone from there, but it is saved in temp.
  4. height = temp: 120 comes back from temp into height.
  5. They are swapped: 80 x 120.

In the naive version, width = height stores 80 in width, and the old 120 is gone. When height = width comes next, width already holds 80, and that is copied back.

The fix is a third, helper variable, temp. It keeps 120 before width is overwritten. Then 120 goes from temp into height, and the sizes come out 80 x 120.

Try it

Put the swap in order

At the shop, two coworkers trade shifts. morning is "Ivan", and evening is "Maria". Put the lines in order so they swap.

  1. String temp = morning;
  2. evening = temp;
  3. morning = evening;
  4. System.out.println("Morning: " + morning + ", evening: " + evening);

The idea

var: the type is inferred

When the type is clear from the value, you can write var instead of it:

var city = "Plovdiv";
var nights = 3;
var pricePerNight = 65.0;
System.out.println(city + ": " + nights + " nights at €" + pricePerNight);
Output
Plovdiv: 3 nights at €65.0

The compiler sees by itself that "Plovdiv" is text, 3 is an int and 65.0 is a double. This is called type inference.

var does not mean "no type". The type is decided by the first value, and after that it does not change:

var nights = 3;
nights = "three";
Message from the compiler
error: incompatible types: String cannot be converted to int

In this course we will mostly write the type explicitly, so you can see it.

More precisely, if you are curious
  • var needs a value right away: var nights; does not compile, because there is no way to tell the type.
  • var is only for variables inside main (and inside the other methods, which come in the "Methods" module).
  • var has been in Java since version 10.

Exercise

Your variables

Solve the tasks in your editor. The values are written in the code, with no reading from the keyboard. Reading is in the next lesson.

1. Swap. The top shelf has 15 books, the bottom one 27. Store them in two variables, swap their values and print before and after.

Output
Before: top 15, bottom 27
After: top 27, bottom 15

2. Age. Store a name and an age in two variables and print them in a sentence.

Output
Maria is 19 years old.

3. A hotel card. Store in variables the name of the hotel (text), the stars (a whole number), the rating (a decimal), whether there is breakfast (yes or no) and the category (one character). Print them.

Output
Hotel: Sea Star
Stars: 4
Rating: 8.7
Breakfast: true
Category: B

More tasks

  • Three in a circle. Three cash registers start the day with €120, €85 and €240. Move the amounts in a circle: the first goes into the second, the second into the third, the third into the first. Use one helper variable. Print 240 120 85.
  • The same with var. Rewrite task 3 with var everywhere. The output should not change.
  • An error on purpose. Store text in an int and a decimal number in an int. Read what the compiler says.

Test

Check yourself

1. What does the line int count = 5; do?
2. Which type is for a price like 12.99?
3. int a = 5; int b = a; a = 9; What is b?
4. Why does swapping two values need a third variable?
5. After var nights = 3;, what is true?

Made by Ivo Gergov as part of Evo Tech's campaign for accessible programming education ·