BeginnerLesson 2 of 16
Variables & Data Types – Java
Primitive types, String, var, conversion and typical number pitfalls.
Java is statically typed: every variable has a fixed type. The eight primitive types are byte, short, int, long, float, double, char and boolean. String is a class, but is used like a basic type.
int alter = 36;
long weltbevoelkerung = 8_100_000_000L; // L suffix for long
double groesse = 1.68;
float f = 1.5f; // f suffix for float
boolean aktiv = true;
char buchstabe = 'A';
String name = "Ada";
final int MAX = 100; // constant: cannot be changedWith var (since Java 10) the compiler infers the type from the value – the variable is still statically typed. var only works for local variables with an initial value.
var stadt = "London"; // String
var zahlen = new java.util.ArrayList<Integer>();
zahlen.add(5);
// stadt = 42; // Error: int does not fit String
System.out.println(7 / 2); // 3 (integer division!)
System.out.println(7 / 2.0); // 3.5
System.out.println(7 % 2); // 1
System.out.println((int) 3.9); // 3 (cast truncates)
System.out.println("Age: " + alter); // Age: 36WarningWith two
int values, / is an integer division. Also, int overflows silently: Integer.MAX_VALUE + 1 gives -2147483648. For monetary amounts use BigDecimal, not double.TipNumbers from text:
Integer.parseInt("42"), Double.parseDouble("2.5"). Number to text: String.valueOf(42) or "" + 42.