Introduction to String Class and Methods with Examples in Java

In java, String is an immutable object which can be defined as a sequence or series of characters. Once created, a String cannot be changed or modified and all such operations on a String lead to creation of a new String object. String class belongs to java.lang package, which needs not to be imported separately. Let’s see more about the ways in which the String can be created and the methods with examples inside String class.

Read Also : Why String is immutable in java

How to Create a String in Java?

A Java String can be created using following ways:

1.    By assigning a String literal
2.    By using “new” keyword

By assigning a String literal

String literal is a simple string inside " " (double quotes). A String literal is considered as a String object.

In this method, we simply assign the value of the String literal to the String reference.

String string1 = "abc"; 

Here, string1 is the reference which is getting assigned with the literal “abc”. If one more reference string2 is assigned with the same literal then the newly created reference will also point to the same String pool object as the previous reference.

String string2 = "abc"; 


String class in java


So, in this case the comparison using == will always return true since the object to which both the references are pointing is same.

By using "new" keyword

We can use new keyword for creating a String whenever we want a new String object to be created.

String string1 = new String("abc"); 

In this case, the object will be created in heap memory. 

If one more object is created using new keyword but with the same literal,

String string2 = new String("abc"); 

the comparison using == will always return false since the object to which both the references are pointing will always be different.

String Example in Java


public class HelloWorld {

    public static void main(String args[]) {
        // Creating String using String literal
        String string1 = "abc";
        String string2 = "abc";
        System.out.println(string1);    
  
       // Creating String using new keyword
       String string3 = new String("abc");
       String string4 = new String("abc");
       System.out.println(string3);
 
      /* References string1 and string2 point to 
         same String in Stringpool */     
       System.out.println(string1 == string2);
 
      /* References string3 and string4 point to
         different String object because these have
         created using new keyword */ 
       System.out.println(string3 == string4);       
 }
}

Output :
abc
abc
true
false

Important String Class Methods in Java

Here is the list of the methods available in the Java String class.

1.    char charAt(int index): It returns the char value or the character at the given index. The index range is similar to Array index, that is, it can be between 0 and length()-1.

2.    int codePointAt(int index): It is similar to the previous method except that it returns the Unicode numeric value of the character present at the given index. For example: A is represented by Unicode numeric value of 65, B as 66, a as 97, b as 98 and so on.

3.    int compareTo(String str): It compares the char sequence of the original String with the char sequence of the argument string based on the Unicode numeric value of each character.

4.    String concat(String str): It concatenates the argument string to this string.

5.    boolean equals(Object object): It compares this string with the given Object and returns true if and only if the argument is not null and it is a string equivalent of the this string.

6.    boolean equalsIgnoreCase(String str): It is similar to equals method except for the fact that it ignores the case differences.

7.    boolean startsWith(String prefix): This method checks if this string starts with the given prefix. It returns true if the char sequence of the argument(prefix) string is a prefix of the char sequence of this string.

8.    boolean startsWith(String prefix, int offset): This method takes into the account the substring of this string that starts from the given offset index. It checks if this substring starts with the given prefix or not similar to startsWith method. It is important to note here that false will be return whenever offset value is negative or greater than the length of this string.
9.    boolean endsWith(String suffix): This method checks if this string ends with the given suffix. It returns true if the char sequence of the argument(suffix) string is a suffix of the char sequence represented by this string.

10.  int indexOf(String str): It returns the index of the first occurrence of the argument substring in this string.

11.  int indexOf(String str, int fromIndex): It returns the index of the first occurrence of the argument substring in this string starting from the given index.

12.  int indexOf(int char): It returns the index of the first occurrence of the character represented by the specified Unicode numeral value within this string. If the char equivalent pf the int value is not found in the char sequence of the string then -1 is returned.

13.  int indexOf(int char, int fromIndex): It is same as indexOf(int char) method except the fact that it searches from the specified index.

14.  int lastindexOf(String str): It returns the index of the last occurrence of the argument substring in this string.

15.  int lastIndexOf(int char): It returns the index of the last occurrence of the character represented by the specified Unicode numeral value within this string.

16.  int lastIndexOf(String str, int fromIndex): It returns the index of the last occurrence of the argument substring in this string, searching backwards, starting from the given index.

17.  int lastIndexOf(int char, int fromIndex): It is same as lastIndexOf(int char) method, except that it searches backward from the specified index.

18.  int length(): It returns the length of this string which is same as number of Unicode code units present in this string.

19.  String trim(): It returns a string which holds the value of this string with all the leading and trailing white spaces removed.

20.  boolean isEmpty(): It used to simply check if the string is empty. If the length of the string is 0 then true is returned otherwise false is returned.

21.  String toLowerCase(): It converts all the characters present in this string to lower case by referring default locale.

22.  String toUpperCase(): It converts all the characters present in this string to upper case by referring the default locale.

23.    String substring(int beginIndex): It returns the substring of this string that starts from the given index.

24.    String substring(int beginIndex, int endIndex): It returns the substring of this string that starts from the given begin index(first argument) and extends till the index calculated using endIndex-1. It means that the first index argument is inclusive and second index argument in this method is exclusive.

25.    boolean contains(CharSequence charSequence): It returns true if this string contains given sequence of char values else returns false.

26.    int hashCode(): It returns the hash code value of this string. The hashcode of an empty string will always be 0.

27.    byte[] getBytes(): It returns the resultant byteArray after encoding this string to byte sequence using the default charset.

28.    String replace(char oldChar, char newChar): It returns the resultant string after replacing all the occurrences of oldChar in the original string with the newChar and returns the resultant string.

29.    String replaceAll(String regex, String replacement): It replaces all the occurrences of substrings that matches the given regular expression with the specified replacement string and returns the resultant string.

30.    char[] toCharArray(): It converts this string to a new character array whose length is same as length of this string.

31.    String[] split(String regex): It gives the resultant string array after splitting the string using the specified regular expression.

32.    String format(String format, Object… args): It returns the formatted string generated by using specified arguments and format.

33.    String intern(): It returns the returns the string from string pool if the specified string already exists else it adds a String object to the string pool and returns its reference.

34.    String valueOf(): This method returns a string representation of passed arguments such as int, long, float, double, char and char array.

35.    boolean matches(String regex): It checks if this string matches the given regular expression.

Reference :
Java String Doc

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry