Java – String class with example

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

  1. Using String literal
  2. 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;
1-String-constant-literal-pool

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”);
2-String-object-in-heap-memory

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 createWhereas 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 areaThis 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 performanceEvery 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 poolThis 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

  1. char charAt(int index) : returns the char value at the specified index
  2. int compareTo(String anotherString) : compares two strings lexicographically
  3. int compareToIgnoreCase(String str) : compares two strings lexicographically, ignoring case differences
  4. String concat(String str) : concatenates the specified string to the end of this string
  5. boolean contains(CharSequence s) : returns true if and only if this string contains the specified sequence of char values
  6. boolean contentEquals(StringBuffer sb) : compares this string to the specified CharSequence or StringBuffer
  7. static String copyValueOf(char[] data) : used to copy the array/sequence of characters to string, by replacing the existing string (not appending/inserting)
  8. boolean endsWith(String suffix) : tests if this string ends with the specified suffix
  9. boolean equals(Object anObject) : compares this string to the specified object
  10. boolean equalsIgnoreCase(Object anObject) : compares this String to another String, ignoring case considerations
  11. 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
  12. byte[] getBytes() : encodes this String into a sequence of bytes and has 4 variations with one being deprecated considering Java 8
  13. 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)
  14. int hashCode() : returns a hash code for this string
  15. int indexOf(int ch) : returns index of 1st occurrence of specified character
  16. int indexOf(int ch, int fromIndex) : returns index of 1st occurrence of specified character, starts searching from fromIndex supplied
  17. int indexOf(String str) : returns index of 1st occurrence of specified substring
  18. int indexOf(String str, int fromIndex) : returns index of 1st occurrence of specified substring, starts searching from fromIndex supplied
  19. String intern() : Returns a canonical representation for the string object
  20. boolean isEmpty() : checks whether string is empty and returns true only if length() is 0
  21. int lastIndexOf(int ch) : returns index of last occurrence of specified character
  22. int lastIndexOf(int ch, int fromIndex) : returns index of last occurrence of specified character, starts searching from fromIndex supplied
  23. int lastIndexOf(String str) : returns index of last occurrence of specified substring
  24. int lastIndexOf(String str, int fromIndex) : returns index of last occurrence of specified substring, starts searching from fromIndex supplied
  25. int length() : returns the length of this string
  26. boolean matches(String regex) : tells whether or not this string matches the given regular expression
  27. 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
  28. String replace(char oldChar, char newChar) : returns new string after replacing all occurrences of oldChar value with newChar value
  29. String replace(CharSequence target, CharSequence replacement) : returns new string after replacing all occurrences of target CharSequence value with replacemnt CharSequence value
  30. String replaceAll(String regex, String replacement) : replaces each substring of this string that matches the given regular expression with the given replacement
  31. String replaceFirst(String regex, String replacement) : replaces the first substring of this string that matches the given regular expression with the given replacement
  32. String[] split(String regex) : returns string array after splitting this string matching the regular expression
  33. 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
  34. boolean startsWith(String prefix) : tests if this string starts with the specified prefix
  35. boolean startsWith(String prefix, int toffset) : tests if this string starts with the specified prefix, start searching from offset
  36. String substring(int beginIndex) : returns substring starting from supplied index
  37. String substring(int beginIndex, int endIndex) : returns substring in between beginIndex and endIndex
  38. char[] toCharArray() : converts this string to character array
  39. 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
  40. 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
  41. String toString() : converts the object to string but in this case it is already string
  42. String trim() : returns a new string after removing all leading and trailing whitespace from original string (in consideration)
  43. 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:

References:

Happy Coding !!
Happy Learning !!

Java - String Literal and String constant pool concept