📦 Lesson 3: Java Variables & Data Types
⏱️ Estimated time: 25 minutes | Difficulty: Beginner
Strong Typing
Java is a strongly-typed language, meaning every variable must be declared with a specific data type before it can be used.
Primitive Data Types
// Integer types
byte small = 127; // -128 to 127
short medium = 32000; // -32,768 to 32,767
int normal = 2000000000; // Most common
long big = 9000000000L; // Note the L suffix!
// Decimal types
float pi = 3.14f; // Note the f suffix!
double precise = 3.14159265358979; // More precise (default)
// Other types
boolean alive = true; // true or false only
char letter = 'A'; // Single character (use single quotes!)
Strings (Reference Type)
String name = "Alice"; // Use double quotes!
String greeting = "Hello, " + name + "!"; // Concatenation
// String methods
name.length(); // 5
name.toUpperCase(); // "ALICE"
name.charAt(0); // 'A'
name.equals("Alice"); // true (use this, NOT ==!)
name.contains("li"); // true
Constants & var
final int MAX = 100; // Constant — can't change
// MAX = 200; // Error!
// Type inference (Java 10+)
var age = 25; // Compiler infers int
var name = "Bob"; // Compiler infers String
Type Casting
// Widening (automatic): smaller → larger
int x = 10;
double y = x; // 10.0 (auto)
// Narrowing (manual): larger → smaller
double a = 9.8;
int b = (int) a; // 9 (decimal truncated!)
// String to number
int num = Integer.parseInt("42");
double dbl = Double.parseDouble("3.14");
// Number to String
String s = String.valueOf(42);
String s2 = Integer.toString(42);
✅ Quick Quiz
❓ Which is the default decimal type in Java?
❓ How should you compare Strings in Java?
❓ What does 'final' keyword do?