The String Class

So far, our experience with Strings has been limited to declaring String Variables, Concatenating Strings, and using Escaped Characters.

String equality

One of the key things we've done with primitive data types is to check if they are equal, for example we could write the following code:

int a = 4;
int b = 4;
boolean equalInts = (a == b);
In this case equalInts will be true. The brackets in the above example are not required, but they aid readability.

If we were to try and write similar code to compare Strings however, the IDE will give us a warning, consider this code

String stringX = "Hello";
String stringY = "Hello";
boolean equalStrings = (stringX ==String values are compared using '==' not 'equals()' stringY);
//hover mouse over == to see error
Because String is a class we should not compare instances of String (such as stringX in the above example) in the same way we do with primitive values. Instead we should call a method called equals() on the String, and provide the String we want to compare with.

Calling a method to check String equality

You may be aware that you already called some methods in earlier tutorials, for example System.out.println()to print out values, and other methods to read in values using the Scanner. In the same way System.out.println() requires a value to display, (e.g. System.out.println("hello")) String's equals() method needs another String to compare against. The process of providing a value to a method is known as passing a parameter. We pass the value we want to compare into the method

The code below shows the correct way of checking if two Strings are equal:

String stringX = "Hello";
String stringY = "Hello";
boolean equalStrings = stringX.equals(stringY);
String's equals() method however, does not print anything, instead it returns a boolean value depending on whether or not the Strings are equal, we know that the method returns a boolean, because the code completion in IntelliJ IDEA informs us of this - to the far right of the suggestions Code completion showing return type for String\'s equals methodMethods can return different types of value, for example the nextLine method of Scanner returns a String, some will return nothing (such as System.out.println). The code completion for a method that does not return anything will say void.

Replacing characters / methods with multiple parameters

Another method provided by the String class allows us to change all occurances of a specific character for another character. This however requires us to tell the method both the old character and the new character, but so far we have only passed one parameter into a method. Fortunately, passing multiple parameters is fairly straight forward, we simply place a comma between them as follows:

String coldplaySong = "The hardest part";
String amendedSongTitle = coldplaySong.replace('p','f');
System.out.println(amendedSongTitle);
We can rely on the code completion to inform us of the order to include the parameters, as shown here: Code completion showing parameter order when calling String\'s replace method

One key thing to also be aware of, is that the method returns a new String - it doesn't change the original String. If we wanted to change the original String, we must reassign it's value as follows:

String coldplaySong = "The hardest part";
coldplaySong = coldplaySong.replace('p','f');

String Methods

The String class also provides a number of other methods, some of the key ones include:

length()
returns an int representing the length of the sequence of characters in the String. E.g.:
String phrase = "Hello World";
int phraseLength = phrase.length(); //phraseLength will be 11
charAt()
given an index (in the form of an int), returns the character at that position in the String. E.g.:
String phrase = "Hello World";
char seventhLetter = phrase.charAt(6); //seventhLetter is W
Note that in programming the first item in a list has an index of 0, the second an index of 1 etc.
trim()
Returns a String having removed any whitespace from the start and end of the String passed in, e.g.:
String phrase = "   The cat sat on the mat   ";
String trimmedPhrase = phrase.trim(); //The cat sat on the mat
indexOf()
Returns an int with the first position of a specified character in a String. If the character does not exist, -1 is returned, e.g.:
String progLangauage = "Java";
int indexOfA = progLangauage.indexOf('a'); //1
int indexOfV = progLangauage.indexOf('v'); //2
int indexOfZ = progLangauage.indexOf('z'); //-1
substring()
Returns a section of the String as a new String. This can be used two ways, one where we provide that index of the start position for the substring (and we get all the remaining letters to the end of the String) as follows
String word = "encodes";
String partOfWord = word.substring(2); //codes
Another way of using it is to pass parameters for both the start and end index. The String returned will include the character at the start index, and go up to the character preceding the end index, e.g.:
String word = "encodes";
String partOfWord = word.substring(2,6); //code

Other methods include equalsIgnoreCase(),startsWith(), endsWith(), toLowerCase(), toUpperCase() and contains()

Task

Write command line programmes to do the following:

  1. Get a String from the user, remove spaces from the start and end and output how many characters the remaining phrase has
  2. Get a String from the user, if it has more than 10 characters print the just the last 5, otherwise, print all of them.
  3. Get a String from the user, if it has more than 30 characters, take the first 27, add an ellipsis (three full stops) and print that, otherwise print the whole String
  4. Get a String from the user and determine if the phrase ends in the word 'like', if so, remove this word from the phrase and print it.
  5. Get a String from the user, check to see if it contains the words: Java, code or String (using any combination of case such as jAvA), and if it contains at least one of them, print the String, otherwise ask for a new String - you will likely need to use a loop to do this, but it may be easier to verify the checking works before adding the loop.
  6. Create a modified version of the previous task, but this time only print it if none of the words are included. (This type of code can also be used to filter obcenities)
  7. Get a String from the user (prompt them to enter a phrase), and, using a loop calculate the number of lowercase letter e in a phrase

Verify what happens if you write the following code:

String someText = "Hello World".substring(6);
System.out.println(someText);
Can you explain why you get the result you do?

Reading & Research

Classes in Java are fairly well documented. Review the documentation for the String class. A this stage, much of it may not be fully understandable, but you should be able to get a better idea about what methods are available that haven't been covered in this tutorial.

The primitive types you have used so far have equivalent class versions. For boolean, int, char and double, investigate what the corresponding Class is called, and explore the methods available for each one. Ensure you make notes.

Advanced tasks

  1. Get a String from the user, then get an int from the user, representing a index in that String. Verify if that character is uppercase or lowercase. This may require further reading.
  2. Add error handling to the above task, so that if the number exceeds the length of the String, the programme does not crash

An example solution to this task can be found here