toUpperCase and trim
- Java course
- Beginner
- Lesson 33/116
- 4 min
Learn transformations with toUpperCase() and trim().
toUpperCase and trim
To uppercase a String use toUpperCase(), to lowercase use toLowerCase(). To trim leading and trailing spaces use trim().
String s = " Hello ";
String clean = s.trim(); // "Hello"
String upper = clean.toUpperCase(); // "HELLO"Strings are immutable; these methods return a new String, leaving the original untouched. You must assign the result to a variable.
Practice Use trim and toUpperCase
Write a Main class with a main method. Assign " java " to String s. Assign s.trim() to String clean and clean.toUpperCase() to String upper. Print upper with println.
Sample solution
public class Main {
public static void main(String[] args) {
String s = " java ";
String clean = s.trim();
String upper = clean.toUpperCase();
System.out.println(upper);
}
}Expected output
JAVA
Chaining transformations
You can call multiple transformations in a row; this is called chaining:
String result = s.trim().toUpperCase().substring(0, 3);Here trim runs first, then toUpperCase, last substring. Each step produces a new String.
Chaining keeps code short but can hurt readability if overused. Long chains may be split for clarity.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does String.toUpperCase() return?
- int
- char
- Same String
- New String Correct answer
Explanation: toUpperCase returns a new String, leaving the original untouched.
2 Match the methods
| Term | Meaning |
|---|---|
toUpperCase() |
Uppercase |
toLowerCase() |
Lowercase |
trim() |
Trim spaces |
length() |
Length |
3 Complete the trim call
String clean = s.____();
String clean = s.trim();
Explanation: trim() removes leading and trailing spaces.