Sub topic 6
Literals and Primitive Types
This chapter assumes you know Java's primitive types (int, long, double, char, byte and the rest), how literals like 42 or 1.5f are written, and the basics of var from earlier chapters. Here you will see how var picks a primitive type from a literal or an arithmetic expression, and where that choice differs from what you might have declared by hand.
The core rule: the literal decides
With an explicit type, the declared type on the left can change how the right side is treated. With var there is no declared type, so the initializer alone decides. A plain integer literal is always int. A plain floating-point literal is always double. var never "widens to fit" or "narrows to fit".
| Initializer | Inferred type |
|---|---|
| `42`, `0x1F`, `0b1010`, `017`, `1_000_000` | `int` |
| `42L` | `long` |
| `4.2`, `1e3`, `5d` | `double` |
| `4.2f` | `float` |
| `'x'` | `char` |
| `true`, `false` | `boolean` |
| `"text"` | `String` |
| `(byte) 1` | `byte` |
| `(short) 1` | `short` |
There is no literal syntax for byte or short. A cast is the only way to get those types from var without calling a method that returns them.
Seeing the inferred types
Java has no built-in "print the static type" operation. A simple trick is to pass the variable to a method taking Object. The primitive is boxed, and the wrapper class name tells you the primitive type. The boxing is only a way of looking at the value. The variable itself stays primitive.
public class LiteralTypes {
static String typeOf(Object o) {
return o.getClass().getSimpleName();
}
public static void main(String[] args) {
var a = 42;
var b = 42L;
var c = 4.2;
var d = 4.2f;
var e = 'x';
var f = true;
var g = 0b1010;
var h = 0x1F;
var i = 1_000_000;
var j = 1e3;
var k = 5d;
System.out.println("a " + typeOf(a)); // Integer
System.out.println("b " + typeOf(b)); // Long
System.out.println("c " + typeOf(c)); // Double
System.out.println("d " + typeOf(d)); // Float
System.out.println("e " + typeOf(e)); // Character
System.out.println("f " + typeOf(f)); // Boolean
System.out.println("g " + typeOf(g)); // Integer
System.out.println("h " + typeOf(h)); // Integer
System.out.println("i " + typeOf(i)); // Integer
System.out.println("j " + typeOf(j)); // Double
System.out.println("k " + typeOf(k)); // Double
}
}Binary, hexadecimal, octal and underscore-separated literals change how the number is written, not its type. Without an L suffix they are all int.
Literals that are too large
Because the type is fixed as int before anything else happens, a literal outside the int range is a compile error. It does not quietly become long.
public class TooBig {
public static void main(String[] args) {
// var big = 3000000000; // error: integer number too large
var big = 3_000_000_000L; // long
System.out.println(big); // 3000000000
}
}Use a lowercase l only if you enjoy confusing readers. 1l looks like 11, so write L.
Why `byte b = 10` and `var b = 10` differ
With an explicit type, Java allows an int constant to be assigned to a byte, short or char if the value fits. This is called assignment conversion of constants. With var, the initializer is typed first, and it is just an int.
public class SmallTypes {
public static void main(String[] args) {
byte explicit = 10; // fine: constant 10 fits in a byte
var inferred = 10; // int, not byte
// byte again = inferred; // error: int cannot be converted to byte
var small = (byte) 10; // byte
small += 100; // compiles: compound assignment casts back to byte
System.out.println(small); // 110
small += 100;
System.out.println(small); // -46 (210 wrapped around)
// small = small + 1; // error: small + 1 is an int
System.out.println(explicit + inferred); // 20
}
}The compound operators (+=, -=, *= and so on) insert a hidden cast back to the variable's type. That keeps small += 100 compiling, and it also silently hides overflow. The same thing happens with int variables, which matters in the next sections.
Arithmetic: binary numeric promotion
When you write var x = a + b, the type of x is the type of the whole expression. For numeric operators Java applies binary numeric promotion:
- If either operand is
double, the result isdouble. - Otherwise, if either is
float, the result isfloat. - Otherwise, if either is
long, the result islong. - Otherwise both are promoted to
int, and the result isint.
Rule 4 is the one that surprises people. byte, short and char operands never produce a byte, short or char from +, -, * or /.
public class Promotion {
static String typeOf(Object o) {
return o.getClass().getSimpleName();
}
public static void main(String[] args) {
var x = 'a' + 1; // int
var y = 7 / 2; // int, integer division
var z = 7 / 2.0; // double
var w = 1 + 2L; // long
var s = (short) 1 + (short) 2; // int, not short
var m = 1 + 1.5f; // float
System.out.println(x + " " + typeOf(x)); // 98 Integer
System.out.println(y + " " + typeOf(y)); // 3 Integer
System.out.println(z + " " + typeOf(z)); // 3.5 Double
System.out.println(w + " " + typeOf(w)); // 3 Long
System.out.println(s + " " + typeOf(s)); // 3 Integer
System.out.println(m + " " + typeOf(m)); // 2.5 Float
}
}Note var y = 7 / 2. If you expected 3.5, var is not at fault. The expression is integer division, and the declared type would not have changed the arithmetic either. What var removes is the visible type name that might have reminded you.
The ternary operator follows similar rules. var t = flag ? 1 : 2.0 is a double, so when flag is true, t holds 1.0.
Loop counters and accumulators
var is allowed in the basic for loop, and the counter's type comes from its initializer. var i = 0 gives an int. If you need a long counter, the initializer must say so.
public class Accumulators {
public static void main(String[] args) {
for (var i = 0L; i < 3; i++) { // i is long
System.out.println(i * 1_000_000_000L);
}
var sum = Integer.MAX_VALUE; // int
sum += 1; // compiles, wraps around
System.out.println(sum); // -2147483648
var safeSum = 0L; // long
for (var n = 0; n < 5; n++) {
safeSum += 2_000_000_000; // int literal widened to long
}
System.out.println(safeSum); // 10000000000
}
}An accumulator initialized with var total = 0; is an int for its whole life. If the values you add can exceed about 2.1 billion, initialize it as 0L. With an explicit declaration (long total = 0;) the type is visible and the literal is widened. With var you have to put the suffix on the literal. Neither version is wrong, but var total = 0; is a common source of silent overflow.
Primitive or boxed?
var keeps whatever the initializer's type is. Literals and arithmetic give primitives. Method calls give whatever the method returns, and that can be a wrapper class.
import java.util.HashMap;
import java.util.List;
public class BoxedOrNot {
public static void main(String[] args) {
var parsed = Integer.parseInt("5"); // int
var boxed = Integer.valueOf(5); // Integer
var list = List.of(1, 2, 3);
var first = list.get(0); // Integer
var counts = new HashMap<String, Integer>();
var missing = counts.get("absent"); // Integer, value is null
System.out.println(missing); // null
try {
int unboxed = missing; // unboxing a null reference
System.out.println(unboxed);
} catch (NullPointerException e) {
System.out.println("NullPointerException");
}
System.out.println(parsed + boxed + first); // 11
}
}The line var missing = counts.get("absent"); looks harmless, but the variable is an Integer that can be null. Had you written int missing = counts.get("absent");, the exception would occur on that line. With var, it moves to wherever the value is first unboxed. When a method returns a wrapper type, either accept that and null-check it, or declare int explicitly to document that you expect unboxing.
Characters
var c = 'x' is a char, and c++ works. Arithmetic on a char, however, produces an int, as you saw with 'a' + 1. To keep a char, cast the result.
public class CharInference {
public static void main(String[] args) {
var c = 'a';
c++; // compound/increment keeps char
var next = (char) (c + 1); // cast needed to stay char
var code = c + 1; // int
System.out.println(c); // b
System.out.println(next); // c
System.out.println(code); // 99
}
}Printing shows why this matters. System.out.println(next) prints a letter, while System.out.println(code) prints a number.
Practical guidance for literals
- Use
varwith a literal when the default type is what you want:var retries = 3;,var ratio = 0.75;,var ready = false;. - Add a suffix for
longandfloatright in the literal:var timeoutMillis = 30_000L;. - Avoid
varforbyte,shortandfloatvalues unless the cast or suffix is already part of the expression.byte flags = 0;is clearer thanvar flags = (byte) 0;. - Be wary of
varfor accumulators and averages. State the type if the numeric range or precision matters. - Do not rely on a variable name alone to convey the type.
var size = 0;does not say whethersizeis anintor along.
Exercise
What are the inferred types of a, b and c, and what does the program print?
var a = 10;
var b = a / 4;
var c = a / 4.0;
System.out.println(b + " " + c);
Show answer
a is int, b is int and c is double. a / 4 is integer division, so b is 2, and a / 4.0 promotes a to double, so c is 2.5. The program prints 2 2.5.
Exercise
Why does var small = (byte) 1; small = small + 1; fail to compile while small += 1; compiles? Give a one-line fix for the first statement.
Show answer
small + 1 is binary numeric promotion to int, and an int cannot be assigned to a byte variable without a cast. The compound assignment += includes an implicit cast back to the variable's type. The fix is small = (byte) (small + 1);.
Exercise
A loop declares var total = 0; and adds int values from a list whose sum can reach 5 billion. What is wrong, and how do you fix it with var?
Show answer
total is an int, so the sum overflows with no error, because += silently casts back to int. Initialize it as a long with var total = 0L;. Adding int values to a long widens them before the addition, so the sum stays correct.