Core Java · Chapter 2 of 48
Variables and types
By the end of this chapter you can keep values in typed variables and constants, and pick a type big enough for the number you need. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: First steps
- 5 tasks
- Java
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
Why you need this
Ravi needs every counter to know the menu prices, which must not change during the day, and the litres of milk to boil. Meera wants what the whole network takes in a year, in paise. The old system printed a negative number for the year.
In chapter 1 every value was typed straight into the code: 40 here, 40 again there. Change a price and one copy always gets missed. Some numbers have a decimal point, and some are too big for the whole numbers Java uses by default: that is where the negative year came from.
The lesson
Every variable has a type
A variable is a named box, and in Java the box has a fixed type:
public class Platform {
static final int PLATFORMS = 10;
static final double TEA_PER_CUP = 0.004;
public static void main(String[] args) {
int trains = 14;
long passengers = 9_000_000_000L;
double kg = 30 * TEA_PER_CUP;
boolean open = true;
char coach = 'B';
String station = "SBC";
System.out.println(trains + " " + passengers + " " + kg);
System.out.println(open + " " + coach + " " + station);
System.out.println(PLATFORMS);
}
}
14 9000000000 0.12
true B SBC
10
int holds whole numbers up to about 2.1 billion, long much bigger ones, double numbers with a decimal point, boolean true or false, and char one character in single quotes. These five are primitives: plain values. String, text in double quotes, is an object. The underscores in 9_000_000_000L are only for your eyes; the L is not. Leave it out and javac stops, because a plain number in the code is an int:
Platform.java:3: error: integer number too large
long passengers = 9_000_000_000;
^
1 error
error: compilation failed
An int cannot take a decimal either: int kg = cups * 0.004; fails with error: incompatible types: possible lossy conversion from double to int. Keep a double answer in a double.
Inside a method, var lets Java work out the type from the value: var trains = 14; makes an int. The type is still fixed: a later trains = "many"; fails with String cannot be converted to int.
Constants with final
PLATFORMS above is a constant: final means assigned once, static puts it on the class for every method, and the name is in UPPER_SNAKE_CASE by convention. Assign it again in main and javac refuses:
Platform.java:5: error: cannot assign a value to static final variable PLATFORMS
PLATFORMS = 12;
^
1 error
error: compilation failed
A char is a number in disguise
A char is stored as a number: 'B' is 66, '₹' is 8377. So + between a char and an int adds them. Once a String takes part, + joins text instead, and Java works from left to right:
char coach = 'B';
System.out.println(coach + 4);
System.out.println("Coach " + coach + 4);
System.out.println(coach + 4 + " is the coach");
70
Coach B4
70 is the coach
When int is not big enough
The biggest int is 2147483647 and the smallest is -2147483648. Go past either end and Java does not complain: the value wraps around to the other end. Integer.MIN_VALUE - 1 prints 2147483647.
int passengers = 23_000_000;
System.out.println(passengers * 365);
long wrong = passengers * 365;
System.out.println(wrong);
System.out.println(passengers * 365L);
System.out.println(passengers * 365 * 2L);
-194934592
-194934592
8395000000
-389869184
Two int values multiply as int, whatever box the answer goes into, so wrong gets the broken number. With one long in the multiplication, the work is done in long, but it must be there from the first step: in the last line passengers * 365 overflows before 2L is reached.
With variables there is no literal to put an L on. Copy the first one into a long variable before you multiply (chapter 3 shows a shorter way):
long all = passengers;
System.out.println(all * 365);
8395000000
Ledger.java has a main: run it with java Ledger.java to try your code.
Your turn
Your five tasks are at the top, all in Ledger.java. Watch two traps: a char plus an int is a number, not text, and a long box does not save a multiplication that already overflowed as int. Kabir's interview question asks what an int does past its biggest value.
What you build: 5 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
Ledger.java: make the menu prices constants
In Ledger.java, make MASALA_CHAI, CUTTING_CHAI and BUN_MASKA constants: each must be final, stay static and stay an int, with its real price in rupees: masala chai 40, cutting chai 25, bun maska 50.
For example, after your change Ledger.MASALA_CHAI is 40, and code that tries to assign it a new value no longer compiles.
- Task 2
Ledger.java: litres of milk for some cups
In Ledger.java, make milkLitres(cups) return the litres of milk for that many cups, as a double, using MILK_PER_CUP (0.125 litres a cup). No cups need no milk.
For example, milkLitres(8) returns 1.0, milkLitres(3) returns 0.375, milkLitres(100) returns 12.5 and milkLitres(0) returns 0.0.
- Task 3
Ledger.java: put the rupee sign in front of a price
In Ledger.java, make priceTag(price) return the price as text with the rupee sign in front and nothing between them: the RUPEE constant, then the digits of the price. A price of 0 gives ₹0.
For example, priceTag(40) returns ₹40 and priceTag(25) returns ₹25. A result like 8417 means the sign and the price were added as numbers.
- Task 4
Ledger.java: a year of takings without overflowing
In Ledger.java, make yearlyPaise(cupsPerDay, pricePaise, days) return cupsPerDay times pricePaise times days, as a long, without overflowing an int on the way. All three parameters are ints.
For example, yearlyPaise(500_000, 4000, 365) returns 730000000000 and yearlyPaise(20, 4000, 1) returns 80000. Even one busy counter, yearlyPaise(2_000, 4000, 365), is 2920000000, already more than an int can hold.
- Task 5 · interview question
Interview: Ledger.java, predict what an int does past its limit
In Ledger.java, make predictOverflow() return the lines the code in its comment prints, one string per line, in order, written exactly as Java prints them (digits only, with a minus sign for a negative number, no underscores).
The check runs the same code and compares your list with what Java really printed.
What you will learn
- Variables and types: int, long, double, boolean, char and String, and what each one holds.
- final: a constant, assigned once and never changed.
- char and String with +: when + adds numbers and when it joins text.
- Overflow: what happens past the biggest int, and how a long avoids it.
More in First steps
Build "Variables and types" yourself
Tapri runs chai counters at railway stations, and every counter runs a Java program you write. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.