Variables
Declaration and initialization
int x = 0;
Schematic syntax: type name = initialValue;.
Java allows several declarations in one statement:
double a, b, c; // Declared, not initialized.
double x = 1.1, y = 1.2, z; // x and y initialized; z only declared.
Local variables must be assigned before they are read.
Primitive types
Java has eight primitive types: byte, short, int, long, float, double, char, and boolean. String is a reference type whose objects are immutable; variables can generally be reassigned unless final.
Correction to the original notes
Stringis not a ninth primitive type, and declaring a variable does not make the variable immutable.
Use single quotes for a char, such as 'A'. For exact decimal arithmetic, BigDecimal can avoid binary floating-point representation errors when constructed appropriately.
Source: Java types and variables.
Arithmetic
Integer division truncates toward zero:
System.out.println(7 / 2); // 3
System.out.println(-7 / 2); // -3
System.out.println(7 / 2.0); // 3.5
Corrections to the original notes
Integer division is not floor division for negative results. Mixed arithmetic does not always become
double: numeric promotion depends on the operand types. Assigning a fractionaldoubleto anintrequires a cast rather than automatic flooring.
Java uses parentheses and operator precedence: multiplication, division, and remainder precede addition and subtraction. Java has no arithmetic exponent operator: ^ means XOR; use Math.pow for powers.
Source: Java expressions §15.17–15.18.
Increments and decrements
int a = 0;
int b = a++;
System.out.println(a + " " + b); // 1 0
int c = ++a;
System.out.println(a + " " + b + " " + c); // 2 0 2
Postfix a++ yields the old value, then increments a. Prefix ++a increments first and yields the new value. -- follows the same pattern while subtracting one.
Compound assignments
+=, -=, *=, /=, and %= combine an operation with assignment. Java’s compound assignments can perform an implicit narrowing conversion, so their behavior is not identical to Python’s.
Floating-point numbers
An integer can be widened to double or float. The primitive names are lowercase; Double is a separate wrapper class. A float literal generally needs an f suffix, such as 1.2f.
For , a floating-point literal can use the form aEb, such as 1.2E3 for 1200.0.
Booleans
A boolean is true or false; ! reverses its value.
Truth table
The original note ended with this heading but contained no table. See Logic for the recorded operator definitions.
Related: Type casting · Number systems · Strings and characters