Prev | Next |
String class
In Java, Strings are objects that represents a sequence of characters. String class supports a variety of constructors and methods to create and manipulate them.
Creating Strings
Strings can be created in two ways in Java. Both have different semantics.
String str1 = "Hello"; // Direct way to create string String str2 = new String("hello"); // Creating String instance char[] arr = {'h', 'e', 'l', 'l', 'o'}; String str3 = new String(arr); // From char array
Why support two ways?
Simply because many programmers would like to treat Strings as a primitive type while the programming language engineers think of Strings as a composite object made up of characters. When created the direct way, the string behaves like a primitive type. When created using new, the string behaves like a reference type.
String length
String str = "hello"; int len = str.length(); // len = 5
Equality of two strings
If strings are created the direct way, you can check for the equality like that of any primitive type. For example,
String s1 = "abc"; String s2 = "abc"; if (s1 == s2) { ... } // returns true
If strings are created using new, they are objects in the heap. You cannot compare them with "==" operator since it will compare two memory locations instead of values. String supports equals() method which is used to compare. See the code snippet below.
String str1 = new String("hello"); String str2 = new String("hello"); if (str1 == str2) { .... } // Incorrect way - returns false always if (str1.equals(str2)) { ... } // Correct way - returns true
Recall that we had implemented equals() method for Point class earlier. String class also has such an implementation. The method equalsIgnoreCase() compares two strings for equality by ignoring case.
Concatenating two strings
The following code snippet concatenates two strings str1 and str2 and returns a new string that is a concatenation of str1 and str2. The '+' operator can also be used to concatenate two strings.
str3 = str1.concat(str2); str3 = str1 + str2;
Immutability of Strings
Strings are immutable. Once a String object is created it cannot be modified.
- Firstly, none of the methods in the String class modifies itself. Instead it creates a new String object that contains the result of the operation and returns that. The above example on concatenation is a clear illustration of this fact. The original strings str1 and str2 don't undergo any changes, while a new string which is a combination of both is returned.
- Secondly, String is implemented as a final class. So, it is simply not possible to extend String to another class, say StringX, and override all the methods to make it mutable.
Find out why Strings are defined as immutable.
Note that in the above concatenation example, merely calling str1.concat() does not modify str1. However it is possible to reassign str1 to the concatenated string as follows.
str1.concat(str2); // No change to str1 str1 = str1.concat(str2); // str1 now points to a different memory location // The memory location pointed to by original str1 will be garbage collected
Finding the index of a char in a String
The indexOf() and lastIndexOf() methods are used to find the first and last index positions of the occurrence a particular char or char sequence in a String. All these methods return -1 if the char or string does not occur.
int pos1 = str.indexOf('x'); // first position of 'x' in str, -1 otherwise int pos2 = str.indexOf("xyz"); // first position of substring "xyz" int pos3 = str.indexOf("xyz", i); // first position of "xyz" from index i int pos4 = str.lastIndexOf('x'); // last occurrence of 'x' in str
Accessing ith character of a String
The charAt() method is used to access a character at a particular position of a String.String str = "hello" char c = str.charAt(i); // return character at position i char c ="hello".charAt(i); // means the same
Replacing ith character of a String
The replace() can be used to get a new String in which ith character is replaced. Note that replace() method returns a new String.str2 = str1.replace(i,'x'); // replace char at ith position with 'x'
There are other replace*() methods to replace a char sequence, first occurance and all occurances.
Checking substring
The contains() method is used to check if one string contains the other.
if (str1.contains(str2)) { .... } // Does str1 contain str2?
Getting substring
The substring() method is used get a part of a string given a range [i,j) or starting index (i).
str2 = str1.substring(i,j); // from i to j-1 str3 = str1.substring(i); // from i till end
Check for a prefix and suffix
The startsWith() and endsWith() methods are used respectively to check if a string starts or ends with a particular string sequence.
if (str1.startsWith(str2)) { ... } // Does str1 start with str2? if (str1.endsWith(str2)) { ... } // Does str1 end with str2?
Convert to a char array
The toCharArray() is used to convert a string to a char array.
char[] cArr = "abc".toCharArray(); // cArr = {'a', 'b', 'c'}
Convert to upper and lower case
The toUpperCase() and toLowerCase() are used respectively to convert all characters of a string to upper and lower cases.
str = "AbCd".toUpperCase(); // returns "ABCD" str = "AbCd".toLowerCase(); // returns "abcd"
Removing leading and trailing whitespaces
The trim() method is used to remove leading and trailing white spaces of a string.
str1 = " abc "; str2 = str1.trim(); // returns "abc"
From primitive value to String object
The valueOf() methods are used to convert values of primitive types to String object. Note that valueOf() is a static method that is invoked using class name.
str = String.valueOf(true); // returns "true" str = String.valueOf(25); // returns "25" str = String.valueOf(25.8); // returns "25.8"
Tokenize based on regex pattern
The split() method is used to split a string into an array of strings based on a regex pattern.
String str1 = "abc;defg;hi;jklm;nop"; String[] tokens1 = str1.split(";"); // tokens1 = {"abc", "defg", "hi", "jklm", "nop"} String str2 = "abc;defg:hi,jklm;nop"; String[] tokens2 = str2.split(";" | ":" | ","); // tokens2 = {"abc", "defg", "hi", "jklm", "nop"}
Creating formatted strings
The format() method is used create a formatted string in much the same way as printf() of C does. format() is a static method. The code snippet below demonstrates this.
int invVal = 10; float floatVal = 2.3; String strVal = "hello" String fmtString = String.format("Integer value is %d, " + "Float value is %f, " + "String value is %s", intVal, floatVal, strVal); System.out.println(fmtString);
Note that the effect of the above code is same as the one below.
int invVal = 10; float floatVal = 2.3; String strVal = "hello" System.out.printf("Integer value is %d, " + "Float value is %f, " + "String value is %s", intVal, floatVal, strVal);
Exercises: Unique characters, reverse, palindrome
StringBuilder
StringBuilder is the mutable equivalent of the String class. When you want to manipulate (i.e. perform inserts, deletes or appends) a string several times, using a String object is inefficient since for every manipulation we get a new string object. StringBuilder is a mutable sequence of chars and hence can be modified without consuming additional space. Once all the manipulations are complete, it can be converted to a String object. The following code snippet shows some common operations on StringBuilder.
StringBuilder sb = new StringBuilder("abc"); sb.append("def"); // sb is now "abcdef" sb.append(10.5); // sb is now "abcdef10.5" sb.insert(3,"xyz"); // sb is now "abcxyzdef10.5" sb.delete(4,7); // sb is now "abcef10.5" sb.deleteCharAt(2); // sb is now "abef10.5" String str = sb.toString(); // str = "abef10.5"
For complete documentation refer to Java docs page at Oracle.