// Primitive types
int number = 42;
long bigNumber = 123456789L;
double decimal = 3.14;
float floatNum = 3.14f;
boolean flag = true;
char letter = 'A';
byte smallNum = 127;
short shortNum = 32000;
// Reference types
String text = "Hello, World!";
Integer wrappedInt = 42; // Wrapper class
// Constants
final int MAX_SIZE = 100;
// Type inference (Java 10+)
var message = "Hello";
var numbers = List.of(1, 2, 3);
// String operations
String str = "Hello";
str.length(); // Get length
str.charAt(0); // Get character at index
str.substring(0, 3); // Get substring
str.toLowerCase(); // Convert to lowercase
str.toUpperCase(); // Convert to uppercase
str.trim(); // Remove whitespace
str.replace("l", "L"); // Replace characters
str.split(","); // Split into array
str.contains("ell"); // Check if contains
str.startsWith("He"); // Check prefix
str.endsWith("lo"); // Check suffix
str.equals("Hello"); // Compare strings
str.equalsIgnoreCase("HELLO"); // Compare ignoring case
// String formatting
String formatted = String.format("Name: %s, Age: %d", name, age);
String template = "Value: %s".formatted(value); // Java 15+
// Text blocks (Java 15+)
String json = """
{
"name": "John",
"age": 30
}
""";
// Arrays
int[] numbers = {1, 2, 3, 4, 5};
int[] empty = new int[10];
int length = numbers.length;
// ArrayList
List<String> list = new ArrayList<>();
list.add("item");
list.get(0);
list.remove(0);
list.size();
list.isEmpty();
list.contains("item");
// HashMap
Map<String, Integer> map = new HashMap<>();
map.put("key", 1);
map.get("key");
map.getOrDefault("key", 0);
map.containsKey("key");
map.remove("key");
map.keySet();
map.values();
map.entrySet();
// HashSet
Set<String> set = new HashSet<>();
set.add("item");
set.contains("item");
set.remove("item");
// Immutable collections (Java 9+)
List<String> immutableList = List.of("a", "b", "c");
Set<Integer> immutableSet = Set.of(1, 2, 3);
Map<String, Integer> immutableMap = Map.of("a", 1, "b", 2);
// If-else
if (condition) {
// code
} else if (otherCondition) {
// code
} else {
// code
}
// Ternary operator
String result = condition ? "yes" : "no";
// Switch (traditional)
switch (value) {
case 1:
// code
break;
case 2:
// code
break;
default:
// code
}
// Switch expressions (Java 14+)
String result = switch (day) {
case MONDAY, FRIDAY -> "Work";
case SATURDAY, SUNDAY -> "Rest";
default -> "Unknown";
};
// Loops
for (int i = 0; i < 10; i++) { }
for (String item : list) { }
while (condition) { }
do { } while (condition);
// Basic method
public int add(int a, int b) {
return a + b;
}
// Static method
public static void utility() { }
// Varargs
public void printAll(String... messages) {
for (String msg : messages) {
System.out.println(msg);
}
}
// Method overloading
public int add(int a, int b) { return a + b; }
public double add(double a, double b) { return a + b; }
// Class definition
public class Person {
// Fields
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String name) {
this.name = name;
}
// Method
public String greet() {
return "Hello, I'm " + name;
}
@Override
public String toString() {
return "Person{name='%s', age=%d}".formatted(name, age);
}
}
// Inheritance
public class Developer extends Person {
private String language;
public Developer(String name, int age, String language) {
super(name, age);
this.language = language;
}
@Override
public String greet() {
return super.greet() + ", I code in " + language;
}
}
// Interface
public interface Drawable {
void draw();
default void clear() { } // Default method
}
// Abstract class
public abstract class Shape {
public abstract double area();
public void describe() {
System.out.println("This is a shape");
}
}
// Immutable data class
public record Person(String name, int age) {
// Compact constructor for validation
public Person {
if (age < 0) throw new IllegalArgumentException("Age cannot be negative");
}
// Additional methods
public String greet() {
return "Hello, I'm " + name;
}
}
// Usage
Person person = new Person("John", 30);
String name = person.name(); // Accessor method
// Stream operations
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
// Map - transform elements
numbers.stream()
.map(n -> n * 2)
.toList();
// Filter - filter elements
numbers.stream()
.filter(n -> n > 2)
.toList();
// Reduce - combine elements
int sum = numbers.stream()
.reduce(0, Integer::sum);
// Find
Optional<Integer> first = numbers.stream()
.filter(n -> n > 3)
.findFirst();
// Match
boolean anyMatch = numbers.stream().anyMatch(n -> n > 3);
boolean allMatch = numbers.stream().allMatch(n -> n > 0);
// Collect
Map<Boolean, List<Integer>> partitioned = numbers.stream()
.collect(Collectors.partitioningBy(n -> n > 3));
// Chaining
List<String> result = people.stream()
.filter(p -> p.age() > 18)
.sorted(Comparator.comparing(Person::name))
.map(Person::name)
.distinct()
.toList();
// Creating Optional
Optional<String> present = Optional.of("value");
Optional<String> nullable = Optional.ofNullable(maybeNull);
Optional<String> empty = Optional.empty();
// Using Optional
optional.isPresent(); // Check if has value
optional.isEmpty(); // Check if empty (Java 11+)
optional.get(); // Get value (throws if empty)
optional.orElse("default"); // Get or default
optional.orElseGet(() -> compute()); // Get or compute
optional.orElseThrow(); // Get or throw
optional.ifPresent(v -> use(v)); // Execute if present
optional.map(String::toUpperCase); // Transform
optional.filter(s -> s.length() > 3); // Filter
optional.flatMap(this::findById); // Flat map
// Try-catch-finally
try {
riskyOperation();
} catch (IOException e) {
handleIOError(e);
} catch (Exception e) {
handleGenericError(e);
} finally {
cleanup();
}
// Try-with-resources
try (var reader = new BufferedReader(new FileReader("file.txt"))) {
String line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
// Throwing exceptions
public void validate(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
// Custom exception
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// Lambda syntax
Runnable r = () -> System.out.println("Hello");
Consumer<String> c = s -> System.out.println(s);
Function<Integer, String> f = n -> "Number: " + n;
Predicate<Integer> p = n -> n > 0;
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
// Method references
list.forEach(System.out::println); // Instance method
list.stream().map(String::toUpperCase); // Instance method
list.stream().map(Person::getName); // Getter
list.stream().sorted(Comparator.comparing(Person::getName));
// Read file to string (Java 11+)
String content = Files.readString(Path.of("file.txt"));
// Write string to file
Files.writeString(Path.of("file.txt"), content);
// HTTP request (Java 11+)
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com"))
.GET()
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
// Parse JSON with pattern matching (Java 21+)
if (obj instanceof String s) {
System.out.println(s.toUpperCase());
}
// Generate random number
int random = new Random().nextInt(100); // 0-99
int randomInRange = new Random().nextInt(min, max); // Java 17+