javabeginner
Varargs and Method Overloading
Use varargs for flexible APIs: method overloading, safe varargs, and patterns for builder methods.
javaPress ⌘/Ctrl + Shift + C to copy
import java.util.*;
import java.util.stream.Collectors;
public class VarargsDemo {
// Basic varargs
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) total += n;
return total;
}
// Varargs with required first param
static String join(String separator, String... parts) {
return String.join(separator, parts);
}
// Type-safe heterogeneous container
@SafeVarargs
static <T> List<T> listOf(T... items) {
return List.of(items);
}
// Printf-style formatting
static void log(String format, Object... args) {
String timestamp = java.time.LocalTime.now().toString();
System.out.printf("[%s] %s%n", timestamp, String.format(format, args));
}
// Builder with varargs
static class Query {
private final String table;
private final List<String> columns;
private final List<String> conditions;
private Query(String table, List<String> columns, List<String> conditions) {
this.table = table;
this.columns = columns;
this.conditions = conditions;
}
static Query from(String table) {
return new Query(table, List.of("*"), List.of());
}
Query select(String... cols) {
return new Query(table, List.of(cols), conditions);
}
Query where(String... conds) {
var all = new ArrayList<>(conditions);
all.addAll(List.of(conds));
return new Query(table, columns, all);
}
String build() {
String sql = "SELECT " + String.join(", ", columns) + " FROM " + table;
if (!conditions.isEmpty()) {
sql += " WHERE " + String.join(" AND ", conditions);
}
return sql;
}
}
// Overloading with varargs
static String format(String value) { return value; }
static String format(String value, int width) {
return String.format("%" + width + "s", value);
}
static String format(String value, int width, char fill) {
String padded = format(value, width);
return padded.replace(' ', fill);
}
public static void main(String[] args) {
System.out.println(sum(1, 2, 3, 4, 5)); // 15
System.out.println(sum()); // 0
System.out.println(join("-", "a", "b", "c")); // a-b-c
log("User %s logged in from %s", "alice", "192.168.1.1");
// Query builder
String sql = Query.from("users")
.select("name", "email", "age")
.where("age > 18", "active = true")
.build();
System.out.println(sql);
// Overloaded
System.out.println(format("hi", 10, '.')); // ........hi
}
}Use Cases
- Flexible API method signatures
- DSL and query builder construction
- Logging and formatting utilities
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
javabeginner
Reverse a String in Java
Multiple ways to reverse a string in Java including StringBuilder, char array, and stream approaches.
Best for: String manipulation in coding interviews
#java#string
javabeginner
Read File Line by Line in Java
Read files using BufferedReader, Files.readAllLines, and Stream API with proper resource management.
Best for: Processing log files line by line
#java#file-io
javabeginner
HashMap Operations and Patterns
Essential HashMap operations: put, get, merge, compute, getOrDefault, and iteration patterns.
Best for: Counting word frequencies in text
#java#collections
javabeginner
Java Streams — Filter, Map, Collect
Process collections with Java Streams: filter, map, flatMap, reduce, and collect to lists or maps.
Best for: Transforming and filtering collections
#java#streams