Command Palette

Search for a command to run...

Back to the lesson: Topic 6.4 — Essential String Methods
Core Java · Example 2 of 4 Java 11+

Trimming, blank checks and case

\u2003 and \u00DF are Unicode escapes (Topic 6.8), used so the source file stays plain ASCII.

The String class has a method for almost every everyday text job: measuring, searching, slicing, trimming, changing case, replacing, splitting, joining and repeating. Knowing their exact rules (end-exclusive indexes, regex arguments, trim vs strip, how split drops empty pieces) prevents most text bugs.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write static String initials(String fullName) that returns the upper-case initials of each word, e.g. "amit kumar singh" gives "AKS". Words are separated by single spaces.

02

Write static String maskEmail(String email) that keeps the first letter of the name and the whole domain, e.g. "ravi@hectal.in" gives "r***@hectal.in". Use indexOf and repeat.

03

Count how many times the letter a appears in "masala chai" without a loop, using replace and length.

Explain it without notes

01

Explain the end-exclusive rule of substring and why it's convenient.

02

What's the difference between trim() and strip(), and between isEmpty() and isBlank()?

03

Why does "1.2.3".split(".") return an empty array, and how do you fix it?

04

Explain the limit argument of split.

05

Why should you pass a Locale to toUpperCase for machine-readable text?

Trimming, blank checks and case Java 11+
Sign in to run this example in your browser.

Expected output

trim:          [hello]
strip:         [hello]
stripLeading:  [hello  ]
stripTrailing: [  hello]
trim length: 4
strip length: 2
"".isEmpty(): true
"   ".isEmpty(): false
"   ".isBlank(): true
MASALA CHAI / masala chai
upper-case of strasse with sharp s: STRASSE
original unchanged: Masala Chai