Object Class Fundamentals
The Object class serves as the superclass for all Java classes, making its methods available to every object in the system. Understanding these methods is crucial for efffective Java development.
The toString() Method
The toString() method returns a string representation of an object. While the default implementation returns the class name followed by a hash code, this method is designed to be overridden by subclasses to provide meaningful representation of object state.
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
When you print a Person object, the toString() method is automatically invoked:
Person p = new Person("Alice", 28);
System.out.println(p); // Output: Person{name='Alice', age=28}
The equals() Method
The default equals() method inherited from Object performs reference comparison (same as the == operator). For value-based comparison, subclasses should override this method to define their own equality criteria.
public class Person {
private String name;
private int age;
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person other = (Person) obj;
return age == other.age &&
(name != null ? name.equals(other.name) : other.name == null);
}
}
The clone() Method
The clone() method creates and returns a copy of an object. To use it, the class must implement the Cloneable interface, otherwise a CloneNotSupportedException is thrown.
public class UserAccount implements Cloneable {
private int userId;
private String login;
private String secretKey;
private double[] balance;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Usage:
UserAccount original = new UserAccount(101, "jsmith", "pass123", new double[]{100.50, 250.75});
UserAccount copy = (UserAccount) original.clone();
The Objects Utility Class
The Objects clas provides utility methods for operations like null-safe equality checks and null validation.
Null-Safe Equality Check
String a = null;
String b = "hello";
// Using Objects.equals - handles null safely
boolean result = Objects.equals(a, b); // false
// Direct equals on null would throw NullPointerException
// a.equals(b) // throws NPE
Null Checks
String test = null;
Objects.isNull(test); // true
Objects.nonNull(test); // false
String existing = "value";
Objects.isNull(existing); // false
Objects.nonNull(existing); // true
The Objects.equals() implementation:
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
Wrapper Classes
Wrapper classes encapsulate primitive types as objects, enabling them to be used in collections and generic contexts.
Autoboxing and Unboxing
Java automatically converts between primitives and their wrapper types:
// Autoboxing: primitive to wrapper
Integer wrapped = 42; // automatically converted
// Unboxing: wrapper to primitive
int primitive = wrapped;
// Working with collections
List<Integer> numbers = new ArrayList<>();
numbers.add(10); // autoboxing
numbers.add(20);
int val = numbers.get(0); // unboxing
Converting Between Types
Wrapper to String
Integer num = 99;
String s1 = Integer.toString(num); // "99"
String s2 = num.toString(); // "99"
String s3 = num + ""; // "99"
String to Primitive/Wrapper
String intStr = "42";
int parsedInt = Integer.parseInt(intStr); // 42
Integer wrappedInt = Integer.valueOf(intStr); // 42
String doubleStr = "3.14";
double parsedDouble = Double.parseDouble(doubleStr); // 3.14
StringBuilder Class
StringBuilder represents a mutable sequence of characters. Unlike String, its contant can be modified in place without creating new objects, making it highly efficient for string manipulation operations.
Basic Operations
StringBuilder builder = new StringBuilder("hello");
// Append various types
builder.append(100);
builder.append(" world");
builder.append(true);
// Chain operations
builder.append("!").append("!").append("!");
// Reverse the string
builder.reverse();
// Get length
int length = builder.length();
// Convert to String
String result = builder.toString();
Performance Comparison
For intensive string operations, StringBuilder significantly outperforms String concatenation:
// Inefficient: creates many intermediate String objects
String inefficient = "";
for (int i = 0; i < 100000; i++) {
inefficient += "data";
}
// Efficient: uses mutable buffer
StringBuilder efficient = new StringBuilder();
for (int i = 0; i < 100000; i++) {
efficient.append("data");
}
Practical Example: Array to Bracket-Notation String
Converting an integer array to a formatted string representation:
public static String formatArray(int[] input) {
if (input == null) return null;
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < input.length; i++) {
if (i > 0) sb.append(", ");
sb.append(input[i]);
}
sb.append("]");
return sb.toString();
}
// Usage
System.out.println(formatArray(new int[]{11, 22, 33}));
// Output: [11, 22, 33]
StringJoiner Class
StringJoiner provides a convenient way to construct sequences of strings with delimiters, similar to Python's join() method. It accepts a delimiter and optionally a prefix and suffix.
Basic Usage
// With delimiter only
StringJoiner sj1 = new StringJoiner(", ");
sj1.add("apple");
sj1.add("banana");
sj1.add("cherry");
System.out.println(sj1.toString());
// Output: apple, banana, cherry
// With delimiter, prefix, and suffix
StringJoiner sj2 = new StringJoiner(", ", "[", "]");
sj2.add("x");
sj2.add("y");
sj2.add("z");
System.out.println(sj2.toString());
// Output: [x, y, z]
Array Formatting with StringJoiner
public static String formatArray(int[] data) {
if (data == null) return null;
StringJoiner joiner = new StringJoiner(", ", "[", "]");
for (int value : data) {
joiner.add(String.valueOf(value));
}
return joiner.toString();
}
// Usage
System.out.println(formatArray(new int[]{11, 22, 33}));
// Output: [11, 22, 33]
API Selection Guidelines
| Operation | Recommended API |
|---|---|
| Simple string storage | String |
| Frequent modifications | StringBuilder |
| Joining with delimiters | StringJoiner |
| Null-safe comparisons | Objects class |
| Value equality | Override equals() |
| Object copying | clone() method |