Visit Sponsor

Written by 12:27 pm Core Java

Java String Length & Trim Example – Guide with Code

In Java, handling string length and whitespace cleanup are fundamental tasks for text processing, validation, and UI formatting. This updated guide on javatechig.com explains how to determine the length of a string and how to remove leading and trailing whitespace using modern, best-practice approaches with clear examples in Java.

Understanding Strings in Java

In Java, String objects store immutable sequences of characters. Operations like calculating length and trimming whitespace are foundational in parsing, input validation, and data normalization.

Java strings are widely used in:

  • User input processing
  • File handling
  • Text formatting
  • Database and network responses

Getting the Length of a String (length())

Java’s String.length() method returns the number of characters in a string.

Example

String text = "Hello World";
int size = text.length();
System.out.println("Length: " + size); // Output: Length: 11

Notes

  • Counts all characters, including spaces
  • Returns 0 for an empty string ("")
  • Does not count null; calling on a null reference throws NullPointerException

Removing Whitespace Using trim()

The trim() method returns a new string with leading and trailing whitespace removed.

Example

String raw = "   Java Rocks   ";
String trimmed = raw.trim();

System.out.println("Before: '" + raw + "'");
System.out.println("After: '" + trimmed + "'");

Output:

Before: '   Java Rocks   '
After: 'Java Rocks'

What trim() Removes

  • Space ' '
  • Horizontal tab \t
  • Newline \n
  • Carriage return \r

Using isEmpty() with length()

A string is empty when its length is zero.

String s = "";
boolean empty = s.isEmpty(); // true

Match with length:

s.length() == 0 // true

isEmpty() is a clearer intent for readability.

Handling null Safely

Calling length() or trim() on null throws an exception. Always check for null:

if (str != null && !str.isEmpty()) {
    // safe to call length() or trim()
}

Or use Objects.requireNonNullElse():

String safe = Objects.requireNonNullElse(str, "");

Practical Examples

Cleaning User Input

When reading from command line or forms:

String userInput = scanner.nextLine().trim();

This helps remove accidental input spaces.

Normalizing File Paths

String path = "  /usr/local/bin/  ";
path = path.trim();

Trimmed paths avoid incorrect comparisons.

Logging and Reporting

String message = "  Error occurred  ";
logger.info(message.trim());

Ensures consistent log formatting.

Tips and Best Practices

Prefer isEmpty() for Readability

string.isEmpty() expresses intent better than string.length() == 0.

Always Null-Check Before Access

NullPointerException is a common pitfall; guard against null references.

Consider strip() (Java 11+)

Java 11 adds String.strip() which removes Unicode whitespace:

String s = "\u2002Hello\u2002";
s = s.strip(); // removes Unicode spaces

This is more comprehensive than trim() for international applications.

Common Mistakes

Assuming length() Excludes Spaces

length() counts all characters, including whitespace.

Using trim() for Internal Spaces

trim() only removes leading/trailing spaces, not spaces within the string:

String s = "  Hello World  ";
s.trim(); // "Hello World", internal space remains

Use replaceAll("\\s+", " ") for internal normalization.

Summary of Methods

MethodPurpose
length()Returns number of characters
trim()Removes leading/trailing whitespace
isEmpty()Checks for empty string
strip()Unicode whitespace removal (Java 11+)
Visited 12 times, 1 visit(s) today
Close