Skip to lesson

Change case, trim and replace (Strings never change)

Methods like toUpperCase(), trim() and replace() give you a changed copy of a String. The original never changes, so you must store the result.

Strings never change

You call name.toUpperCase(); and name still prints in small letters. A String is immutable: once made, its characters never change, so a method makes a new String instead.

Left: name.toUpperCase(); on its own makes a new String "PRIYA" that is not stored, so name still holds "priya". Right: name = name.toUpperCase(); stores the new String, so name now holds "PRIYA" and the old "priya" is no longer used.

Example 1 · The original does not change

Immutable.javaJava
public class Immutable {    public static void main(String[] args) {        String name = "priya";        name.toUpperCase();   // result not stored        System.out.println(name);        name = name.toUpperCase();        System.out.println(name);    }}
Output
priya
PRIYA

What this code does

  • Line 4 makes PRIYA but nothing keeps it, so name still holds priya.
  • Line 6 stores the new String in name, so the second print shows PRIYA.
If a String method "did nothing", check that you stored its result.

Change case before you compare

Marksheet.PDF fails the check endsWith(".pdf"), because searches are case-sensitive (opens in a new tab). Make the case the same first: toLowerCase() or toUpperCase(), then check.

Example 2 · Capitals should not matter

FileType.javaJava
public class FileType {    public static void main(String[] args) {        String file = "Marksheet.PDF";        String lower = file.toLowerCase();        System.out.println(lower);        System.out.println(lower.endsWith(".pdf"));        System.out.println(file);    }}
Output
marksheet.pdf
true
Marksheet.PDF

What this code does

  • After toLowerCase(), the check works for .pdf, .PDF or .Pdf.
  • file itself is still Marksheet.PDF: toLowerCase() made a new String called lower.
  • Digits, spaces and symbols such as . do not change with the case.

Calling one method on the result of another, file.toLowerCase().endsWith(".pdf"), is called chaining. Java runs it from left to right.

Experiment

Case lab

Type Delhi in any mix of capitals. Which check still says true?

String city = "DeLhI";
System.out.println(city.toLowerCase());
System.out.println(city.equals("delhi"));
System.out.println(city.toLowerCase().equals("delhi"));
city.toLowerCase()
delhi
city.equals("delhi")
false
city.toLowerCase().equals("delhi")
true

Remove outer spaces: trim()

Users often type " Rohit Kumar " with extra spaces. trim() removes the spaces at the start and the end, never the ones between words.

Example 3 · Clean up typed text

CleanInput.javaJava
public class CleanInput {    public static void main(String[] args) {        String raw = "   Rohit Kumar  ";        String clean = raw.trim();        System.out.println("[" + raw + "]");        System.out.println("[" + clean + "]");        System.out.println(raw.length() + " -> " + clean.length());        System.out.println("[" + raw.stripLeading() + "]");        System.out.println("[" + raw.stripTrailing() + "]");        System.out.println("   ".isEmpty() + " " + "   ".isBlank());    }}
Output
[   Rohit Kumar  ]
[Rohit Kumar]
16 -> 11
[Rohit Kumar  ]
[   Rohit Kumar]
false true

What this code does

  • The square brackets show where the spaces are. trim() keeps the space between the two words.
  • stripLeading() removes only the spaces at the start, and stripTrailing() only those at the end.
  • " " has 3 spaces, so it is not empty, but isBlank() is true: it is empty or only spaces.

strip() does the same job as trim() and also knows some rare space characters from other keyboards. stripLeading() cleans only the start and stripTrailing() only the end. Any of them is fine for typed input.

Replace, repeat and concat

A date arrives as 15-08-2024 but the report needs 15/08/2024. replace(old, new) changes every match, and repeat(n) gives the same text n times.

Example 4 · Replace, repeat and concat

ReplaceDemo.javaJava
public class ReplaceDemo {    public static void main(String[] args) {        String date = "15-08-2024";        System.out.println(date.replace('-', '/'));        String msg = "Good morning Sir. Thank you Sir.";        System.out.println(msg.replace("Sir", "Ma'am"));        String phone = "9876543210";        System.out.println("*".repeat(6) + phone.substring(6));        String first = "Rohit";        System.out.println(first.concat(" Kumar"));    }}
Output
15/08/2024
Good morning Ma'am. Thank you Ma'am.
******3210
Rohit Kumar

What this code does

  • replace() works with two char values ('-', '/') or two Strings, and changes every match, not only the first.
  • "*".repeat(6) makes six stars to hide the first six digits; substring(6) keeps the rest.
  • concat(" Kumar") adds text to the end and gives a new String, just like first + " Kumar". Most Java code simply uses +.

concat(s) joins s to the end of a String, like +. Like every method in this lesson, it gives a new String and leaves the original as it was.

Next step

Check your understanding

10 quick questions