1. Introduction to Java Utilities
1.1 What are Utility Classes
Utility classes provide reusable methods for common tasks.
1.2 Importance
- Reduces code complexity
- Saves development time
- Improves performance
2. String Class
2.1 What is String
A String is a sequence of characters.
2.2 Immutability
Strings cannot be changed once created.
2.3 Creating Strings
String s1 = "Hello";
String s2 = new String("World");
2.4 Common Methods
s1.length();
s1.charAt(0);
s1.substring(1);
s1.equals(s2);
2.5 Comparison
==→ compares referenceequals()→ compares value
3. StringBuilder and StringBuffer
3.1 Definition
Used for mutable strings (can be modified).
3.2 Example
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb);
3.3 StringBuilder vs StringBuffer
| Feature | StringBuilder | StringBuffer |
|---|---|---|
| Thread-safe | No | Yes |
| Performance | Faster | Slower |
3.4 Common Methods
- append()
- insert()
- delete()
- reverse()
4. Date and Time API
4.1 Introduction
Java provides java.time package for date and time.
4.2 Example
import java.time.LocalDate;LocalDate today = LocalDate.now();
System.out.println(today);
4.3 LocalDateTime
import java.time.LocalDateTime;LocalDateTime now = LocalDateTime.now();
4.4 Formatting
import java.time.format.DateTimeFormatter;DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-yyyy");
System.out.println(today.format(dtf));
5. Math Class
5.1 Definition
Provides methods for mathematical operations.
5.2 Common Methods
Math.abs(-10);
Math.sqrt(25);
Math.pow(2, 3);
Math.max(10, 20);
5.3 Random Numbers
Math.random();
5.4 Rounding
Math.ceil(4.2);
Math.floor(4.8);
Math.round(4.5);
Conclusion
Java utility classes make programming easier and more efficient. By understanding how to work with strings, dates, and mathematical operations, beginners can write cleaner and more optimized code. These utilities are widely used in real-world applications and are essential for every Java developer.
Leave a Reply