Command Palette

Search for a command to run...

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

Searching and slicing

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?

Searching and slicing
Sign in to run this example in your browser.

Expected output

length: 18
charAt(6): s
indexOf(chai): 0
indexOf(chai, 1): 14
lastIndexOf(chai): 14
indexOf(tea): -1
contains(samosa): true
startsWith(chai): true
endsWith(samosa): false
substring(6, 12): [samosa]
substring(14): [chai]
occurrences of chai: 2
key [city], value [Pune]