Variables, types and final

Java is statically typed: every variable has a type, the type is fixed when the variable is declared, and the compiler checks every use against it. Eight of the types are primitives, written with a keyword and stored as a fixed number of bits; every other type is a class or an interface, and a variable of such a type holds a reference to an object.

The eight primitives

Four hold whole numbers of different widths, two hold floating-point numbers, one holds a single UTF-16 code unit, and one holds true or false. Each wrapper class in java.lang carries the size and the range as constants, which is how the program below prints them instead of trusting a table.

The file Primitives.java:

public class Primitives { public static void main(String[] args) { byte b = 100; short s = 30_000; int i = 2_000_000_000; long l = 9_000_000_000L; float f = 1.5f; double d = 2.5; char c = 'A'; boolean flag = true; System.out.println("byte: " + b + " (" + Byte.SIZE + " bits, " + Byte.MIN_VALUE + " to " + Byte.MAX_VALUE + ")"); System.out.println("short: " + s + " (" + Short.SIZE + " bits, " + Short.MIN_VALUE + " to " + Short.MAX_VALUE + ")"); System.out.println("int: " + i + " (" + Integer.SIZE + " bits, " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE + ")"); System.out.println("long: " + l + " (" + Long.SIZE + " bits, " + Long.MIN_VALUE + " to " + Long.MAX_VALUE + ")"); System.out.println("float: " + f + " (" + Float.SIZE + " bits)"); System.out.println("double: " + d + " (" + Double.SIZE + " bits)"); System.out.println("char: " + c + " (" + Character.SIZE + " bits, code " + (int) c + ")"); System.out.println("boolean: " + flag); } }

javac -Xlint:all Primitives.java
java Primitives

byte: 100 (8 bits, -128 to 127)
short: 30000 (16 bits, -32768 to 32767)
int: 2000000000 (32 bits, -2147483648 to 2147483647)
long: 9000000000 (64 bits, -9223372036854775808 to 9223372036854775807)
float: 1.5 (32 bits)
double: 2.5 (64 bits)
char: A (16 bits, code 65)
boolean: true

int is the default for a whole number and double for a fractional one. long needs the L suffix when the value does not fit in an int, and float needs the f suffix, because without it a fractional literal is a double and the assignment is a loss of precision. A boolean is not a number: it has no size constant, because the language does not promise one.

Literals

A literal is a value written in the source. Underscores may group the digits of a number and are ignored by the compiler; a prefix selects another base, and an exponent moves the decimal point. Every form below is one int, long, double, char, String or boolean.

public class Literals { public static void main(String[] args) { int decimal = 1_000_000; int hex = 0xFF; int binary = 0b1010; long big = 9_000_000_000L; double fraction = 1.5e3; char letter = 'J'; String text = "Java"; boolean flag = true; System.out.println("decimal: " + decimal); System.out.println("hex: " + hex); System.out.println("binary: " + binary); System.out.println("long: " + big); System.out.println("fraction: " + fraction); System.out.println("letter: " + letter); System.out.println("text: " + text); System.out.println("flag: " + flag); } }

javac -Xlint:all Literals.java
java Literals

decimal: 1000000
hex: 255
binary: 10
long: 9000000000
fraction: 1500.0
letter: J
text: Java
flag: true

The base and the underscores are for the reader: 0xFF and 255 are the same value, and 1_000_000 has no separator left at run time. An integer literal that is too large for int is an error unless it ends in L, which is why the L above is not optional.

var

Since Java 10 a local variable may be declared with var, and the compiler infers the type from the initialiser. It is still a statically typed variable: the inferred type is fixed, and a later assignment of another type is an error exactly as it would be with the type written out.

import java.util.ArrayList; public class Var { public static void main(String[] args) { var count = 3; var name = "Ada"; var names = new ArrayList<String>(); names.add(name); names.add("Grace"); System.out.println("count: " + count); System.out.println("name: " + name); System.out.println("names: " + names); } }

javac -Xlint:all Var.java
java Var

count: 3
name: Ada
names: [Ada, Grace]

var is allowed for a local variable with an initialiser, and nowhere else: not for a field, not for a parameter, not for a variable declared without a value. It saves typing when the type is long and obvious from the right-hand side, and it hides it when the right-hand side does not say, which is the reason many teams keep it for locals only.

final

final makes a variable assignable once. The compiler checks the assignment, so a second one is an error rather than a run-time surprise. A static final field is a constant of the class, and the convention writes its name in capitals.

public class Constants { static final int MAX = 100; public static void main(String[] args) { final double RATE = 0.2; int price = 50; System.out.println("max: " + MAX); System.out.println("with tax: " + (price * (1 + RATE))); } }

javac -Xlint:all Constants.java
java Constants

max: 100
with tax: 60.0

A second assignment is refused at compile time, and the message names the variable and the line:

public class FinalError { public static void main(String[] args) { final int limit = 10; limit = 20; System.out.println(limit); } }

javac -Xlint:all FinalError.java

FinalError.java:4: error: cannot assign a value to final variable limit
limit = 20;
^
1 error

final on a reference forbids a new object, not a change inside the object: a final list still accepts add. That distinction is the subject of the final page and of a later lesson on immutable objects.

Default values of fields

A local variable must be assigned before it is read, and the compiler refuses a read that might come first. A field is different: every field of an object starts with a default value, which is zero for the numeric types, false for a boolean, the NUL character for a char and null for a reference.

public class Defaults { byte b; short s; int i; long l; float f; double d; char c; boolean flag; String text; public static void main(String[] args) { Defaults object = new Defaults(); System.out.println("byte: " + object.b); System.out.println("short: " + object.s); System.out.println("int: " + object.i); System.out.println("long: " + object.l); System.out.println("float: " + object.f); System.out.println("double: " + object.d); System.out.println("char: " + (int) object.c); System.out.println("boolean: " + object.flag); System.out.println("String: " + object.text); } }

javac -Xlint:all Defaults.java
java Defaults

byte: 0
short: 0
int: 0
long: 0
float: 0.0
double: 0.0
char: 0
boolean: false
String: null

The char is printed as a number because the NUL character has no visible form; without the cast, println would write a byte that a terminal does not show. A null field is not an empty string: it is the absence of an object, and calling a method on it throws NullPointerException, which a later lesson on objects and references reads in full.

Scope

A variable lives from its declaration to the end of the block that declares it, and a block is a pair of braces. The variable declared inside an if body is not visible after the closing brace, and the compiler reports every use outside it:

public class Scope { public static void main(String[] args) { if (args.length >= 0) { int inside = 1; } System.out.println(inside); } }

javac -Xlint:all Scope.java

Scope.java:6: error: cannot find symbol
System.out.println(inside);
^
symbol: variable inside
location: class Scope
1 error

The rule is the reason to declare a variable in the smallest block that needs it: a variable that is not in scope cannot be read by accident, and its name is free for another use outside. A variable declared in the outer block is visible in the inner one, which is how a loop counter and an accumulator work together.

Exercises

  1. Declare a byte with the value 127 and add one to it in a byte variable. Which value do you get, and why?
  2. Write the same number as a decimal, a hexadecimal and a binary literal, and print all three.
  3. Replace every var in Var.java with the type the compiler inferred. Which one is the longest, and which is the least obvious?
  4. Move int inside = 1; outside the if in Scope.java and build again. What changes?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which of these is not a primitive type?

    Answer

    String

    String is a class in java.lang; the primitives are the eight keywords byte, short, int, long, float, double, char and boolean.

  2. How many bits does an int have?

    Answer

    32

    Integer.SIZE is 32, and the range is -2147483648 to 2147483647.

  3. What is the value of the literal 1_000_000?

    Answer

    One million

    Underscores group digits and are ignored, so the literal is 1000000.

  4. What does this program print? public class Q1 { public static void main(String[] args) { byte b = 127; b++; System.out.println(b); } }

    Answer

    -128

    A byte wraps around at its maximum, so 127 plus one is the minimum, -128.

  5. What does this program print? public class Q2 { public static void main(String[] args) { var count = 3; var name = "Ada"; System.out.println(name + " " + count); } }

    Answer

    Ada 3

    var infers String and int from the initialisers, and the concatenation joins them in order.

  6. What is the first line of the compiler output for this program? public class Q3 { public static void main(String[] args) { final int limit = 10; limit = 20; System.out.println(limit); } }

    Answer

    error: cannot assign a value to final variable limit

    A final variable is assignable once, and the second assignment is a compile-time error.

  7. What does this program print? public class Q4 { static int count; public static void main(String[] args) { System.out.println(count); } }

    Answer

    0

    An int field starts at zero; null is the default of a reference, not of a primitive.

  8. What does this program print? public class Q5 { public static void main(String[] args) { System.out.println("A" + 1 + 2); } }

    Answer

    A12

    The left + joins the string with 1 first, so the result is a string and 2 is appended to it.

  9. What happens to a local variable that is declared and never assigned?

    Answer

    The compiler refuses to read it

    Only fields get default values; a local must be definitely assigned before it is read.

  10. What does this program print? public class Q6 { public static void main(String[] args) { System.out.println('A' + 1); } }

    Answer

    66

    A char is a number in arithmetic, so A is 65 and the expression is 66.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev