Java String Formatting, Regular Expressions, and StringBuilder

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.

SpecifierDescriptionExample
%teDay of month (1-31)5
%tbAbbreviated month nameJan
%tBFull month nameJanuary
%tAFull weekday nameSunday
%taAbbreviated weekday nameSun
%tcFull date and timeSun Jan 05 14:30:00 UTC 2020
%tY4-digit year2020
%tjDay of year (001-366)005
%tm2-digit month (01-12)01
%td2-digit day of month (01-31)05
%ty2-digit year20
SpecifierDescriptionExample
%tH24-hour clock hour (00-23)14
%tI12-hour clock hour (01-12)02
%tk24-hour clock hour (0-23)9
%tl12-hour clock hour (1-12)9
%tMMinutes (00-59)30
%tSSeconds (00-60)45
%tLMilliseconds (000-999)250
%tNNanoseconds (000000000-999999999)500000000
%tpAM/PM markerpm
%tzTime zone RFC 82 offset+0000
%tZTime zone abbreviationUTC
%tsSeconds since epoch1578232245
%tQMilliseconds since epoch1578232245250
SpecifierDescriptionExample
%tFISO 8601 date (YYYY-MM-DD)2020-01-05
%tDUS date format (MM/DD/YY)01/05/20
%tcFull date and timeSun Jan 05 14:30:00 UTC 2020
%tr12-hour time (HH:MM:SS AM/PM)02:30:45 PM
%tT24-hour time (HH:MM:SS)14:30:45
%tR24-hour time (HH:MM)14:30

General Data Type Formatting

These specifiers apply to any argument type.

SpecifierDescriptionExample
%b, %BBooleantrue
%h, %HHash codeA05A5198
%s, %SStringtext
%c, %CCharacterZ
%dDecimal integer42
%oOctal integer52
%x, %XHexadecimal integer2a
%eScientific notation3.140000e+01
%aHexadecimal floating-point0x1.fap3
%nLine 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

RegexJava StringMeaning
..Any single character
\d\\dA digit [0-9]
\D\\DA non-digit
\s\\sA whitespace character
\S\\SA non-whitespace character
\w\\wA word character [a-zA-Z_0-9]
\W\\WA 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:

QuantifierDescriptionExample
?Zero or one occurrenceX?
*Zero or more occurrencesX*
+One or more occurrencesX+
{n}Exactly n occurrencesX{2}
{n,}At least n occurrencesX{3,}
{n,m}Between n and m occurrencesX{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());
    }
}

Tags: java String Formatting regular expressions StringBuilder

Posted on Sun, 10 May 2026 03:36:43 +0000 by respiant