String Formatting in Java
The String.format() method allows creating formatted strings using specified format specifiers and arguments.
format(String format, Object... args): Uses the default locale.format(Locale l, String format, Object... args): Applies a specific locale during formatting.
Date and Time Formatting
Date and time representations can be customized using specific conversion characters prefixed with %t.
| Specifier | Description | Example |
|---|---|---|
| %te | Day of month (1-31) | 5 |
| %tb | Abbreviated month name | Jan |
| %tB | Full month name | January |
| %tA | Full weekday name | Sunday |
| %ta | Abbreviated weekday name | Sun |
| %tc | Full date and time | Sun Jan 05 14:30:00 UTC 2020 |
| %tY | 4-digit year | 2020 |
| %tj | Day of year (001-366) | 005 |
| %tm | 2-digit month (01-12) | 01 |
| %td | 2-digit day of month (01-31) | 05 |
| %ty | 2-digit year | 20 |
| Specifier | Description | Example |
|---|---|---|
| %tH | 24-hour clock hour (00-23) | 14 |
| %tI | 12-hour clock hour (01-12) | 02 |
| %tk | 24-hour clock hour (0-23) | 9 |
| %tl | 12-hour clock hour (1-12) | 9 |
| %tM | Minutes (00-59) | 30 |
| %tS | Seconds (00-60) | 45 |
| %tL | Milliseconds (000-999) | 250 |
| %tN | Nanoseconds (000000000-999999999) | 500000000 |
| %tp | AM/PM marker | pm |
| %tz | Time zone RFC 82 offset | +0000 |
| %tZ | Time zone abbreviation | UTC |
| %ts | Seconds since epoch | 1578232245 |
| %tQ | Milliseconds since epoch | 1578232245250 |
| Specifier | Description | Example |
|---|---|---|
| %tF | ISO 8601 date (YYYY-MM-DD) | 2020-01-05 |
| %tD | US date format (MM/DD/YY) | 01/05/20 |
| %tc | Full date and time | Sun Jan 05 14:30:00 UTC 2020 |
| %tr | 12-hour time (HH:MM:SS AM/PM) | 02:30:45 PM |
| %tT | 24-hour time (HH:MM:SS) | 14:30:45 |
| %tR | 24-hour time (HH:MM) | 14:30 |
General Data Type Formatting
These specifiers apply to any argument type.
| Specifier | Description | Example |
|---|---|---|
| %b, %B | Boolean | true |
| %h, %H | Hash code | A05A5198 |
| %s, %S | String | text |
| %c, %C | Character | Z |
| %d | Decimal integer | 42 |
| %o | Octal integer | 52 |
| %x, %X | Hexadecimal integer | 2a |
| %e | Scientific notation | 3.140000e+01 |
| %a | Hexadecimal floating-point | 0x1.fap3 |
| %n | Line separator | |
| %% | Literal percent sign | % |
import java.util.Date;
public class FormatDemo {
public static void main(String[] args) {
Date now = new Date();
String yr = String.format("%tY", now);
String mo = String.format("%tm", now);
String dy = String.format("%td", now);
System.out.printf("Date: %s-%s-%s%n", yr, mo, dy);
String hr = String.format("%tH", now);
String mn = String.format("%tM", now);
String sc = String.format("%tS", now);
System.out.printf("Time: %s:%s:%s%n", hr, mn, sc);
String fullIso = String.format("%tF", now);
String fullTime = String.format("%tT", now);
System.out.println("ISO Date: " + fullIso);
System.out.println("24-Hour Time: " + fullTime);
String boolVal = String.format("%b", 10 > 5);
String decVal = String.format("%d", 255);
String hexVal = String.format("%x", 255);
System.out.println("Comparison result: " + boolVal);
System.out.println("Decimal 255 -> Hex: " + hexVal);
}
}
Regular Expressions
Regular expressions define search patterns for string matching and validation. They rely heavily on metacharacters and quantifiers.
Common Metacharacters
| Regex | Java String | Meaning |
|---|---|---|
| . | . | Any single character |
| \d | \\d | A digit [0-9] |
| \D | \\D | A non-digit |
| \s | \\s | A whitespace character |
| \S | \\S | A non-whitespace character |
| \w | \\w | A word character [a-zA-Z_0-9] |
| \W | \\W | A non-word character |
Character classes use brackets to define sets of valid characters, such as [a-z] for lowercase letters or [^0-9] for non-digits. Quantifiers specify occurrence counts:
| Quantifier | Description | Example |
|---|---|---|
| ? | Zero or one occurrence | X? |
| * | Zero or more occurrences | X* |
| + | One or more occurrences | X+ |
| {n} | Exactly n occurrences | X{2} |
| {n,} | At least n occurrences | X{3,} |
| {n,m} | Between n and m occurrences | X{2,5} |
public class RegexValidator {
public static void main(String[] args) {
String emailPattern = "\\w+@\\w+(\\.\\w{2,3})*\\.\\w{2,3}";
String[] testEmails = {"user@", "invalid", "admin@example.org"};
for (String address : testEmails) {
if (address.matches(emailPattern)) {
System.out.println(address + " is a valid email format.");
} else {
System.out.println(address + " is NOT a valid email format.");
}
}
}
}
StringBuilder for Efficient String Manipulation
String objects in Java are immutable; operations like concatenation create new instances, which degrades performance in loops. The StringBuilder class provides a mutable sequence of characters, starting with a default capacity of 16. It automatically expands when needed.
Core methods include:
append(Object obj): Appends the string representation of the argument.insert(int offset, Object obj): Inserts the argument at the specified position.delete(int start, int end): Removes characters in the specified substring.
public class StringBuilderPerf {
public static void main(String[] args) {
int iterations = 10000;
long startMs = System.currentTimeMillis();
String immutableStr = "";
for (int i = 0; i < iterations; i++) {
immutableStr += i;
}
long endMs = System.currentTimeMillis();
System.out.println("String concatenation took: " + (endMs - startMs) + " ms");
startMs = System.currentTimeMillis();
StringBuilder mutableBuffer = new StringBuilder("");
for (int i = 0; i < iterations; i++) {
mutableBuffer.append(i);
}
endMs = System.currentTimeMillis();
System.out.println("StringBuilder took: " + (endMs - startMs) + " ms");
}
}
Practical String Operations
public class StringExercises {
public static void main(String[] args) {
// Case conversion
String mixedCase = "AbCdEfG";
System.out.println("Upper: " + mixedCase.toUpperCase());
System.out.println("Lower: " + mixedCase.toLowerCase());
// Substring comparison
String phrase1 = "programming";
String phrase2 = "programmatic";
String sub1 = phrase1.substring(0, 7);
String sub2 = phrase2.substring(0, 7);
System.out.println("Substrings equal? " + sub1.equals(sub2));
// Mobile number regex validation
String phoneRegex = "^1[3-9]\\d{9}$";
String mobile = "1381234567";
System.out.println(mobile + " valid? " + mobile.matches(phoneRegex));
// StringBuilder number appending
StringBuilder sequence = new StringBuilder("Numbers:");
for (int k = 1; k <= 10; k++) {
sequence.append(k);
}
System.out.println(sequence.toString());
}
}