Basic Data Types

Variables

int count = 42;
double price = 19.99;
boolean active = true;
String name = "Ann";

var count2 = 42;        // same thing, type inferred
final double VAT = 0.19;  // constant

var works for local variables only — not fields, parameters or return types.

Tip

Make everything final that never changes. final var works too.

The eight primitives

Type Size Use Default
byte 8 bit −128…127 0
short 16 bit −32,768…32,767 0
int 32 bit default integer type 0
long 64 bit big integers, suffix L 0L
float 32 bit suffix f 0.0f
double 64 bit default decimal type 0.0
char 16 bit one character, single quotes '�'
boolean true / false false
long population = 8_500_000_000L;   // underscores for readability
char initial = 'A';

Arithmetic

7 / 2       // 3   ← integer division!
7 % 2       // 1
7 / 2.0     // 3.5

int max = Integer.MAX_VALUE;
max + 1                  // overflows silently
Math.addExact(max, 1)    // throws ArithmeticException

0.1 + 0.2   // 0.30000000000000004

For money use BigDecimal, or count cents in a long:

new BigDecimal("0.1").add(new BigDecimal("0.2"))   // 0.3
var n = 0;
n += 5; n -= 2; n *= 4; n++; n--;

Wrappers and autoboxing

Every primitive has an object twin: Integer, Long, Double, Boolean, Character. Collections need those, and conversion is automatic.

List<Integer> nums = new ArrayList<>();
nums.add(42);          // int → Integer
int first = nums.get(0);
Warning

Wrappers can be null. Integer x = null; int y = x; throws a NullPointerException.

Strings

Strings are immutable — every method returns a new one.

var text = "Hello World";

text.length()             // 11
text.toUpperCase()
text.charAt(0)            // 'H'
text.substring(6)         // "World"
text.contains("World")    // true
text.indexOf("World")     // 6
text.replace("World", "Java")
text.split(" ")           // ["Hello", "World"]
"  edge  ".strip()
"   ".isBlank()           // true
"ab".repeat(3)            // "ababab"

Building strings

var s1 = name + " is " + age;
var s2 = "%s is %d".formatted(name, age);
var s3 = String.join(", ", "red", "green", "blue");
Format Meaning
%s any value as text
%d integer, %05d00042
%.2f two decimals
%n newline

Comparing strings

a == b          // reference identity — almost never what you want
a.equals(b)     // content
a.equalsIgnoreCase(b)
The classic beginner bug

Use equals for objects, == only for primitives and enum constants.

Text blocks

var json = """
    {
      "name": "Ann",
      "role": "developer"
    }
    """;

Indentation is stripped relative to the closing """; no escaping of quotes needed.

StringBuilder

var sb = new StringBuilder();
for (var i = 1; i <= 5; i++) sb.append(i).append(" ");
sb.toString().strip();   // "1 2 3 4 5"

Input and output

void main() {
    var name = IO.readln("Your name? ");
    IO.println("Hello, " + name + "!");
}

The classic way still works: System.out.println(...), System.err.println(...).

★ Exercises

  1. Store your name, birth year and height in suitable types and print one sentence.
  2. Compute your age in days (365 per year is fine).
  3. Write three versions of 5 / 2 that yield 2.5.
  4. Split "ann,miller,berlin" and print each part capitalized on its own line.
  5. Build a small HTML page with a text block and print it.
  6. Why is 0.1 + 0.2 == 0.3 false? How would you compare instead?