Lesson 2 of 13
Variables & Types
Learn how to declare and use Java's basic types. Java is strictly typed, so it checks that every value matches its declared type and asks for an explicit cast when a conversion could lose data.
public class Variables {
public static void main(String[] args) {
// Primitive types (stored by value)
byte b = 127; // -128 to 127
short s = 32767;
int i = 2_147_483_647; // underscores for readability (Java 7+)
long l = 9_999_999_999L; // L suffix required
float f = 3.14f; // f suffix required
double d = 3.14159265358979;
boolean flag = true;
char c = 'A'; // 16-bit Unicode
// var — type inference (Java 10+)
var name = "Alice"; // String
var count = 42; // int
var pi = 3.14; // double
// String — special class (immutable, reference type)
String first = "Hello";
String second = "World";
String combined = first + ", " + second + "!";
// String methods
System.out.println(combined.length()); // 13
System.out.println(combined.toUpperCase()); // HELLO, WORLD!
System.out.println(combined.contains("World")); // true
System.out.println(combined.replace("World", "Java")); // Hello, Java!
System.out.println(combined.substring(7)); // World!
System.out.println(combined.trim()); // removes whitespace
// String comparison — use .equals(), NOT ==
String a = "hello";
String b2 = "hello";
System.out.println(a.equals(b2)); // true (correct)
// System.out.println(a == b2); // might be true (accident) or false
System.out.println(combined);
}
}public class TypeConversion {
public static void main(String[] args) {
// Widening conversion (automatic)
int i = 42;
double d = i; // int -> double, automatic
// Narrowing conversion (explicit cast required)
double pi = 3.14159;
int truncated = (int) pi; // 3 — decimal part lost!
// String conversions
int num = 42;
String s = Integer.toString(num); // "42"
String s2 = String.valueOf(num); // "42"
String s3 = "" + num; // "42" (concatenation trick)
int back = Integer.parseInt("42"); // 42 (throws NumberFormatException if invalid)
double d2 = Double.parseDouble("3.14");
boolean flag = Boolean.parseBoolean("true"); // true
// Wrapper classes — boxed versions of primitives
Integer boxed = 42; // auto-boxing
int unboxed = boxed; // auto-unboxing
// Useful constants
System.out.println(Integer.MAX_VALUE); // 2147483647
System.out.println(Integer.MIN_VALUE); // -2147483648
System.out.println(Double.MAX_VALUE); // 1.7976931348623157E308
System.out.println(s + " " + back);
}
}Finished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.