EMZETT.
Login

Kurz: Java ist statisch typisiert: Jede Variable hat einen festen Typ, der sich nicht ändern lässt.

Teil des Kurses Java

Kapitel 3 von 22 im Kurs Java (Abschnitt „Grundlagen“). Mit Fortschritt, Quiz und Zertifikat auf der Lernseite.

Java ist statisch typisiert: Jede Variable hat einen festen Typ, der sich nicht ändern lässt.

Primitive Typen

TypGrößeWertebereich / ZweckBeispiel
byte8 Bit-128 bis 127byte b = 100;
short16 Bit-32.768 bis 32.767short s = 1000;
int32 Bitca. ±2,1 Mrd. (Standard für ganze Zahlen)int alter = 17;
long64 Bitca. ±9,2 Trillionenlong gross = 10_000_000_000L;
float32 BitKommazahl (ca. 7 Stellen)float f = 3.14f;
double64 BitKommazahl (ca. 15 Stellen, Standard)double d = 3.14;
char16 Bitein Zeichenchar c = 'A';
booleantrue oder falseboolean ok = true;

Dazu kommt String (Text), der kein primitiver Typ, sondern eine Klasse ist.

public class Typen {
    public static void main(String[] args) {
        int alter = 17;
        long einwohner = 83_000_000L;       // Unterstriche machen Zahlen lesbar
        double preis = 19.99;
        char note = 'A';
        boolean volljaehrig = alter >= 18;
        String name = "Mia";
 
        System.out.println(name + " ist " + alter + ", Note " + note + ", volljährig: " + volljaehrig);
        System.out.println(einwohner + " / " + preis);
        System.out.println(Integer.MAX_VALUE + " " + Integer.MIN_VALUE + " " + Long.MAX_VALUE);
        System.out.println(Double.MAX_VALUE);
    }
}

Ausgabe:

Mia ist 17, Note A, volljährig: false
83000000 / 19.99
2147483647 -2147483648 9223372036854775807
1.7976931348623157E308

var: Typinferenz

Seit Java 10 erkennt der Compiler lokale Variablentypen selbst:

import java.util.*;
 
public class Var {
    public static void main(String[] args) {
        var zahl = 42;                 // int
        var text = "Hallo";            // String
        var liste = new ArrayList<String>();   // ArrayList<String>
        liste.add("A");
        System.out.println(zahl + " " + text + " " + liste);
    }
}

Ausgabe:

42 Hallo [A]

var funktioniert nur bei lokalen Variablen mit Anfangswert, der Typ bleibt statisch.

final: Konstanten

public class Konstanten {
    static final double MWST = 0.19;    // Klassenkonstante
 
    public static void main(String[] args) {
        final int max = 10;             // lokale Konstante
        System.out.println(max + " " + MWST);
    }
}

Ausgabe:

10 0.19
public class FinalFehler {
    public static void main(String[] args) {
        final int max = 10;
        max = 20;
    }
}

Fehlermeldung:

FinalFehler.java:4: error: cannot assign a value to final variable max
        max = 20;
        ^

Typumwandlung (Casting)

Von kleinen zu großen Typen geht es automatisch (widening). In die andere Richtung muss man bewusst umwandeln (narrowing), dabei können Daten verloren gehen:

public class Cast {
    public static void main(String[] args) {
        int i = 7;
        double d = i;                 // automatisch: 7.0
        double pi = 3.99;
        int abgeschnitten = (int) pi; // Cast: 3 (Nachkommastellen fallen weg)
        long gross = 3_000_000_000L;
        int kaputt = (int) gross;     // Überlauf!
        System.out.println(d + " " + abgeschnitten + " " + kaputt);
 
        System.out.println(7 / 2);        // 3: Ganzzahldivision
        System.out.println(7 / 2.0);      // 3.5
        System.out.println((double) 7 / 2);
        System.out.println('A' + 1);      // 66: char wird zu int
        System.out.println((char) ('A' + 1));
    }
}

Ausgabe:

7.0 3 -1294967296
3
3.5
3.5
66
B

Text in Zahl und zurück

public class Parsen {
    public static void main(String[] args) {
        int a = Integer.parseInt("42");
        double b = Double.parseDouble("3.5");
        String s = String.valueOf(a) + Integer.toString(7);
        System.out.println(a + b + " " + s);
        try {
            Integer.parseInt("abc");
        } catch (NumberFormatException e) {
            System.out.println("Fehler: " + e.getMessage());
        }
    }
}

Ausgabe:

45.5 427
Fehler: For input string: "abc"

Wrapper-Klassen

Zu jedem primitiven Typ gibt es eine Klasse: Integer, Double, Boolean, Character, Long. Sie werden bei Collections gebraucht (List<Integer>) und wandeln automatisch um (Autoboxing). Sie können null sein, primitive Typen nicht.

public class Wrapper {
    public static void main(String[] args) {
        Integer a = 127, b = 127;
        Integer c = 1000, d = 1000;
        System.out.println((a == b) + " " + (c == d) + " " + c.equals(d));   // Falle bei ==
        System.out.println(Integer.compare(5, 9) + " " + Integer.valueOf(5).hashCode());
    }
}

Ausgabe:

true false true
-1 5

Achtung

Vergleiche Objekte (auch Integer, String) mit .equals(), nicht mit ==. Der Operator == vergleicht dort die Speicheradresse.

Rechnen und Genauigkeit

import java.math.BigDecimal;
 
public class Genau {
    public static void main(String[] args) {
        System.out.println(0.1 + 0.2);
        System.out.println(new BigDecimal("0.1").add(new BigDecimal("0.2")));   // exakt, ideal für Geld
        System.out.println(Integer.MAX_VALUE + 1);       // Überlauf
        System.out.println(Math.addExact(1, 2));
    }
}

Ausgabe:

0.30000000000000004
0.3
-2147483648
3

Für Geldbeträge nimmst du BigDecimal oder rechnest in Cent als long.

Merke

  • Primitive Typen: byte, short, int, long, float, double, char, boolean; String ist eine Klasse
  • int und double sind die Standardtypen
  • var lässt den Compiler den Typ erkennen; final macht eine Variable unveränderlich
  • Casting (int) x schneidet ab; 7 / 2 ist 3
  • Objekte mit .equals() vergleichen; Geld mit BigDecimal

Übungsaufgabe

Berechne aus Nettopreis (double) und MwSt-Satz (Konstante) den Bruttopreis und gib ihn mit zwei Nachkommastellen aus.

Quiz zur Selbstkontrolle

Weiter im Kurs

Zurück: Das erste Programm im Detail

Weiter: Operatoren und Ausdrücke

Alle Kapitel: Java im Überblick