Search the courses, subjects, tracks, games and features, or jump straight to a page.
Learn it your way
A short class with Sarah and her students. The other ways are under More.
Sign up free to listen. Transcripts are free to read.
Here is our string: two spaces, Java Programming, then two more spaces. How long is it?
Java Programming has 16 characters if I count the space in the middle, so 16?
length() says 20. Every space counts as a character, including the four at the edges.
So trim() brings it back down to 16?
Exactly. trim() removes spaces from the beginning and the end, but never from the middle, so the space between Java and Programming stays.
Does trim() change the original string?
No, strings never change. trim() hands back a new string, and if you want to keep it, you store it with name = name.trim();
Which character is at index 2 of our untrimmed string?
The v in Java? J is 0, a is 1, v is 2.
Careful: the two leading spaces sit at indexes 0 and 1, so charAt(2) is J. Spaces take up index positions too.
And in the trimmed text, Java Programming, J is at 0 and P is at 5?
Right, because the space between the words is at index 4. The last index is always length() minus 1.
What happens if I ask for charAt(16) on the trimmed text?
There is no index 16, so Java throws a StringIndexOutOfBoundsException. Valid indexes run from 0 to length() minus 1.
substring(2, 6) on our string gives Java. Why does it end at 6 when J starts at 2?
Because the end index isn't included? It takes indexes 2, 3, 4 and 5.
Yes: begin included, end excluded, and the result is end minus begin characters long, here 4.
So to get Program out of Java Programming, I need substring(5, 12), not substring(5, 11)?
Exactly. substring(5, 11) stops one letter short and gives Progra. Now, how would you trim and capitalise in one line?
name.trim().toUpperCase(). trim() runs first, and toUpperCase() works on the trimmed result.
Perfect. That's method chaining: each method hands its result to the next one, from left to right.
length() counts every character, including spaces at the edges and in the middle.
trim() removes leading and trailing spaces but never the spaces inside the text.
the first character is at index 0 and the last at length() - 1.
substring(begin, end) stops just before end, so the result has end - begin characters.
String methods return a new string, so store the result if you want to keep it.
a chain such as trim().toUpperCase() runs from left to right, each call working on the previous result.
The complete basic-operations program; the square brackets in its output make the edge spaces visible:
public class StringExample {
public static void main(String[] args) {
String name = " Java Programming ";
System.out.println("Length : " + name.length()); // 20
System.out.println("Trimmed : [" + name.trim() + "]"); // [Java Programming]
System.out.println("Upper case : [" + name.toUpperCase() + "]"); // [ JAVA PROGRAMMING ]
System.out.println("charAt(2) : " + name.charAt(2)); // J
System.out.println("substring(2, 6) : " + name.substring(2, 6)); // Java
System.out.println("Original : [" + name + "]"); // [ Java Programming ]
}
}Exploring the indexes of "Java Programming" with charAt() and substring():
public class IndexExplorer {
public static void main(String[] args) {
String text = "Java Programming";
System.out.println("length() : " + text.length()); // 16
System.out.println("charAt(0) : " + text.charAt(0)); // J
System.out.println("charAt(4) : [" + text.charAt(4) + "]"); // [ ]
System.out.println("charAt(5) : " + text.charAt(5)); // P
System.out.println("last character : " + text.charAt(text.length() - 1)); // g
System.out.println("substring(0, 4) : " + text.substring(0, 4)); // Java
System.out.println("substring(5) : " + text.substring(5)); // Programming
System.out.println("substring(5, 12) : " + text.substring(5, 12)); // Program
System.out.println("substring(5, 11) : " + text.substring(5, 11)); // Progra
}
}Cleaning messy input with a chain, and checking that the original string never changes:
public class CleanAndShout {
public static void main(String[] args) {
String input = " hello world ";
String cleaned = input.trim();
String shout = input.trim().toUpperCase();
System.out.println("input : [" + input + "] length " + input.length()); // length 17
System.out.println("cleaned : [" + cleaned + "] length " + cleaned.length()); // length 11
System.out.println("shout : [" + shout + "]"); // [HELLO WORLD]
input.toUpperCase(); // the new string is thrown away
System.out.println("input is still: [" + input + "]");
input = input.trim(); // storing the result keeps it
System.out.println("after input = input.trim(): [" + input + "]");
}
}Taking apart the sentence "Learning Java is fun!" with the same basic operations:
public class SentenceParts {
public static void main(String[] args) {
String sentence = "Learning Java is fun!";
System.out.println("Sentence : " + sentence);
System.out.println("Characters : " + sentence.length()); // 21
System.out.println("First character : " + sentence.charAt(0)); // L
System.out.println("Last character : " + sentence.charAt(sentence.length() - 1)); // !
System.out.println("The language : " + sentence.substring(9, 13)); // Java
System.out.println("Shouted : " + sentence.toUpperCase());
System.out.println("Whispered : " + sentence.toLowerCase());
}
}Start at zero, stop before the end; trim cleans the edges, the middle won't bend.
A tailor named Substring cuts cloth for his customers. He always starts cutting at the first mark they give him but stops just before the second, so a customer who asks for marks 2 to 6 walks away with exactly 4 pieces. His assistant Trim only snips the loose threads at the two ends and never touches the middle of the cloth.
In substring, the first number is IN and the second is OUT: begin is in, end is out.
B.I.E.E. - Begin Included, End Excluded.
Term
What does length() return for "Java Programming" with two spaces added at each end?
Click to flip
Term
What does trim() remove?
Click to flip
Term
What is the index of the first character in a string?
Click to flip
Term
What does `"Java Programming".substring(5, 12)` return?
Click to flip
Term
Does `name.toUpperCase()` change the variable name?
Click to flip
Term
In `str.trim().toUpperCase()`, which method runs first?
Click to flip
A sequence of characters written in double quotes, such as "Java Programming"; in Java it is an object of the String class.
The position of a character in a string, counted from 0 up to length() - 1.
Returns the number of characters in a string, spaces included.
Returns a copy of the string without whitespace at the beginning and end.
Returns the single character (a char) at the given index.
Returns the characters from index begin up to, but not including, index end.
Unable to change after creation; String methods return new strings instead of changing the original.
Calling one method on the result of another, as in name.trim().toUpperCase().
This lesson works through one complete program that applies the basic String operations, length(), trim(), toUpperCase(), charAt() and substring(), to the text "Java Programming" padded with two spaces at each end, and explains every result it prints.
Knowing the names of String methods is one thing; predicting exactly what they return is another. Using the string "Java Programming" with two spaces added at each end, this lesson measures it with length(), cleans it with trim(), changes its case with toUpperCase() and toLowerCase(), reads single characters with charAt() and cuts out pieces with substring(). Along the way it builds an index map, explains why the end index of substring() is left out, shows how to chain calls such as trim().toUpperCase(), and shows that a String never changes: every method hands back a new string.
The program in this lesson works on one string: String name = " Java Programming ";, with two spaces before the text and two after it. Each basic operation gives this result:
length() returns the number of characters, and spaces are characters too. "Java Programming" alone has 16 (4 + 1 + 11), and the four edge spaces raise the total to 20. The last character of any string sits at index length() - 1, here 19.
trim() returns a copy without spaces (and tabs or line breaks) at the start and the end. It never touches spaces inside the text, so the space between "Java" and "Programming" survives. Trimming is the usual first step for text a person typed, such as a line read with Scanner's nextLine() method, because people often add stray spaces. The examples here use fixed strings so that they run without any input.
toUpperCase() turns every letter into its capital and leaves spaces, digits and symbols alone; toLowerCase() does the opposite. Case conversion is often used before comparing or displaying text.
Indexes start at 0. Here is the index map of the trimmed text "Java Programming":
So charAt(0) is 'J', charAt(4) is a space and charAt(5) is 'P'. In the untrimmed string, every index shifts by 2 because of the leading spaces, which is why name.charAt(2) is 'J'. charAt returns a single char. Asking for an index below 0 or at length() or beyond throws a StringIndexOutOfBoundsException.
substring(begin, end) returns the characters from begin up to, but not including, end, so the result always has end - begin characters. On "Java Programming":
substring(0, 4) is "Java" (indexes 0 to 3).substring(5), with no end, runs to the end of the string: "Programming".substring(5, 12) is "Program" (indexes 5 to 11).substring(5, 11) stops one letter short: "Progra".None of these calls changes name. A String is immutable: every method builds and returns a new string, and the original stays exactly as it was. To keep a result, store it, for example name = name.trim();.
Because each of these methods returns a String, you can call the next method on the result straight away. name.trim().toUpperCase() trims first and then converts the trimmed text, giving "JAVA PROGRAMMING". Chains run from left to right, and the order can change the answer: name.trim().length() is 16 while name.length() is 20, and name.trim().charAt(0) is 'J' while name.charAt(0) is a space.