Java Kurs

Java Variables and Data Types

Python 3 Tutorial für Anfänger.

Declaring Variables

In Java, every variable must have a declared type. The syntax is: type variableName = value;

int age = 25;
double price = 9.99;
boolean isActive = true;
String name = "Alice";

Primitive Types

TypeSizeRange / Example
byte1 byte-128 to 127
short2 bytes-32,768 to 32,767
int4 bytes-2^31 to 2^31-1
long8 bytes-2^63 to 2^63-1
float4 bytes3.14f
double8 bytes3.14159
char2 bytes'A'
boolean1 bittrue / false

Constants with final

final double PI = 3.14159265;
final int MAX_SIZE = 100;
// PI = 3; // ❌ compilation error

Type Casting

// Widening (implicit)
int i = 42;
double d = i;   // 42.0 — OK automatically

// Narrowing (explicit)
double x = 9.99;
int n = (int) x;  // 9 — decimal part is lost

String Basics

String greeting = "Hello, " + "World!";
int length = greeting.length();       // 13
String upper = greeting.toUpperCase(); // "HELLO, WORLD!"
boolean starts = greeting.startsWith("Hello"); // true

var (Java 10+)

var count = 10;       // inferred as int
var message = "Hi";   // inferred as String
// var x;             // ❌ must be initialized