|
The String class has many important methods. Following are some of the most commonly used methods which also important from the exam perspective.
This method creates a new string by appending the contents of string object passed as argument to the contents of string on which the method is invoked. The signature of this method is:
public String concat(String str)
You can invoke this method as:
String original = "Bon";
System.out.println(original.concat(" Voyage") );// "Bon Voyage” printed
The + and += operators (Chapter 9 operators) can also be used to concatenate strings. For example, you can do a string concatenation with + operator as:
String original = "Bon";
System.out.println(original + “ Voyage") );// "Bon Voyage” printed
The operator += has implicit assignment in it. Hence, it first creates a new string by concatenating and stores the reference of a new string in the original reference. For example,
String original = "Bon";
original += " Voyage"; //equivalent to original = original + " Voyage"
System.out.println(original);// "Bon Voyage” printed
Thus + will not modify the original string reference but += will. The string object however always remains unchanged.
This method creates a new string using the same contents as that of the string object on which the method is invoked. However, in the content of new string all occurrences of a character passed as first argument are replaced by the character in the second argument. The signature of this method is:
public String replace(char old, char new)
For instance, you can invoke this method to replace all occurrences of character ‘b’ with character ‘d’ in a string "Ball bearings" as:
String original = "Ball bearings";
System.out.println(original.replace('b', 'd') ); // “Ball dearings"
Note that only the character ‘b’ is replaced with ‘d’. The character ‘B’ is kept as it is. If the original string starts with lower case b, say "ball bearings", then original.replace('b', 'd') would result in “dall dearings” replacing both the occurrences of character ‘b’.
substring ()
The substring method creates a new string using partial contents of the String on which it is invoked. This method has two overloaded versions. The method signatures are:
public String substring(int begin)
public String substring(int begin, int end)
The first version takes the partial content from the index specified by begin until the end of the string. Note that index of the string is zero-based. It means that the first character in the string has the index 0, the second character has the index 1 and so on. You can create a new string “rings” by calling a substring method on string “bearings” as:
String original = "bearings";
System.out.println(original.substring(3)); // prints “rings"
We specified the begin index as 3. Since the character ‘r’ is at the third index, the rest of the contents until the end of the string are used to create the new substring. If you wish to create only “ring” from this string, you need to specify the end index as well. The second version of substring method allows you to specify the start and end index as:
String original = "bearings";
System.out.println(original.substring(3,6) ); // “rin" is printed
Note that end index is not exactly the index of the last character that you would like in your substring. Therefore, though ‘g’ is the character at 6th index. original.substring(3,6) will not include it. Hence, always remember that, you need to give the end index as index of the last character you want + 1. Therefore, the following code will print the substring “ring”.
String original = "bearings";
System.out.println(original.substring(3,7) ); // “ring" is printed
Figure 13.10 illustrates how the substring method works.
![]() |
Figure also shows the indices of characters in the string. As you can see, character index is zero-based. Therefore, the character at index 3 actually means the fourth character from left in the string.
toLowerCase()
This method creates a new String using the same contents of a String used to invoke the method. But all the characters in uppercase are converted into a lowercase. The signature of this method is:
public String toLowerCase()
You can create a string in all lower case characters by invoking this method as:
String original = "It's a Beautiful LIFE.";
System.out.println(original.toLowerCase()); // “it's a beautiful life."
A new string in all lower case characters “it's a beautiful life.” is printed after the above code is executed.
toUpperCase()
This method is just the opposite of toLowerCase()method. It creates a new string using the same contents of a string used to invoke the method. However, all the characters in lowercase are converted into uppercase. The signature of this method is:
public String toUpperCase()
You can create a string in all upper case characters by invoking this method as:
String original = "It's a Beautiful Life.";
System.out.println(original.toLowerCase()); // “IT'S A BEAUTIFUL LIFE."
A new string in all uppercase characters, “IT'S A BEAUTIFUL LIFE.” is printed after the above code is executed.
toString()
The String class inherits this method from the Object class. Usually this method should be overridden by subclasses of Object to return a string representation that object. Since the best representation of a string is its contents, this method does not try to create any new string object. It simply returns the reference of the same String that is used to invoke the method. The signature of this method is:
public String toString()
In the call to System.out.println(), you need not call the toString() method on any object as the println() methods calls it implicitly for printing string representation of any object. But you can also invoke it explicitly as:
String original = "It's a beautiful Life.";
System.out.println(original.toString());
The call original.toString() return the string referenced by original itself. Hence, the same contents (It's a beautiful Life.) are printed on output stream.
This method is inherited from the Object class. This method is used for object comparison. It takes another object as argument. The signature of this method is:
public boolean equals(Object anObject)
This method is overridden to check whether two strings are equal in contents. It does two things to decide it-
1. It checks whether the object passed as an argument is of type String (using the instanceof operator). If not this method returns false irrespective of the contents of that object.
2. Then it compares the contents of the string passed as argument and the contents of the string on which the method is invoked.
You can invoke this method as:
String str = "Are we same?";
System.out.println(str.equals("Are we same?")); // prints true
Note that this method considers the case of characters while comparing. Hence, it returns false even when characters in the two String objects are same but they are in different cases. For instance str.equals (“ARE we same?”) would be false.
|
|
The equals() method does not return true if the object passed in is not a string. For example, if you pass a char array with same contents as a string, equals() will still not return true. "same".equals(new char[]{'s','a','m','e'}); returns false. |
trim()
This method returns a new string with the same contents as the string used to invoke the method, but with any leading or trailing blank spaces removed. If the original string does not have any leading and trailing white spaces, then the new string has exactly same contents as the original string. In either case, the original string object remains unchangeable. The signature of this method is as:
public String trim()
You can invoke trim() to get a string without any leading or white spaces as:
String original = " Only this ";
System.out.println(original); // Prints " Only this "
System.out.println(original.trim()); // Prints "Only this"
Note that this method does not remove the white spaces within a string. Therefore the string contents are still “Only this” and not “Onlythis” after trimming.
This method returns a character located at the specified index within a string object. The signature of this method is:
public char charAt(int index)
The String indexes are similar to the array indexes. They start at 0. Therefore, you can get fourth character in a string as:
String str = "Voyage";
System.out.println(str.charAt(3) ); // character 'a' is printed
This method returns an index of the first occurrence of a character passed as argument. The signature of this method is:
public int indexOf(int ch)
The string indexes start at 0. Therefore, if a character is found at fifth position (from left) in a string. indexOf() returns 4 as:
String str = "Voyage";
System.out.println(str.indexOf(‘g’)); // 4 is printed
Note that the indexOf() takes an int argument. Hence you can pass a char as argument as char is narrower that int. Another overloaded version of this method allows you to set the starting position from where you will start searching for the character. The signature of this overloaded method is as:
public int indexOf(int ch, int fromIndex)
In the following example, the search for character ‘g’ starts at 2nd index.
String str = "great voyage";
System.out.println(str.indexOf(‘g’,2)); // 10 is printed
As the search for character ‘g’ starts at 2nd index, the ‘g’ at 0th index is not found. Note that if the specified character is not found in the given string, indexOf() return -1.
This method returns the length of the string used to invoke the method. In simple words, it returns the total number of characters in the string. The signature of this method is as:
public int length()
Note that, if the string has any white spaces (they are also part of string content) and hence the length() method account for them, For example,
String str = " Voyage ";
System.out.println(str.length()); // 8 is printed
|
|
Bear in mind that length() is a method in Strings and not a member variable. Do not confuse it with a Java array that has a member variable named length (not a method). The exam may have questions that try to use the length() method on an array, or try to use the length member variable on a string. In both cases, the compiler will flag an error. For example accessing “What is my length?”.length is erroneous. |
This method compares the contents of the string passed as an argument and the contents of the string on which the method is invoked. This method ignores the case (of characters) while comparing the contents. It means this method returns true even when characters in the two string objects are same but are in different cases. The signature of this method is:
public boolean equalsIgnoreCase(String anotherString)
You can invoke this method as:
String str = "check It";
System.out.println(str.equalsIgnoreCase(“CheCK It”)); // prints true
Note that this method ( and also the equals() method) compares for order of the characters as well. Therefore, all of the following statements will print false.
String str = "check It";
System.out.println(str.equalsIgnoreCase(“checkIt”)); // prints false
System.out.println(str.equalsIgnoreCase(“It Check”)); // prints false