In this article, we will learn and understand String class and list its methods in detail
1. String
- String is a sequence of characters or array of characters
2. char, char-array and String
Let us understand char, char array and String with examples,
1. char: To represent char data-type in Java, we use single quote (‘b’)
char testChar = ‘b’;
2. char[]: char array is represented using, sequence of comma-separated char values within curly-braces
char[] testCharArray = {‘b’, ‘e’, ‘n’, ‘c’, ‘h’};
3. String: To represent String data-type in Java, we use double quotes (“bench”)
String testString = “bench”;
3. Conversion of char-array to String
- We can use char array to build String in Java using String class constructor
// char-array
char[] testCharArray = {'b', 'e', 'n', 'c', 'h'};
// string constructed using above char[]
String strNew = new String(testCharArray);
4. Creating String:
There are 2 ways to create a String
- Using String literal
- Using new operator (like other objects in Java)
4.1 String Literal
- In Java, String uses the concept of string constant pool or string literal pool or simply string pool which is used interchangeably to refer the special pool area inside heap memory to store unique strings
- As we all know in Java, everything is object except primitive types even for that case Java has equivalent wrapper classes
- And other exceptional is String
- Yes, String can be created using double quotes i.e.; without new keyword
- Reason : Java does for us to increase the performance
String str = “Bench Resources”;
Let us understand all above statements in detail,
There are 3 strings inside string literal pool area, these are,
String str1 = “bench”;
String str2 = “resources”;
String str21 = “resources”;
String str3 = str1 + “ “ + str2;
Explanation:
String creation logics inside String literal pool area,
- When we created 1st string str1 = “bench” using double quotes, compiler checks string literal pool area and finds no equivalent string so it creates called “bench”
- In the next line, when we created 2nd string str2 = “resources” using double quotes, again compiler checks string literal pool area and finds no equivalent string so it creates another string called “resources”
- But in the next line when it encountered str 21 = “resources” again, compiler checks string literal pool area and finds exact string so doesn’t creates a new string instead a reference to string is assigned to str21
- String str3 is the combination of str1 and str2 which is concantenated using + operator (this is padded with a space in between)
4.2 String object using new keyword
- The other way to create String in Java is using new keyword. For example,
String referenceStr = new String(“Bench”);
- This time, when we created string object using new keyword/operator then it is created inside heap memory and its reference is assigned
There are 2 strings inside heap memory area, these are,
- String strRef1 = new String(“williamson”);
- String strRef2 = new String(“williamson”);
Explanation:
Above figure depicts, 2 string creation using new keyword/operator
- 1st time, when we created string object –> then a new string is created inside heap memory and its reference-address is assigned to strRef1
- In the next line, when we created same string object –> again a new string is created inside heap memory and its reference-address is assigned to strRef2
- So every time, when we create objects using new operator/keyword then always a new string is placed inside heap memory and its reference-address is returned
4.3 String objects v/s String Literal:
String Literal | String objects |
String literal is created using double quotes and thus are simple to create | Whereas string objects is created using new operator/keyword (a pure OO principle) |
Strings created using double quotes are always stored/placed inside String Literal pool area | This is created using new operator/keyword and stored/placed inside heap memory |
This avoids duplication of same string inside string literal pool area and thus increases performance | Every time a new object is created, as new string is stored/placed inside heap memory even though it can be same string value |
This is also referred as string constant pool or simply string pool | This is referred as string objects and sometime it storage area i.e.; heap memory is referred as non-pool area |
5. String class methods
String class provides useful methods for string handling purpose like,
- Getting sub-string
- Finding length of the string
- Formatting string
Here, we will list out some of the very useful methods which are frequently used for string handling
- char charAt(int index) : returns the char value at the specified index
- int compareTo(String anotherString) : compares two strings lexicographically
- int compareToIgnoreCase(String str) : compares two strings lexicographically, ignoring case differences
- String concat(String str) : concatenates the specified string to the end of this string
- boolean contains(CharSequence s) : returns true if and only if this string contains the specified sequence of char values
- boolean contentEquals(StringBuffer sb) : compares this string to the specified CharSequence or StringBuffer
- static String copyValueOf(char[] data) : used to copy the array/sequence of characters to string, by replacing the existing string (not appending/inserting)
- boolean endsWith(String suffix) : tests if this string ends with the specified suffix
- boolean equals(Object anObject) : compares this string to the specified object
- boolean equalsIgnoreCase(Object anObject) : compares this String to another String, ignoring case considerations
- static String format(String format, Object… args) : returns a formatted string using the specified format string and arguments. There is one more variation which includes Locale as argument
- byte[] getBytes() : encodes this String into a sequence of bytes and has 4 variations with one being deprecated considering Java 8
- void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) : copies characters from source string into the destination character array (srcBegin and srcEnd defines the limit)
- int hashCode() : returns a hash code for this string
- int indexOf(int ch) : returns index of 1st occurrence of specified character
- int indexOf(int ch, int fromIndex) : returns index of 1st occurrence of specified character, starts searching from fromIndex supplied
- int indexOf(String str) : returns index of 1st occurrence of specified substring
- int indexOf(String str, int fromIndex) : returns index of 1st occurrence of specified substring, starts searching from fromIndex supplied
- String intern() : Returns a canonical representation for the string object
- boolean isEmpty() : checks whether string is empty and returns true only if length() is 0
- int lastIndexOf(int ch) : returns index of last occurrence of specified character
- int lastIndexOf(int ch, int fromIndex) : returns index of last occurrence of specified character, starts searching from fromIndex supplied
- int lastIndexOf(String str) : returns index of last occurrence of specified substring
- int lastIndexOf(String str, int fromIndex) : returns index of last occurrence of specified substring, starts searching from fromIndex supplied
- int length() : returns the length of this string
- boolean matches(String regex) : tells whether or not this string matches the given regular expression
- boolean regionMatches(int toffset, String other, int ooffset, int len) : tests if two string regions are equal (checks whether substring supplied with another substring in question)
And there is one more variation which is useful to turn-off Case-Sensitive by supplying Boolean flag as true - String replace(char oldChar, char newChar) : returns new string after replacing all occurrences of oldChar value with newChar value
- String replace(CharSequence target, CharSequence replacement) : returns new string after replacing all occurrences of target CharSequence value with replacemnt CharSequence value
- String replaceAll(String regex, String replacement) : replaces each substring of this string that matches the given regular expression with the given replacement
- String replaceFirst(String regex, String replacement) : replaces the first substring of this string that matches the given regular expression with the given replacement
- String[] split(String regex) : returns string array after splitting this string matching the regular expression
- String[] split(String regex, int limit) : returns string array after splitting this string matching the regular expression. The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array
- boolean startsWith(String prefix) : tests if this string starts with the specified prefix
- boolean startsWith(String prefix, int toffset) : tests if this string starts with the specified prefix, start searching from offset
- String substring(int beginIndex) : returns substring starting from supplied index
- String substring(int beginIndex, int endIndex) : returns substring in between beginIndex and endIndex
- char[] toCharArray() : converts this string to character array
- String toLowerCase() : converts all of the characters in this String to lower case using the rules of the default locale
There is one more variation which does the same thing of converting all characters to lower case using the specified argument Locale - String toUpperCase() : converts all of the characters in this String to upper case using the rules of the default locale
There is one more variation which does the same thing of converting all characters to upper case using the specified argument Locale - String toString() : converts the object to string but in this case it is already string
- String trim() : returns a new string after removing all leading and trailing whitespace from original string (in consideration)
- static String valueOf(DataType dataType) : returns a string representation of specified data type
There are around 9 overloaded methods taking different primitive types
Related Articles:
- String charAt(int index) method
- String compareTo(String anotherString) method
- String compareToIgnoreCase(String str) method
- String concat(String str) method
- String contains(CharSequence s) method
- String contentEquals(StringBuffer sb) method
- String copyValueOf(char[] data) method (2)
- String endsWith(String suffix) method
- String equals(Object anObject) method
- String equalsIgnoreCase(Object anObject) method
- String format(String format, Object… args) method
- String getBytes() method (4)
- String getChars() method
- String hashCode() method
- String indexOf() method (4)
- String intern() method
- String isEmpty() method
- String join() method (2)
- String lastIndexOf() method (4)
- String length() method
- String matches(String regex) method
- String regionMatches() method (2)
- String replace(char oldChar, char newChar) method
- String replace(CharSequence target, CharSequence replacement) method
- String replaceAll(String regex, String replacement) method
- String replaceFirst(String regex, String replacement) method
- String split(String regex) method
- String split(String regex, int limit) method
- String startsWith(String prefix) method
- String startsWith(String prefix, int toffset) method
- String subSequence(int beginIndex, int endIndex) method
- String substring(int beginIndex) method
- String substring(int beginIndex, int endIndex) method
- String toCharArray() method
- String toLowerCase() method (2)
- String toUpperCase() method (2)
- String toString() method
- String trim() method
- String valueOf() method (9)
References:
- https://docs.oracle.com/javase/tutorial/java/data/strings.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html
Happy Coding !!
Happy Learning !!