Java Core APIs
Java provides a rich set of core classes for the most common operations. In this article we'll explore the most used ones: String, StringBuilder, Wrapper classes and the modern Date/Time API.
What You Will Learn
- String: immutability and main methods
- StringBuilder for efficient concatenation
- Wrapper classes and autoboxing
- LocalDate, LocalTime, LocalDateTime
- Date formatting and parsing
- ZonedDateTime for time zones
The String Class
String is one of the most used classes in Java. Strings are
immutable: once created, they cannot be modified.
// Ways to create Strings
String name = "John Smith"; // literal (recommended)
String lastName = new String("Green"); // constructor (not recommended)
// Empty String vs null
String empty = ""; // empty string, length 0
String nullRef = null; // null reference, no object
// Immutability: methods return NEW strings
String original = "Java";
String uppercase = original.toUpperCase();
System.out.println(original); // "Java" - not modified!
System.out.println(uppercase); // "JAVA" - new string
Main Methods
String course = "Java Programming";
// Length
int length = course.length(); // 16
// Character access
char first = course.charAt(0); // 'J'
char last = course.charAt(course.length() - 1); // 'g'
// Searching
int position = course.indexOf("Java"); // 0
int lastPos = course.lastIndexOf("a"); // 14
boolean contains = course.contains("Prog"); // true
boolean starts = course.startsWith("Java"); // true
boolean ends = course.endsWith("ming"); // true
// Comparison
String other = "java programming";
boolean equal = course.equals(other); // false
boolean equalIgnoreCase = course.equalsIgnoreCase(other); // true
int comparison = course.compareTo(other); // negative (J < j)
// Extraction
String sub1 = course.substring(0, 4); // "Java"
String sub2 = course.substring(5); // "Programming"
// Transformation
String upper = course.toUpperCase(); // "JAVA PROGRAMMING"
String lower = course.toLowerCase(); // "java programming"
String trimmed = " spaces ".trim(); // "spaces"
String replaced = course.replace("Java", "Python"); // "Python Programming"
Split and Join
// Split: divides string into array
String csv = "John,Smith,25,Boston";
String[] parts = csv.split(",");
// parts = ["John", "Smith", "25", "Boston"]
for (String part : parts) {
System.out.println(part);
}
// Join: combines array into string
String[] languages = {"Java", "Python", "SQL"};
String list = String.join(", ", languages); // "Java, Python, SQL"
// Split with limit
String phrase = "one-two-three-four";
String[] firstTwo = phrase.split("-", 2); // ["one", "two-three-four"]
StringBuilder
StringBuilder is a mutable class for building
strings efficiently, especially in loops.
// INEFFICIENT with String (creates many intermediate strings)
String result = "";
for (int i = 0; i < 1000; i++) {
result += i + ", "; // Creates a new String each iteration!
}
// EFFICIENT with StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i).append(", ");
}
String efficientResult = sb.toString();
StringBuilder sb = new StringBuilder("Hello");
// Append: adds at end
sb.append(" ");
sb.append("World");
sb.append(123); // "Hello World123"
// Insert: inserts at position
sb.insert(5, ","); // "Hello, World123"
// Delete: removes characters
sb.delete(11, 14); // "Hello, World"
// Replace: replaces
sb.replace(0, 5, "Hi"); // "Hi, World"
// Reverse: reverses
sb.reverse(); // "dlroW ,iH"
// Final conversion
String final = sb.toString();
Wrapper Classes
Wrappers are classes that "wrap" primitive types, allowing them to be used as objects (e.g., in collections).
Primitives and Wrappers
| Primitive | Wrapper | Typical Use |
|---|---|---|
| int | Integer | Collections, null handling |
| double | Double | Nullable decimals |
| boolean | Boolean | Tri-state (true/false/null) |
| char | Character | Characters in collections |
// Autoboxing: primitive -> wrapper (automatic)
Integer gradeWrapper = 85; // equivalent to: Integer.valueOf(85)
Double average = 82.5;
// Unboxing: wrapper -> primitive (automatic)
int gradePrimitive = gradeWrapper; // equivalent to: gradeWrapper.intValue()
double avgDouble = average;
// Parsing: String -> number
int number = Integer.parseInt("42");
double decimal = Double.parseDouble("3.14");
boolean flag = Boolean.parseBoolean("true");
// Number -> String conversion
String string1 = Integer.toString(42);
String string2 = String.valueOf(42);
// Useful methods
int max = Integer.MAX_VALUE; // 2147483647
int min = Integer.MIN_VALUE; // -2147483648
int comparison = Integer.compare(10, 20); // negative
// BEWARE of null!
Integer nullable = null;
// int value = nullable; // NullPointerException!
Date and Time API (java.time)
Starting from Java 8, the new java.time API replaces the
problematic Date and Calendar classes.
LocalDate - Date Only
import java.time.LocalDate;
import java.time.Month;
// Creation
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(2000, 3, 15);
LocalDate withMonth = LocalDate.of(2000, Month.MARCH, 15);
LocalDate parsed = LocalDate.parse("2024-03-15");
// Getters
int year = today.getYear(); // 2025
int month = today.getMonthValue(); // 2
Month monthEnum = today.getMonth(); // FEBRUARY
int day = today.getDayOfMonth(); // 1
int dayOfYear = today.getDayOfYear(); // 32
// Manipulation (returns new instance)
LocalDate tomorrow = today.plusDays(1);
LocalDate nextMonth = today.plusMonths(1);
LocalDate lastYear = today.minusYears(1);
// Comparison
boolean before = birthday.isBefore(today);
boolean after = birthday.isAfter(today);
boolean equal = birthday.isEqual(today);
// Calculating difference
long days = today.until(birthday).getDays();
LocalTime - Time Only
import java.time.LocalTime;
// Creation
LocalTime now = LocalTime.now();
LocalTime lecture = LocalTime.of(9, 30); // 09:30
LocalTime precise = LocalTime.of(9, 30, 45); // 09:30:45
LocalTime parsed = LocalTime.parse("14:30:00");
// Getters
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
// Manipulation
LocalTime inOneHour = now.plusHours(1);
LocalTime halfHourAgo = now.minusMinutes(30);
// Useful constants
LocalTime midnight = LocalTime.MIDNIGHT; // 00:00
LocalTime noon = LocalTime.NOON; // 12:00
LocalDateTime - Date and Time
import java.time.LocalDateTime;
// Creation
LocalDateTime exactNow = LocalDateTime.now();
LocalDateTime exam = LocalDateTime.of(2025, 2, 15, 9, 0);
LocalDateTime combined = LocalDateTime.of(
LocalDate.of(2025, 2, 15),
LocalTime.of(9, 0)
);
// Extracting components
LocalDate date = exactNow.toLocalDate();
LocalTime time = exactNow.toLocalTime();
// Manipulation
LocalDateTime next = exactNow.plusDays(7).plusHours(2);
// Formatting
System.out.println(exactNow); // 2025-02-01T11:30:00.123
Formatting and Parsing
import java.time.format.DateTimeFormatter;
import java.util.Locale;
LocalDateTime dt = LocalDateTime.now();
// Predefined patterns
DateTimeFormatter isoDate = DateTimeFormatter.ISO_LOCAL_DATE;
System.out.println(dt.format(isoDate)); // 2025-02-01
// Custom patterns
DateTimeFormatter european = DateTimeFormatter.ofPattern("dd/MM/yyyy");
DateTimeFormatter full = DateTimeFormatter.ofPattern("EEEE, MMMM d, yyyy, HH:mm", Locale.US);
DateTimeFormatter american = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm a", Locale.US);
System.out.println(dt.format(european)); // 01/02/2025
System.out.println(dt.format(full)); // Saturday, February 1, 2025, 11:30
System.out.println(dt.format(american)); // 02-01-2025 11:30 AM
// Parsing with format
String dateString = "15/03/2025";
LocalDate dateParsed = LocalDate.parse(dateString, european);
ZonedDateTime - Time Zones
import java.time.ZonedDateTime;
import java.time.ZoneId;
// Current time in local zone
ZonedDateTime localNow = ZonedDateTime.now();
// Time in specific zones
ZonedDateTime london = ZonedDateTime.now(ZoneId.of("Europe/London"));
ZonedDateTime newYork = ZonedDateTime.now(ZoneId.of("America/New_York"));
ZonedDateTime tokyo = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
System.out.println("London: " + london);
System.out.println("New York: " + newYork);
System.out.println("Tokyo: " + tokyo);
// Converting between zones
ZonedDateTime londonNow = ZonedDateTime.now(ZoneId.of("Europe/London"));
ZonedDateTime sameInstantNY = londonNow.withZoneSameInstant(ZoneId.of("America/New_York"));
// List available zones
Set<String> zones = ZoneId.getAvailableZoneIds();
Complete Example: Exam Calendar Management
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class ExamCalendar {
private static final DateTimeFormatter DATE_FORMAT =
DateTimeFormatter.ofPattern("EEEE, MMMM d, yyyy", Locale.US);
private static final DateTimeFormatter TIME_FORMAT =
DateTimeFormatter.ofPattern("HH:mm");
public static void main(String[] args) {
// Exam data
String course = "Java Programming";
LocalDate examDate = LocalDate.of(2025, Month.FEBRUARY, 15);
LocalTime startTime = LocalTime.of(9, 0);
LocalTime endTime = LocalTime.of(12, 0);
// Calculate days remaining
LocalDate today = LocalDate.now();
Period difference = Period.between(today, examDate);
long daysRemaining = today.until(examDate).getDays();
// Print information
StringBuilder sb = new StringBuilder();
sb.append("╔════════════════════════════════════════╗\n");
sb.append("║ UPCOMING EXAM ║\n");
sb.append("╠════════════════════════════════════════╣\n");
sb.append(String.format("║ Course: %-30s ║%n", course));
sb.append(String.format("║ Date: %-30s ║%n",
examDate.format(DATE_FORMAT)));
sb.append(String.format("║ Time: %s - %s ║%n",
startTime.format(TIME_FORMAT),
endTime.format(TIME_FORMAT)));
sb.append("╠════════════════════════════════════════╣\n");
if (daysRemaining > 0) {
sb.append(String.format("║ %d days remaining ║%n", daysRemaining));
} else if (daysRemaining == 0) {
sb.append("║ THE EXAM IS TODAY! ║\n");
} else {
sb.append("║ Exam already taken ║\n");
}
sb.append("╚════════════════════════════════════════╝");
System.out.println(sb.toString());
}
}
Conclusion
In this article we explored Java core APIs: String and StringBuilder for text manipulation, Wrappers for primitive types, and the modern Date/Time API for handling dates and times.
In the next article we'll cover the Collections Framework: List, Set, Map and their various implementations.
Related deep dive: 04 - OOP: Concetti Fondamentali.
Related deep dive: 05 - Astrazione e Contratti: Interfacce e Classi Astratte.
Key Points to Remember
- String: Immutable, use StringBuilder for multiple concatenations
- StringBuilder: Mutable, efficient for building strings
- Wrappers: Autoboxing automatically converts primitive/object
- LocalDate/Time: Immutable, thread-safe, modern API
- DateTimeFormatter: For formatting and parsing dates
- ZonedDateTime: For handling time zones
Frequently asked questions
What is the main difference between String and StringBuilder classes in Java?
The String class is immutable, meaning it cannot be modified once created, whereas the StringBuilder class is mutable, allowing for efficient building of strings.
Why are Wrapper classes used in Java?
Wrapper classes allow primitive types to be used as objects, enabling their use in collections and other object-oriented programming scenarios.
What replaced the old Date/Time API in Java 8?
The new modern Date/Time API (java.time) replaced the problematic and classes that were previously used for handling dates and times.
What is covered in the next article related to this one?
The Collections Framework, including List, Set, Map, and their various implementations.
Commenti
Caricamento commenti...
Sign in to comment