Java will not let you pour a large value into a small variable unless you write a cast, but it will happily push a small value into a large variable all by itself. Once you understand the two directions, and the arithmetic rules that follow from them, most of the "why does this number look wrong" moments in a Java program disappear.
The previous lesson in this module covered "How Do Variables, Constants and var Work in Java?", and the next lesson in this module is about "What Operators Does Java Support and When Are They Useful?", which covers the symbols that Java uses for arithmetic and for comparing values.
What is widening?
Converting a type into a larger and more capable one happens automatically. A byte becomes a short. A short becomes an int. An int becomes a long. A long becomes a float, and a float becomes a double. Nothing is lost, so the compiler does it for you.
int count = 42;
long total = count; // fine: the int widens to a long
double ratio = count; // fine: the int widens to a double
short small = 7;
int widened = small; // fine: the short widens to an int
System.out.println(widened + " " + total + " " + ratio);
Widening is the reason that you can add a byte to an int without thinking about it, because the byte is promoted first.
What is narrowing?
Going the other way can throw information away, so the compiler asks you to write an explicit cast that says you really meant it. The cast does not check anything. It simply re-reads the value inside a smaller range.
long big = 300L;
int narrowed = (int) big; // 300, and the cast is required
double price = 19.99;
int whole = (int) price; // 19, and the fraction is discarded
System.out.println(narrowed + " " + whole);
Casting a double to an int cuts the number off towards zero, so 19.99 becomes 19 and -19.99 becomes -19. If you want the number rounded instead, say so with Math.round rather than relying on a cast to do something surprising.
What happens in arithmetic that mixes types?
When an operator works on two numbers of different types, Java widens the smaller one until both sides have the same type. The rule is easy to remember. If either side is a double, the answer is a double. Otherwise, if either side is a float, the answer is a float. Otherwise, if either side is a long, the answer is a long. Otherwise, the answer is an int.
int a = 7;
long b = 3;
double c = 2.5;
System.out.println(a + b); // 10, because the int widened to a long
System.out.println(a + c); // 9.5, because the int widened to a double
System.out.println(a / b); // 2, because both sides became longs
System.out.println(a / 2.0); // 3.5, because one side became a double
System.out.println(7 / 2); // 3
System.out.println(7 / 2.0); // 3.5
System.out.println(7 % 2); // 1
The division line is the one that catches everybody. The expression 7 / 2 is 3, because both sides are whole numbers and whole number division throws the remainder away. Multiply one of them by a decimal number and the same expression gives you 3.5. When you want the remainder as well, the modulus operator gives it to you, and 7 % 2 is 1.
What about compound assignments?
Operators such as += and *= have a rule of their own. The right-hand side is promoted to the type of the variable on the left, and then the result is changed back into that type. That is why adding a double to an int variable throws the fraction away.
int total = 10;
total += 5; // 15
total *= 2; // 30
total /= 7; // 4, because whole number division happens first
byte small = 100;
small += 50; // a compile error: 150 does not fit in a byte
That last line is a real safety net. The compiler refuses a compound assignment whose result cannot fit inside the variable, even though the plain assignment small = 150 would compile and would overflow while the program runs.
What happens when a value is too big?
Whole number arithmetic wraps around silently. There is no exception and there is no warning while the program runs, which is the reason that overflow bugs show up as impossible numbers several days later.
int max = Integer.MAX_VALUE;
System.out.println(max + 1); // wraps around to Integer.MIN_VALUE
long big = Long.MAX_VALUE;
System.out.println(big + 1); // wraps around to Long.MIN_VALUE
When a wrap is not acceptable, use Math.addExact and Math.multiplyExact, because they throw an exception instead of wrapping around. For money, keep the value in whole small units, so that there is no rounding question and no overflow question to answer.
Why do characters turn into numbers?
Arithmetic on a char promotes it to an int, because the arithmetic has to happen somewhere and a char is too narrow to hold the answer. That is why 'A' + 1 is 66, and it is also why the character codes of the letters sit next to each other with no gaps.
char a = 'A';
int code = a + 1; // 66
char b = (char) (a + 1); // 'B'
int sum = 'x' + 'y'; // 232, and not "xy"
System.out.println(code + " " + b + " " + sum);
What happens when you compare a box with a plain value?
Every primitive type has a matching object form, and Java converts between them on its own. That conversion is where a surprising comparison comes from. Two plain numbers are compared by their value. But when one side is an object and the other side is a plain value, Java takes the object apart first and then compares the value inside it.
Integer boxed = Integer.valueOf(1);
int plain = 1;
System.out.println(boxed == plain); // true, because one side is taken apart
System.out.println(boxed.equals(plain)); // true, because the values are the same
System.out.println(boxed.equals(1)); // true
Integer other = Integer.valueOf(1);
System.out.println(boxed == other); // false, because two objects are not the same object
That last line is the one to remember. When you compare two objects with ==, Java compares the references, so it asks whether the two variables point at the same object in memory. When you compare two objects with equals, Java asks whether their contents are the same. The same rule applies to text, which is why equals is the safe habit for anything that might be an object.
How do you convert between text and numbers safely?
Casting is not the only way to move between a String and a number, and the two directions fail in different ways. Turning text into a number is the risky direction, because Integer.parseInt("12a") throws a NumberFormatException while the program is running. The compiler has no idea whether the text holds a number or not. Going the other way never fails, because every value can be turned into text.
The trap in the other direction is arithmetic on text. The expression "1" + 2 produces "12" and not 3, because the left side is text and text joining wins. You have to convert the text first, and the conversion has to happen before the addition rather than after it.
public class TextAndNumbers {
public static void main(String[] args) {
String input = "42";
int parsed = Integer.parseInt(input);
System.out.println("parsed : " + parsed);
System.out.println("doubled : " + (parsed * 2));
System.out.println("text plus number : " + (input + 2));
System.out.println("number as text : " + (parsed + 2));
try {
Integer.parseInt("12a");
} catch (NumberFormatException e) {
System.out.println("bad text : " + e.getMessage());
}
}
}
parsed : 42
doubled : 84
text plus number : 422
number as text : 44
bad text : For input string: "12a"
The two lines in the middle are the whole lesson. The same + operator produced 422 and 44 from code that looks almost the same, and only the first thing on the line decided which one you got. When you are not sure, convert the text into a number first and keep it in a variable that has a number type.
Quick reference
- Widening happens on its own, while narrowing needs an explicit cast that does not check anything.
- Arithmetic widens both sides to the widest type that is present.
- The expression
7/ 2 is3, because whole number division cuts the remainder away. Use % for the remainder. - Casting a double to an int cuts towards zero, and it does not round.
- A compound assignment changes the answer back into the type of the variable, and it refuses to overflow at compile time.
- Plain whole number arithmetic wraps around quietly, while Math.addExact throws an exception instead.
Try it yourself: write a program with an int and a double that both hold the value 7. Divide them both by 2 and print both answers. Then change the divisor to 2.0 and explain the difference. Finally, print Integer.MAX_VALUE + 1 and work out which way the number wrapped.