Variables & Data Types
Understand Java's type system including primitive types, wrapper classes, strings, and arrays.
Primitive Types
Java has eight primitive data types that serve as the foundation of its type system: byte, short, int, long, float, double, char, and boolean. Each primitive has a fixed size in memory, ensuring consistent behavior across platforms. The int type is the default for integer literals, while double is the default for floating-point literals. Using the appropriate primitive type helps optimize memory usage, especially when working with large arrays.
public class Primitives {
public static void main(String[] args) {
// Integer types
byte b = 127; // 8-bit, -128 to 127
short s = 32000; // 16-bit
int i = 2_000_000_000; // 32-bit (underscores for readability)
long l = 9_000_000_000L; // 64-bit, note the L suffix
// Floating-point types
float f = 3.14f; // 32-bit, note the f suffix
double d = 3.141592653589; // 64-bit
// Character and boolean
char c = 'A'; // 16-bit Unicode
boolean flag = true;
System.out.println("int max: " + Integer.MAX_VALUE);
System.out.println("double: " + d);
System.out.println("char: " + c + " (code: " + (int) c + ")");
}
}
Wrapper Classes and Autoboxing
Each primitive type has a corresponding wrapper class (Integer, Double, Boolean, etc.) that provides an object representation. Autoboxing automatically converts between primitives and their wrapper classes, making it seamless to use primitives with collections and generics. The wrapper classes also provide useful utility methods for parsing, converting, and comparing values. Be aware that autoboxing can introduce subtle performance costs and null pointer exceptions when unboxing null references.
public class WrapperDemo {
public static void main(String[] args) {
// Autoboxing: primitive -> wrapper
Integer boxedInt = 42;
Double boxedDouble = 3.14;
// Unboxing: wrapper -> primitive
int unboxed = boxedInt;
// Useful wrapper methods
int parsed = Integer.parseInt("123");
String binary = Integer.toBinaryString(42);
System.out.println("42 in binary: " + binary); // 101010
// Comparing wrapper objects
Integer a = 127;
Integer b = 127;
System.out.println(a == b); // true (cached range)
System.out.println(a.equals(b)); // true (always safe)
Integer x = 200;
Integer y = 200;
System.out.println(x == y); // false (outside cache)
System.out.println(x.equals(y)); // true
}
}
Strings
Strings in Java are immutable objects represented by the String class, meaning any modification creates a new String instance. The JVM maintains a string pool that reuses string literals to save memory. The StringBuilder class provides a mutable alternative for efficient string concatenation in loops. Java strings support a rich set of methods for searching, comparing, formatting, and manipulating text data.
public class StringDemo {
public static void main(String[] args) {
// String creation
String greeting = "Hello, World!";
String name = new String("Java");
// Common string methods
System.out.println(greeting.length()); // 13
System.out.println(greeting.substring(0, 5)); // "Hello"
System.out.println(greeting.toLowerCase()); // "hello, world!"
System.out.println(greeting.contains("World")); // true
System.out.println(greeting.indexOf("World")); // 7
System.out.println(greeting.replace("World", "Java")); // "Hello, Java!"
// StringBuilder for efficient concatenation
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
sb.append("item").append(i).append(", ");
}
String result = sb.toString();
System.out.println(result); // "item0, item1, item2, item3, item4, "
// Text blocks (Java 15+)
String json = """
{
"name": "Alice",
"age": 30
}
""";
System.out.println(json);
}
}
Arrays
Arrays in Java are fixed-size, zero-indexed collections that hold elements of a single type. They are objects with a length property and support both primitive and reference types. Once created, the size of an array cannot be changed, which is why collections like ArrayList are preferred for dynamic data. Multi-dimensional arrays are implemented as arrays of arrays, allowing for both rectangular and jagged configurations.
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
// Array declaration and initialization
int[] numbers = {10, 20, 30, 40, 50};
String[] names = new String[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";
// Accessing and iterating
System.out.println("First: " + numbers[0]); // 10
System.out.println("Length: " + numbers.length); // 5
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println();
// Array utility methods
int[] sorted = Arrays.copyOf(numbers, numbers.length);
Arrays.sort(sorted);
System.out.println(Arrays.toString(sorted)); // [10, 20, 30, 40, 50]
int index = Arrays.binarySearch(sorted, 30);
System.out.println("Found 30 at index: " + index); // 2
// 2D array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("Center: " + matrix[1][1]); // 5
}
}