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#
| Type | Range | Use for |
|---|---|---|
int | about ±2.1 × 10^9 | everyday whole numbers |
long | about ±9.2 × 10^18 | large values, sums, products |
double | about 15 significant digits | fractional values |
char | one character | letters and symbols |
boolean | true or false | conditions |
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;Stringis a class. intoverflows silently past about 2.1 billion; uselong, and cast before multiplying.varinfers a type;finalforbids changes.- Casting narrows;
Integer.parseIntandString.valueOfconvert text.
Next: operators, and reading input with Scanner.