Methods, Arrays, Strings, and Object Contracts
Learn method design, varargs, recursion, arrays, String behavior, immutability, equals/hashCode, toString, and object-level contracts.
Methods, Parameters, Return Values, and Varargs
A method should perform one coherent operation and expose a clear contract. Java passes arguments by value. For object arguments, the copied value is the reference itself.
static int add(int a, int b) {
return a + b;
}
static int sum(int... values) {
int total = 0;
for (int value : values) total += value;
return total;
}
Varargs are compiled as an array parameter and must be the final parameter.
Java never passes variables by reference. A reference value can be copied, and both variables can point to the same object.
- Java is strictly pass-by-value.
- Varargs provide convenient variable-length arguments.
- Method contracts should make inputs, outputs, and failure behavior explicit.
Arrays and Multidimensional Data
Arrays are fixed-size objects with zero-based indexing.
int[] values = new int[3];
values[0] = 10;
int[] scores = {90, 80, 95};
int[][] matrix = {
{1, 2},
{3, 4}
};
Java's multidimensional arrays are arrays of arrays, so rows can have different lengths. Arrays are efficient for indexed access, but collections are usually better when size or data-structure semantics vary.
- Arrays have fixed length.
- Array indexing starts at zero.
- A Java
T[][]is an array whose elements are themselves arrays.
String Immutability and StringBuilder
String is immutable. Operations such as concatenation produce a new string rather than changing the existing instance.
String name = "Java";
String upper = name.toUpperCase();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 3; i++) {
builder.append(i).append(',');
}
String result = builder.toString();
Repeated concatenation in a large loop can create unnecessary temporary strings. StringBuilder is generally appropriate for incremental construction in one thread.
Use equals() for string content. == compares reference identity for objects.
- Strings are immutable.
- Use
StringBuilderfor repeated string construction. - String pooling is not a reason to use
==for value comparison.
equals, hashCode, and toString Contracts
equals() defines logical equality when overridden. hashCode() must be consistent with equals: equal objects must have equal hash codes. toString() provides a readable representation for logs and debugging.
public record UserKey(String tenantId, String userId) {}
For mutable classes used as HashMap keys, changing fields involved in equality after insertion can make the entry effectively unreachable.
The equality relation should be reflexive, symmetric, transitive, consistent, and false for comparison with null.
equalsdefines logical equality.- Equal objects must have equal hash codes.
- Do not mutate equality-defining state of a key while it is stored in a hash-based collection.