So far, our experience with Strings has been limited to declaring String Variables, Concatenating Strings, and using Escaped Characters.
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.
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
Methods 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.
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:
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');
The String class also provides a number of other methods, some of the key ones include:
length()
String phrase = "Hello World";
int phraseLength = phrase.length(); //phraseLength will be 11
charAt()
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()
String phrase = " The cat sat on the mat ";
String trimmedPhrase = phrase.trim(); //The cat sat on the mat
indexOf()
String progLangauage = "Java";
int indexOfA = progLangauage.indexOf('a'); //1
int indexOfV = progLangauage.indexOf('v'); //2
int indexOfZ = progLangauage.indexOf('z'); //-1
substring()
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()
Write command line programmes to do the following:
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?
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.
An example solution to this task can be found here