</>CodexBash
Java
JavaBeginner10 min

Variables and data types

Java's primitive types and their ranges, String, overflow and long, var, final, and converting between types with casts and parsing.

Variables are named boxesstep 1/6
?
age
?
name
?
count
Three variables, not yet given a value. Each is a named box in memory.

Declaring variables#

int age = 21;
double price = 99.5;
char grade = 'A';
boolean passed = true;
String name = "Asha";

Every variable has a type that never changes. Java refuses to compile code that reads a local variable before giving it a value, which rules out a whole class of C bugs.

The primitive types#

TypeRangeUse for
intabout ±2.1 × 10^9everyday whole numbers
longabout ±9.2 × 10^18large values, sums, products
doubleabout 15 significant digitsfractional values
charone characterletters and symbols
booleantrue or falseconditions

There are also byte, short and float, which you will rarely need.

String is not a primitive but a class, which is why it starts with a capital letter. It is used so constantly that Java gives it special syntax, like "text" literals and +.

Overflow#

int tops out at Integer.MAX_VALUE, which is 2147483647. One more wraps around to a large negative number, silently:

int big = Integer.MAX_VALUE;
big = big + 1;           // -2147483648, no error

When values can grow large, use long, and mark big literals with L:

long total = 0;
total += 3_000_000_000L;            // underscores are allowed for readability
long area = (long) width * height;  // cast before multiplying, not after

(long) (width * height) would multiply in int, overflow, and only then convert the wrong answer.

var#

Since Java 10, local variables can let the compiler infer the type:

var count = 0;            // int
var names = new ArrayList<String>();

The type is still fixed; var just saves writing it twice. Use it when the type is obvious from the right-hand side.

final#

final int DAYS_IN_WEEK = 7;
DAYS_IN_WEEK = 8;        // compile error

Characters are numbers#

A char holds a character code, so arithmetic works:

char c = '7';
int digit = c - '0';          // 7
int index = 'd' - 'a';        // 3
char upper = Character.toUpperCase('q');   // 'Q'

Character also has isDigit, isLetter, isLetterOrDigit and isWhitespace.

Converting#

Widening, such as int to long or double, happens automatically. Narrowing needs a cast and may lose information:

int a = 7, b = 2;
double wrong = a / b;            // 3.0: int division happened first
double right = (double) a / b;   // 3.5
int truncated = (int) 3.9;       // 3

Text to numbers and back:

int n = Integer.parseInt("42");
long big = Long.parseLong("9000000000");
double d = Double.parseDouble("3.5");
String s = String.valueOf(42);   // or "" + 42

Integer.parseInt("hello") throws a NumberFormatException.

Key points#

  • Primitives (int, long, double, char, boolean) hold values; String is a class.
  • int overflows silently past about 2.1 billion; use long, and cast before multiplying.
  • var infers a type; final forbids changes.
  • Casting narrows; Integer.parseInt and String.valueOf convert text.

Next: operators, and reading input with Scanner.

Practise it

The same idea, in the order it is worth meeting it.

  1. Not startedHow many digitsEasy
  2. Not startedTurn the digits aroundEasy
Create a free account to track your progress