Java String - methods with example

java.lang
Class String


public final class String extends Object implements Serializable, Comparable<String>, CharSequence



In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string.For Example :

  char data[] = { 'j', 'a', 'v','a' };
String str = new String(data);
System.out.println(str);


is same as:

                String str = "java";



  • Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
  • The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
  • The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in java by using these three classes.
  • The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.

Create a String Object


By String Literal:

A string literal should be enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "knowledgefactory.net'.


      String str="knowledgefactory.net";



By new Keyword:


String str=new String("Knowledgefactory.net");


Java String class methods


  • charAt(int index):It returns the character at the specified index.

        String str="knowledegafctory";
        System.out.println(str.charAt(3));

         Output:w
                 


  • length():It returns the length of a String.
        String str="knowledegafctory";
        System.out.println(str.length());

        Output:16


  • equals(Object obj):Compares the string with the specified string and returns true if both matches else false.
       String str="knowledegafctory";
       String strnew="knowledegafctorys";
       System.out.println(str.equals(strnew));

           Output:false


  • equalsIgnoreCase(String string):It does a case insensitive comparison.
        String str="knowledegafctory";
        String strnew="KnowledegafctorY";
        System.out.println(str.equalsIgnoreCase(strnew));

            Output:true


  • compareTo(String string):This method compares the two strings based on the Unicode value of each character in the strings.
        String str="knowledegafctory";
        String strnew="KnowledegafctorY";
        System.out.println(str.compareTo(strnew));

           Output:32


  • compareToIgnoreCase(String str):Same as CompareTo method however it ignores the case during comparison.
       String str="knowledegafctory";
       String strnew="KnowledegafctorY";
       System.out.println(str.compareToIgnoreCase(strnew));

          Output:0



  • startsWith(String prefix):It tests whether the string is having specified prefix, if yes then it returns true else false.
       String str = "knowledegafctory";
       System.out.println(str.startsWith("know"));

         Output:true


  • startsWith(Str prefix,int offset):It checks whether the substring (starting from the specified offset index) is having the specified prefix or not.
       String str = "knowledegafctory";
       System.out.println(str.startsWith("now",1));

          Output:true


  • endsWith(String suffix):Checks whether the string ends with the specified suffix.
       String str = "knowledegafactory";
       System.out.println(str.endsWith("factory"));

          Output:true


  • hashCode():It returns the hash code of the string.
       String str = "knowledegafactory";
       System.out.println(str.hashCode());

         Output:-1923401781


  • indexOf(int ch): It returns the index of the first occurrence of character ch in a given String.
       String str = "knowledegafactory";
       System.out.println(str.indexOf('e'));

          Output:5


  • indexOf(int ch, int fromIndex): It returns the index of first occurrence of character ch in the given string after the specified index “fromIndex”. 
       String str = "knowledegafactory";
       System.out.println(str.indexOf('e',6));

          Output:7


  • lastindexOf(String str): Returns the index of last occurrence of string str.

  • substring(int beginIndex): It returns the substring of the string. The substring starts with the character at the specified index.
       String str = "knowledegafactory";
       System.out.println(str.substring(10)); 

         Output:factory


  • substring(int beginIndex, int endIndex): Returns the substring. The substring starts with character at beginIndex and ends with the character at endIndex.
       String str = "knowledegafactory";
       System.out.println(str.substring(10,14));

          Output:fact


  • replace(char oldChar, char newChar): It returns the new updated string after changing all the occurrences of oldChar with the newChar.
       String str = "knowledegafactory";
       System.out.println(str.replace('e','n'));

          Output:knowlndngafactory


  • boolean contains(CharSequence s): It checks whether the string contains the specified sequence of char values. If yes then it returns true else false.
       String str = "knowledegafactory";
       System.out.println(str.contains("now"));

          Output:true


  • toUpperCase(): Converts the string to upper case.
       String str = "knowledegafactory";
       System.out.println(str.toUpperCase());

          Output:KNOWLEDEGAFACTORY


  •  intern(): This method searches the specified string in the memory pool and if it is found then it returns the reference of it, else it allocates the memory space to the specified string and assign the reference to it.
  •  isEmpty(): This method returns true if the given string has 0 length. If the length of the specified Java String is non-zero then it returns false.
        String str = "knowledegafactory";
        System.out.println(str.isEmpty());

           Output:false


  • String join(): This method joins the given strings using the specified delimiter and returns the concatenated Java String

  • replaceFirst(String regex, String replacement): It replaces the first occurrence of substring that fits the given regular expression “regex” with the specified replacement string.
       
  • replaceAll(String regex, String replacement): It replaces all the occurrences of substrings that fits the regular expression regex with the replacement string.

  • split(String regex): Same as split(String regex, int limit) method however it does not have any threshold limit.
       String str="java string split method by knowledgefactory";  


       String[] words=str.split("\\s");//splits the string based on  whitespace  
       //using java foreach loop to print elements of string array  
for(String w:words){  
System.out.println(w);  
}  

          Output:
                      java
                      string
                      split
                      method
                      by
                      knowledgefactory

  • split(String regex, int limit): It splits the string and returns the array of substrings that matches the given regular expression. limit is a result threshold here.

  • toLowerCase(): It converts the string to lower case string.

  • format(): This method returns a formatted java String

  • trim(): Returns the substring after omitting leading and trailing white spaces from the original string.
       String str = "knowledgefactory  ";
       System.out.println(str.trim());




  • toCharArray(): Converts the string to a character array.
       
  • copyValueOf(char[] data): It returns a string that contains the characters of the specified character array.

  • copyValueOf(char[] data, int offset, int count): Same as above method with two extra arguments – initial offset of subarray and length of subarray.

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

       int num = 1223;
       char character = 'a';
       System.out.println(String.valueOf(num));
       System.out.println(String.valueOf(character));

         Output:
                    1223
                     a


  • length(): It returns the length of a String.

  • getBytes(String charsetName): It converts the String into sequence of bytes using the specified charset encoding and returns the array of resulted bytes.

  • getBytes(): This method is similar to the above method it just uses the default charset encoding for converting the string into sequence of bytes.


This article is contributed by Sibin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete