Lesson 7 of 10

Strings

Goal

Comparing with equals instead of ==, and the StringBuilder class

01

Explanation

A string is an object of the String class, and it comes with plenty of methods: length() to count its characters (with parentheses, unlike an array's length), charAt(i) to get the character at position i, trim() to remove spaces from both ends, toLowerCase() to convert letters to lower case, replace(" ", "") to swap one piece of text for another, and split(" +") to break the string into an array at every run of one or more spaces. A string never changes, so methods like trim and replace return a new string instead of changing the original. That's why name.trim(); on its own does nothing.

The most famous Java trap is that == between two strings asks "are these the same object?", not "do they have the same characters?". It may give you the right answer with strings written in your code, then get it wrong with a string the user typed or one built while the program runs. So always compare content with a.equals(b), or with equalsIgnoreCase when you want to ignore the difference between upper and lower case.

Since a string never changes, joining with += inside a loop builds a brand-new string on every iteration. A StringBuilder, on the other hand, is text you can modify: you add to it with append, reverse it in place with reverse(), and get the final string with toString().

02

Your task

Write samePlayer(a, b) to return true if the two names match, ignoring case and any spaces around the names. Write reverseWords(s) to reverse the order of the words using StringBuilder, with a single space between them no matter how many spaces the original had, and isPalindrome(s) to return true if the text reads the same forward and backward, ignoring case and spaces. Then print the result of reverseWords("Java runs Minecraft") from main.

Checks

6 checks
  1. samePlayer compares characters with equals, not ==
  2. samePlayer ignores case and the spaces around the name
  3. reverseWords reverses the order of the words
  4. reverseWords leaves one space between words however many there were
  5. isPalindrome ignores case and spaces
  6. "Minecraft runs Java" was printed
03

Hints

0/3
Track lessons0 of 10 done

Java is the language behind Android apps and large systems. Everything in it lives inside a class, and you state every variable's type explicitly.

Beginner level, 10 lessons, 2 hours in total.

Main.java
OutputJava 13 (Judge0)

Compiling and running your code on the server.

–/6

Compiling and running your code on the server.

6 checks listed under “Your task”.

Track lessons0 of 10 done

Java is the language behind Android apps and large systems. Everything in it lives inside a class, and you state every variable's type explicitly.

Beginner level, 10 lessons, 2 hours in total.