Java String

By | October 25th 2019 08:53:41 PM | viewed 42 times

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[] ch={'j','a','v','a','t','p','o','i','n','t'};  
  String s=new String(ch);  
	

is same as:

String s="javatpoint"; 

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

CharSequence Interface

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.

We will discuss immutable string later. Let's first understand what is String in Java and how to create the String object.

What is String in java

Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.

How to create a string object?

There are two ways to create String object:

  • By string literal
  • By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

 String s="welcome";  

Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:

    String s1="Welcome";  
    String s2="Welcome";//It doesn't create a new instance  

In the above example, only one object will be created. Firstly, JVM will not find any string object with the value "Welcome" in string constant pool, that is why it will create a new object. After that it will find the string with the value "Welcome" in the pool, it will not create a new object but will return the reference to the same instance.

Note: String objects are stored in a special memory area known as the "string constant pool".

Why Java uses the concept of String literal?

To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).

2) By new keyword

    String s=new String("Welcome");//creates two objects and one reference variable  

In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-pool).

Java String Example
    public class StringExample{  
    public static void main(String args[]){  
    String s1="java";//creating string by java string literal  
    char ch[]={'s','t','r','i','n','g','s'};  
    String s2=new String(ch);//converting char array to string  
    String s3=new String("example");//creating java string by new keyword  
    System.out.println(s1);  
    System.out.println(s2);  
    System.out.println(s3);  
    }}  

java
strings
example

Java String class methods

The java.lang.String class provides many useful methods to perform operations on sequence of char values.

No. Method Description
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 static String format(String format, Object... args) returns a formatted string.
4 static String format(Locale l, String format, Object... args) returns formatted string with given locale.
5 String substring(int beginIndex) returns substring for given begin index.
6 String substring(int beginIndex, int endIndex) returns substring for given begin index and end index.
7 boolean contains(CharSequence s) returns true or false after matching the sequence of char value.
8 static String join(CharSequence delimiter, CharSequence... elements)) returns a joined string.
9 static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) returns a joined string.
10 boolean equals(Object another) checks the equality of string with the given object.
11 boolean isEmpty() checks if string is empty.
12 String concat(String str) concatenates the specified string.
13 String replace(char old, char new) replaces all occurrences of the specified char value
14 String replace(CharSequence old, CharSequence new) replaces all occurrences of the specified CharSequence.
15 static String equalsIgnoreCase(String another) compares another string. It doesn't check case.
16 String[] split(String regex) returns a split string matching regex.
17 String[] split(String regex, int limit) returns a split string matching regex and limit.
18 String intern() returns an interned string.
19 int indexOf(int ch) returns the specified char value index.
20 int indexOf(int ch, int fromIndex) returns the specified char value index starting with given index.
21 int indexOf(String substring) returns the specified substring index.
22 int indexOf(String substring, int fromIndex) returns the specified substring index starting with given index.
23 String toLowerCase() returns a string in lowercase.
24 String toLowerCase(Locale l) returns a string in lowercase using specified locale.
25 String toUpperCase() returns a string in uppercase.
26 String toUpperCase(Locale l) returns a string in uppercase using specified locale.
27 String trim() removes beginning and ending spaces of this string.
28 static String valueOf(int value) converts given type into string. It is an overloaded method.

Example

Java String charAt() method example

    public class CharAtExample{  
    public static void main(String args[]){  
    String name="javatpoint";  
    char ch=name.charAt(4);//returns the char value at the 4th index  
    System.out.println(ch);  
    }}  

Test it Now

Output:

t

StringIndexOutOfBoundsException with charAt()

Let's see the example of charAt() method where we are passing greater index value. In such case, it throws StringIndexOutOfBoundsException at run time.


    public class CharAtExample{  
    public static void main(String args[]){  
    String name="javatpoint";  
    char ch=name.charAt(10);//returns the char value at the 10th index  
    System.out.println(ch);  
    }}  

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
String index out of range: 10
at java.lang.String.charAt(String.java:658)
at CharAtExample.main(CharAtExample.java:4)

Java String charAt() Example 3

    public class CharAtExample3 {  
        public static void main(String[] args) {  
        String str = "Welcome to Javatpoint portal";      
        int strLength = str.length();      
        // Fetching first character  
        System.out.println("Character at 0 index is: "+ str.charAt(0));      
        // The last Character is present at the string length-1 index  
        System.out.println("Character at last index is: "+ str.charAt(strLength-1));      
        }  
    }  

Output:

Character at 0 index is: W
Character at last index is: l

Java String charAt() Example 4

    public class CharAtExample4 {  
        public static void main(String[] args) {  
            String str = "Welcome to Javatpoint portal";          
            for (int i=0; i<=str.length()-1; i++) {  
                if(i%2!=0) {  
                    System.out.println("Char at "+i+" place "+str.charAt(i));  
                }  
            }  
        }  
    }  

Output:

Char at 1 place e
Char at 3 place c
Char at 5 place m
Char at 7 place  
Char at 9 place o
Char at 11 place J
Char at 13 place v
Char at 15 place t
Char at 17 place o
Char at 19 place n
Char at 21 place  
Char at 23 place o
Char at 25 place t
Char at 27 place l


Java String charAt() Example 5

    public class CharAtExample5 {  
        public static void main(String[] args) {  
            String str = "Welcome to Javatpoint portal";  
            int count = 0;  
            for (int i=0; i<=str.length()-1; i++) {  
                if(str.charAt(i) == 't') {  
                    count++;  
                }  
            }  
            System.out.println("Frequency of t is: "+count);  
        }  
    }  

Output:

Frequency of t is: 4

Java String compareTo() method example

    public class CompareToExample{  
    public static void main(String args[]){  
    String s1="hello";  
    String s2="hello";  
    String s3="meklo";  
    String s4="hemlo";  
    String s5="flag";  
    System.out.println(s1.compareTo(s2));//0 because both are equal  
    System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"  
    System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"  
    System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"  
    }}  

Test it Now

Output:

0
-5
-1
2

Java String compareTo(): empty string

If you compare string with blank or empty string, it returns length of the string. If second string is empty, result would be positive. If first string is empty, result would be negative.

    public class CompareToExample2{  
    public static void main(String args[]){  
    String s1="hello";  
    String s2="";  
    String s3="me";  
    System.out.println(s1.compareTo(s2));  
    System.out.println(s2.compareTo(s3));  
    }}  

Test it Now

Output:

5
-2

Java String concat() method example

    public class ConcatExample{  
    public static void main(String args[]){  
    String s1="java string";  
    s1.concat("is immutable");  
    System.out.println(s1);  
    s1=s1.concat(" is immutable so assign it explicitly");  
    System.out.println(s1);  
    }}  

Test it Now

java string
java string is immutable so assign it explicitly

Java String concat() Method Example 2

    public class ConcatExample2 {  
        public static void main(String[] args) {      
            String str1 = "Hello";  
            String str2 = "Javatpoint";  
            String str3 = "Reader";  
            // Concatenating one string   
            String str4 = str1.concat(str2);          
            System.out.println(str4);  
            // Concatenating multiple strings  
            String str5 = str1.concat(str2).concat(str3);  
            System.out.println(str5);  
        }  
    }  

Output:

HelloJavatpoint
HelloJavatpointReader

Java String concat() Method Example 3

    public class ConcatExample3 {  
        public static void main(String[] args) {  
            String str1 = "Hello";  
            String str2 = "Javatpoint";  
            String str3 = "Reader";  
            // Concatenating Space among strings  
            String str4 = str1.concat(" ").concat(str2).concat(" ").concat(str3);  
            System.out.println(str4);         
            // Concatenating Special Chars        
            String str5 = str1.concat("!!!");  
            System.out.println(str5);         
            String str6 = str1.concat("@").concat(str2);  
            System.out.println(str6);  
        }  
    }  

Output:

Hello Javatpoint Reader
Hello!!!
Hello@Javatpoint

Java String contains() method example

    class ContainsExample{  
    public static void main(String args[]){  
    String name="what do you know about me";  
    System.out.println(name.contains("do you know"));  
    System.out.println(name.contains("about"));  
    System.out.println(name.contains("hello"));  
    }}  

Test it Now

true
true
false

Java String contains() Method Example 2

The contains() method searches case sensitive char sequence. If the argument is not case sensitive, it returns false. Let's see an example below.

    public class ContainsExample2 {  
        public static void main(String[] args) {  
            String str = "Hello Javatpoint readers";  
            boolean isContains = str.contains("Javatpoint");  
            System.out.println(isContains);  
            // Case Sensitive  
            System.out.println(str.contains("javatpoint")); // false  
        }  
    }  

true
false

Java String contains() Method Example 3

The contains() method is helpful to find a char-sequence in the string. We can use it in control structure to produce search based result. Let us see an example below.

    public class ContainsExample3 {   
        public static void main(String[] args) {          
            String str = "To learn Java visit Javatpoint.com";        
            if(str.contains("Javatpoint.com")) {  
                System.out.println("This string contains javatpoint.com");  
            }else  
                System.out.println("Result not found");       
        }  
    }  

Output:

This string contains javatpoint.com

Java String endsWith() method example

    public class EndsWithExample{  
    public static void main(String args[]){  
    String s1="java by javatpoint";  
    System.out.println(s1.endsWith("t"));  
    System.out.println(s1.endsWith("point"));  
    }}  

Test it Now

Output:

true
true

Java String endsWith() Method Example 2

    public class EndsWithExample2 {  
        public static void main(String[] args) {  
            String str = "Welcome to Javatpoint.com";  
            System.out.println(str.endsWith("point"));  
            if(str.endsWith(".com")) {  
                System.out.println("String ends with .com");  
            }else System.out.println("It does not end with .com");  
        }  
    }  

Output:

false
String ends with .com

Java String equals() method example

    public class EqualsExample{  
    public static void main(String args[]){  
    String s1="javatpoint";  
    String s2="javatpoint";  
    String s3="JAVATPOINT";  
    String s4="python";  
    System.out.println(s1.equals(s2));//true because content and case is same  
    System.out.println(s1.equals(s3));//false because case is not same  
    System.out.println(s1.equals(s4));//false because content is not same  
    }}  

Test it Now

true
false
false

Java String equals() Method Example 2

The equals() method compares two strings and can be used in if-else control structure.

    public class EqualsExample {  
        public static void main(String[] args) {  
            String s1 = "javatpoint";    
            String s2 = "javatpoint";    
            String s3 = "Javatpoint";  
            System.out.println(s1.equals(s2)); // True because content is same    
            if (s1.equals(s3)) {  
                System.out.println("both strings are equal");  
            }else System.out.println("both strings are unequal");     
        }  
    }  

true
both strings are unequal

Java String equals() Method Example 3

    import java.util.ArrayList;  
    public class EqualsExample3 {  
        public static void main(String[] args) {  
            String str1 = "Mukesh";  
            ArrayList list = new ArrayList<>();  
            list.add("Ravi");   
            list.add("Mukesh");  
            list.add("Ramesh");  
            list.add("Ajay");  
            for (String str : list) {  
                if (str.equals(str1)) {  
                    System.out.println("Mukesh is present");  
                }  
            }  
        }  
    }  

Mukesh is present

Java String equalsIgnoreCase() method example

    public class EqualsIgnoreCaseExample{  
    public static void main(String args[]){  
    String s1="javatpoint";  
    String s2="javatpoint";  
    String s3="JAVATPOINT";  
    String s4="python";  
    System.out.println(s1.equalsIgnoreCase(s2));//true because content and case both are same  
    System.out.println(s1.equalsIgnoreCase(s3));//true because case is ignored  
    System.out.println(s1.equalsIgnoreCase(s4));//false because content is not same  
    }}  

Test it Now

true
true
false

Java String equalsIgnoreCase() Method Example 2

    import java.util.ArrayList;  
    public class EqualsIgnoreCaseExample2 {  
        public static void main(String[] args) {  
            String str1 = "Mukesh Kumar";  
            ArrayList list = new ArrayList<>();  
            list.add("Mohan");   
            list.add("Mukesh");  
            list.add("RAVI");  
            list.add("MuKesH kuMar");  
            list.add("Suresh");  
            for (String str : list) {  
                if (str.equalsIgnoreCase(str1)) {  
                    System.out.println("Mukesh kumar is present");  
                }  
            }  
        }  
    }  

Output:

Mukesh kumar is present

Java String format() method example

    public class FormatExample{  
    public static void main(String args[]){  
    String name="sonoo";  
    String sf1=String.format("name is %s",name);  
    String sf2=String.format("value is %f",32.33434);  
    String sf3=String.format("value is %32.12f",32.33434);//returns 12 char fractional part filling with 0  
      
    System.out.println(sf1);  
    System.out.println(sf2);  
    System.out.println(sf3);  
    }}  

Test it Now

name is sonoo
value is 32.334340
value is                  32.334340000000

Java String Format Specifiers

Format Specifier Data Type Output
%a floating point (except BigDecimal) Returns Hex output of floating point number.
%b Any type "true" if non-null, "false" if null
%c character Unicode character
%d integer (incl. byte, short, int, long, bigint) Decimal Integer
%e floating point decimal number in scientific notation
%f floating point decimal number
%g floating point decimal number, possibly in scientific notation depending on the precision and value.
%h any type Hex String of value from hashCode() method.
%n none Platform-specific line separator.
%o integer (incl. byte, short, int, long, bigint) Octal number
%s any type String value
%t Date/Time (incl. long, Calendar, Date and TemporalAccessor) %t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.
%x integer (incl. byte, short, int, long, bigint) Hex string

Java String format() Method Example 2

    public class FormatExample2 {  
        public static void main(String[] args) {  
            String str1 = String.format("%d", 101);          // Integer value  
            String str2 = String.format("%s", "Amar Singh"); // String value  
            String str3 = String.format("%f", 101.00);       // Float value  
            String str4 = String.format("%x", 101);          // Hexadecimal value  
            String str5 = String.format("%c", 'c');          // Char value  
            System.out.println(str1);  
            System.out.println(str2);  
            System.out.println(str3);  
            System.out.println(str4);  
            System.out.println(str5);  
        }  
      
    }  

Test it Now

101
Amar Singh
101.000000
65
c

Java String format() Method Example 3

Apart from formatting, we can set width, padding etc. of any value. Let us see an example where we are setting width and padding for an integer value.

    public class FormatExample3 {  
        public static void main(String[] args) {          
            String str1 = String.format("%d", 101);  
            String str2 = String.format("|%10d|", 101);  // Specifying length of integer  
            String str3 = String.format("|%-10d|", 101); // Left-justifying within the specified width  
            String str4 = String.format("|% d|", 101);   
            String str5 = String.format("|%010d|", 101); // Filling with zeroes  
            System.out.println(str1);  
            System.out.println(str2);  
            System.out.println(str3);  
            System.out.println(str4);  
            System.out.println(str5);  
        }  
    }  

Test it Now

101
|       101|
|101       |
| 101|
|0000000101|

Java String getBytes() method example

    public class StringGetBytesExample{  
    public static void main(String args[]){  
    String s1="ABCDEFG";  
    byte[] barr=s1.getBytes();  
    for(int i=0;i<barr.length;i++){  
    System.out.println(barr[i]);  
    }  
    }}  

Output:

65
66
67
68
69
70
71

Java String getBytes() Method Example 2

This method returns a byte array that again can be passed to String constructor to get String.

    public class StringGetBytesExample2 {  
        public static void main(String[] args) {  
            String s1 = "ABCDEFG";  
            byte[] barr = s1.getBytes();  
            for(int i=0;i<barr.length;i++){  
                System.out.println(barr[i]);  
            }  
            // Getting string back   
            String s2 = new String(barr);  
            System.out.println(s2);  
        }  
    }  

Output:

65
66
67
68
69
70
71
ABCDEFG

Java String getChars() method example

    public class StringGetCharsExample{  
    public static void main(String args[]){  
     String str = new String("hello javatpoint how r u");  
          char[] ch = new char[10];  
          try{  
             str.getChars(6, 16, ch, 0);  
             System.out.println(ch);  
          }catch(Exception ex){System.out.println(ex);}  
    }}  
Output:

javatpoint

Java String getChars() Method Example 2

    public class StringGetCharsExample2 {  
        public static void main(String[] args) {  
            String str = new String("Welcome to Javatpoint");  
            char[] ch  = new char[20];  
            try {  
                str.getChars(1, 26, ch, 0);  
                System.out.println(ch);  
            } catch (Exception e) {  
                System.out.println(e);  
            }  
        }  
    }  

Output:

java.lang.StringIndexOutOfBoundsException: offset 10, count 14, length 20

Java String indexOf()

There are 4 types of indexOf method in java. The signature of indexOf methods are given below:

No. Method Description
1 int indexOf(int ch) returns index position for the given char value
2 int indexOf(int ch, int fromIndex) returns index position for the given char value and from index
3 int indexOf(String substring) returns index position for the given substring
4 int indexOf(String substring, int fromIndex) returns index position for the given substring and from index

Java String intern()

The java string intern() method returns the interned string. It returns the canonical representation of string.

It can be used to return string from memory, if it is created by new keyword. It creates exact copy of heap string object in string constant pool.

Java String intern() method example

    public class InternExample{  
    public static void main(String args[]){  
    String s1=new String("hello");  
    String s2="hello";  
    String s3=s1.intern();//returns string from pool, now it will be same as s2  
    System.out.println(s1==s2);//false because reference variables are pointing to different instance  
    System.out.println(s2==s3);//true because reference variables are pointing to same instance  
    }}  


false
true

Java String intern() Method Example 2

    public class InternExample2 {  
        public static void main(String[] args) {          
            String s1 = "Javatpoint";  
            String s2 = s1.intern();  
            String s3 = new String("Javatpoint");  
            String s4 = s3.intern();          
            System.out.println(s1==s2); // True  
            System.out.println(s1==s3); // False  
            System.out.println(s1==s4); // True       
            System.out.println(s2==s3); // False  
            System.out.println(s2==s4); // True        
            System.out.println(s3==s4); // False          
        }  
    }  


true
false
true
false
true
false

Java String isEmpty()

The java string isEmpty() method checks if this string is empty or not. It returns true, if length of string is 0 otherwise false. In other words, true is returned if string is empty otherwise it returns false.

The isEmpty() method of String class is included in java string since JDK 1.6.

Java String isEmpty() method example

    public class IsEmptyExample{  
    public static void main(String args[]){  
    String s1="";  
    String s2="javatpoint";  
      
    System.out.println(s1.isEmpty());  
    System.out.println(s2.isEmpty());  
    }}  


true
false

Java String isEmpty() Method Example 2

    public class IsEmptyExample2 {  
        public static void main(String[] args) {  
            String s1="";    
            String s2="Javatpoint";             
            // Either length is zero or isEmpty is true  
            if(s1.length()==0 || s1.isEmpty())  
                System.out.println("String s1 is empty");  
            else System.out.println("s1");        
            if(s2.length()==0 || s2.isEmpty())  
                System.out.println("String s2 is empty");  
            else System.out.println(s2);  
        }  
    }  

String s1 is empty
Javatpoint

Java String join()

The java string join() method returns a string joined with given delimiter. In string join method, delimiter is copied for each elements.

In case of null element, "null" is added. The join() method is included in java string since JDK 1.8. There are two types of join() methods in java string.

Java String join() method example

    public class StringJoinExample{  
    public static void main(String args[]){  
    String joinString1=String.join("-","welcome","to","javatpoint");  
    System.out.println(joinString1);  
    }}  


welcome-to-javatpoint

Java String join() Method Example 2

    public class StringJoinExample2 {  
        public static void main(String[] args) {          
            String date = String.join("/","25","06","2018");    
            System.out.print(date);    
            String time = String.join(":", "12","10","10");  
            System.out.println(" "+time);  
        }  
    }  

25/06/2018 12:10:10

Java String lastIndexOf()

The java string lastIndexOf() method returns last index of the given character value or substring. If it is not found, it returns -1. The index counter starts from zero.

There are 4 types of lastIndexOf method in java. The signature of lastIndexOf methods are given below:

No. Method Description
1 int lastIndexOf(int ch) returns last index position for the given char value
2 int lastIndexOf(int ch, int fromIndex) returns last index position for the given char value and from index
3 int lastIndexOf(String substring) returns last index position for the given substring
4 int lastIndexOf(String substring, int fromIndex) returns last index position for the given substring and from index

Java String lastIndexOf() method example

    public class LastIndexOfExample{  
    public static void main(String args[]){  
    String s1="this is index of example";//there are 2 's' characters in this sentence  
    int index1=s1.lastIndexOf('s');//returns last index of 's' char value  
    System.out.println(index1);//6  
    }}  

Output:

6

Java String lastIndexOf(String substring) Method Example

    public class LastIndexOfExample3 {  
        public static void main(String[] args) {           
            String str = "This is last index of example";  
            int index = str.lastIndexOf("of");  
            System.out.println(index);        
        }  
    }  


Output:

19

Java String lastIndexOf(String substring, int fromIndex) Method Example

    public class LastIndexOfExample4 {  
        public static void main(String[] args) {           
            String str = "This is last index of example";  
            int index = str.lastIndexOf("of", 25);  
            System.out.println(index);  
            index = str.lastIndexOf("of", 10);  
            System.out.println(index); // -1, if not found        
        }  
    }  


Output:

19
-1

Java String length()

The java string length() method length of the string. It returns count of total number of characters. The length of java string is same as the unicode code units of the string.

Java String length() method example

    public class LengthExample{  
    public static void main(String args[]){  
    String s1="javatpoint";  
    String s2="python";  
    System.out.println("string length is: "+s1.length());//10 is the length of javatpoint string  
    System.out.println("string length is: "+s2.length());//6 is the length of python string  
    }}  


string length is: 10
string length is: 6

Java String length() Method Example 2

    public class LengthExample2 {  
        public static void main(String[] args) {  
            String str = "Javatpoint";  
            if(str.length()>0) {  
                System.out.println("String is not empty and length is: "+str.length());  
            }  
            str = "";  
            if(str.length()==0) {  
                System.out.println("String is empty now: "+str.length());  
            }  
        }  
    }  

String is not empty and length is: 10
String is empty now: 0

Java String replace()

The java string replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence. Since JDK 1.5, a new replace() method is introduced, allowing you to replace a sequence of char values.

Java String replace(char old, char new) method example

    public class ReplaceExample1{  
    public static void main(String args[]){  
    String s1="javatpoint is a very good website";  
    String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'  
    System.out.println(replaceString);  
    }}  

jevetpoint is e very good website

Java String replace(CharSequence target, CharSequence replacement) method example

    public class ReplaceExample2{  
    public static void main(String args[]){  
    String s1="my name is khan my name is java";  
    String replaceString=s1.replace("is","was");//replaces all occurrences of "is" to "was"  
    System.out.println(replaceString);  
    }}  

my name was khan my name was java

Java String replace() Method Example 3

    public class ReplaceExample3 {  
        public static void main(String[] args) {  
            String str = "oooooo-hhhh-oooooo";  
            String rs = str.replace("h","s"); // Replace 'h' with 's'  
            System.out.println(rs);  
            rs = rs.replace("s","h"); // Replace 's' with 'h'  
            System.out.println(rs);  
        }  
    }  

oooooo-ssss-oooooo
oooooo-hhhh-oooooo

Java String replaceAll()

The java string replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.

Java String replaceAll() example: replace character

    public class ReplaceAllExample1{  
    public static void main(String args[]){  
    String s1="javatpoint is a very good website";  
    String replaceString=s1.replaceAll("a","e");//replaces all occurrences of "a" to "e"  
    System.out.println(replaceString);  
    }}  

jevetpoint is e very good website

Java String replaceAll() example: replace word

    public class ReplaceAllExample2{  
    public static void main(String args[]){  
    String s1="My name is Khan. My name is Bob. My name is Sonoo.";  
    String replaceString=s1.replaceAll("is","was");//replaces all occurrences of "is" to "was"  
    System.out.println(replaceString);  
    }}  


My name was Khan. My name was Bob. My name was Sonoo.

Java String replaceAll() example: remove white spaces

    public class ReplaceAllExample3{  
    public static void main(String args[]){  
    String s1="My name is Khan. My name is Bob. My name is Sonoo.";  
    String replaceString=s1.replaceAll("\\s","");  
    System.out.println(replaceString);  
    }}  


MynameisKhan.MynameisBob.MynameisSonoo.

Java String split()

The java string split() method splits this string against given regular expression and returns a char array.

Java String split() method example

    public class SplitExample{  
    public static void main(String args[]){  
    String s1="java string split method by javatpoint";  
    String[] words=s1.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);  
    }  
    }}  


java
string
split
method
by
javatpoint

Java String split() method with regex and length example

    public class SplitExample2{  
    public static void main(String args[]){  
    String s1="welcome to split world";  
    System.out.println("returning words:");  
    for(String w:s1.split("\\s",0)){  
    System.out.println(w);  
    }  
    System.out.println("returning words:");  
    for(String w:s1.split("\\s",1)){  
    System.out.println(w);  
    }  
    System.out.println("returning words:");  
    for(String w:s1.split("\\s",2)){  
    System.out.println(w);  
    }  
      
    }}  

Test it Now

returning words:
welcome 
to 
split 
world
returning words:
welcome to split world
returning words:
welcome 
to split world

Java String split() method with regex and length example 2

Here, we are passing split limit as a second argument to this function. This limits the number of splitted strings.

    public class SplitExample3 {  
        public static void main(String[] args) {  
            String str = "Javatpointtt";  
            System.out.println("Returning words:");  
            String[] arr = str.split("t", 0);  
            for (String w : arr) {  
                System.out.println(w);  
            }  
            System.out.println("Split array length: "+arr.length);  
        }  
    }  

Returning words:
Java
poin
Split array length: 2

Java String startsWith()

The java string startsWith() method checks if this string starts with given prefix. It returns true if this string starts with given prefix else returns false.

Java String startsWith() method example

    public class StartsWithExample{  
    public static void main(String args[]){  
    String s1="java string split method by javatpoint";  
    System.out.println(s1.startsWith("ja"));  
    System.out.println(s1.startsWith("java string"));  
    }}  


Output:

true
true

Java String startsWith(String prefix, int offset) Method Example

This is overloaded method of startWith() method which is used to pass one extra argument (offset) to the function. This method works from the passed offset. Let's see an example.

    public class StartsWithExample2 {  
        public static void main(String[] args) {  
            String str = "Javatpoint";  
            System.out.println(str.startsWith("J")); // True  
            System.out.println(str.startsWith("a")); // False  
            System.out.println(str.startsWith("a",1)); // True  
        }  
    }  

Output:

true
false
true

Java String substring()

The java string substring() method returns a part of the string.

We pass begin index and end index number position in the java substring method where start index is inclusive and end index is exclusive. In other words, start index starts from 0 whereas end index starts from 1.

There are two types of substring methods in java string.

Java String substring() method example

 

   public class SubstringExample{  
    public static void main(String args[]){  
    String s1="javatpoint";  
    System.out.println(s1.substring(2,4));//returns va  
    System.out.println(s1.substring(2));//returns vatpoint  
    }}  


va
vatpoint

Java String substring() Method Example 2

    public class SubstringExample2 {  
        public static void main(String[] args) {  
            String s1="Javatpoint";    
            String substr = s1.substring(0); // Starts with 0 and goes to end  
            System.out.println(substr);  
            String substr2 = s1.substring(5,10); // Starts from 5 and goes to 10  
            System.out.println(substr2);    
            String substr3 = s1.substring(5,15); // Returns Exception  
        }  
    }  

Javatpoint
point
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 5, end 15, length 10

Java String toCharArray()

The java string toCharArray() method converts this string into character array. It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string.

Java String toCharArray() method example

    public class StringToCharArrayExample{  
    public static void main(String args[]){  
    String s1="hello";  
    char[] ch=s1.toCharArray();  
    for(int i=0;i<ch.length;i++){  
    System.out.print(ch[i]);  
    }  
    }}  


Output:

hello

Java String toCharArray() Method Example 2

Let's see one more example of char array. It is useful method which returns char array from the string without writing any custom code.

    public class StringToCharArrayExample2 {  
        public static void main(String[] args) {  
            String s1 = "Welcome to Javatpoint";  
            char[] ch = s1.toCharArray();  
            int len = ch.length;  
            System.out.println("Char Array length: " + len);  
            System.out.println("Char Array elements: ");  
            for (int i = 0; i < len; i++) {  
                System.out.println(ch[i]);  
            }  
        }  
    }  

Output:

Char Array length: 21
Char Array elements: 
W
e
l
c
o
m
e
 
t
o
 
J
a
v
a
t
p
o
i
n
t

Java String toLowerCase()

The java string toLowerCase() method returns the string in lowercase letter. In other words, it converts all characters of the string into lower case letter.

The toLowerCase() method works same as toLowerCase(Locale.getDefault()) method. It internally uses the default locale.

Java String toLowerCase() method example

    public class StringLowerExample{  
    public static void main(String args[]){  
    String s1="JAVATPOINT HELLO stRIng";  
    String s1lower=s1.toLowerCase();  
    System.out.println(s1lower);  
    }}  


Output:

javatpoint hello string

Java String toLowerCase(Locale locale) Method Example 2

This method allows us to pass locale too for the various langauges. Let's see an example below where we are getting string in english and turkish both.

    import java.util.Locale;  
    public class StringLowerExample2 {  
        public static void main(String[] args) {  
            String s = "JAVATPOINT HELLO stRIng";    
            String eng = s.toLowerCase(Locale.ENGLISH);  
            System.out.println(eng);  
            String turkish = s.toLowerCase(Locale.forLanguageTag("tr")); // It shows i without dot  
            System.out.println(turkish);  
        }  
    }  

Output:

javatpoint hello string
javatpo?nt hello str?ng

Java String toUpperCase()

The java string toUpperCase() method returns the string in uppercase letter. In other words, it converts all characters of the string into upper case letter.

The toUpperCase() method works same as toUpperCase(Locale.getDefault()) method. It internally uses the default locale.

Java String toUpperCase() method example

    public class StringUpperExample{  
    public static void main(String args[]){  
    String s1="hello string";  
    String s1upper=s1.toUpperCase();  
    System.out.println(s1upper);  
    }}  


Output:

HELLO STRING

Java String toUpperCase(Locale locale) Method Example 2

    import java.util.Locale;  
    public class StringUpperExample2 {  
        public static void main(String[] args) {  
            String s = "hello string";    
            String turkish = s.toUpperCase(Locale.forLanguageTag("tr"));  
            String english = s.toUpperCase(Locale.forLanguageTag("en"));  
            System.out.println(turkish);//will print I with dot on upper side  
            System.out.println(english);  
        }  
    }  

Output:

HELLO STR?NG
HELLO STRING

Java String trim()

The java string trim() method eliminates leading and trailing spaces. The unicode value of space character is '\u0020'. The trim() method in java string checks this unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.

    public class StringTrimExample{  
    public static void main(String args[]){  
    String s1="  hello string   ";  
    System.out.println(s1+"javatpoint");//without trim()  
    System.out.println(s1.trim()+"javatpoint");//with trim()  
    }}  


  hello string   javatpoint
hello stringjavatpoint   

Java String trim() Method Example 2

This example demonstrate the use of trim method. This method removes all the trailing spaces so the length of string also reduces. Let's see an example.

    public class StringTrimExample {  
        public static void main(String[] args) {  
            String s1 ="  hello java string   ";  
            System.out.println(s1.length());  
            System.out.println(s1); //Without trim()  
            String tr = s1.trim();  
            System.out.println(tr.length());  
            System.out.println(tr); //With trim()  
        }  
    }  

22
  hello java string   
17
hello java string

Java String valueOf()

The java string valueOf() method converts different types of values into string. By the help of string valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float to string, double to string, object to string and char array to string.

Java String valueOf() method example

    public class StringValueOfExample{  
    public static void main(String args[]){  
    int value=30;  
    String s1=String.valueOf(value);  
    System.out.println(s1+10);//concatenating string with 10  
    }}  

Test it Now

Output:

3010

Java String valueOf(boolean bol) Method Example

    public class StringValueOfExample2 {  
        public static void main(String[] args) {          
            // Boolean to String  
            boolean bol = true;    
            boolean bol2 = false;    
            String s1 = String.valueOf(bol);    
            String s2 = String.valueOf(bol2);  
            System.out.println(s1);  
            System.out.println(s2);  
        }  
    }  

Test it Now

Output:

true
false

Java String valueOf(char ch) Method Example

This is a char version of overloaded valueOf() method. It takes char value and returns a string. Let's see an example.

    public class StringValueOfExample3 {  
        public static void main(String[] args) {  
            // char to String         
            char ch1 = 'A';    
            char ch2 = 'B';  
            String s1 = String.valueOf(ch1);    
            String s2 = String.valueOf(ch2);  
            System.out.println(s1);  
            System.out.println(s2);  
        }  
    }  

Test it Now

Output:

A
B

Java String valueOf(float f) and valueOf(double d)

This is a float version of overloaded valueOf() method. It takes float value and returns a string. Let's see an example.

    public class StringValueOfExample4 {  
        public static void main(String[] args) {  
            // Float and Double to String  
            float f  = 10.05f;    
            double d = 10.02;  
            String s1 = String.valueOf(f);    
            String s2 = String.valueOf(d);  
            System.out.println(s1);  
            System.out.println(s2);  
        }  
    }  


Output:

10.05
10.02

Java String valueOf() Complete Examples

    public class StringValueOfExample5 {  
        public static void main(String[] args) {  
            boolean b1=true;  
            byte b2=11;    
            short sh = 12;  
            int i = 13;  
            long l = 14L;  
            float f = 15.5f;  
            double d = 16.5d;  
            char chr[]={'j','a','v','a'};  
            StringValueOfExample5 obj=new StringValueOfExample5();  
            String s1 = String.valueOf(b1);    
            String s2 = String.valueOf(b2);    
            String s3 = String.valueOf(sh);    
            String s4 = String.valueOf(i);    
            String s5 = String.valueOf(l);    
            String s6 = String.valueOf(f);    
            String s7 = String.valueOf(d);    
            String s8 = String.valueOf(chr);    
            String s9 = String.valueOf(obj);    
            System.out.println(s1);  
            System.out.println(s2);  
            System.out.println(s3);  
            System.out.println(s4);  
            System.out.println(s5);  
            System.out.println(s6);  
            System.out.println(s7);  
            System.out.println(s8);  
            System.out.println(s9);  
        }  
    }  

Test it Now

Output:

true
11
12
13
14
15.5
16.5
java
StringValueOfExample5@2a139a55

Immutable String in Java

In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.

Once string object is created its data or state can't be changed but a new string object is created.

Let's try to understand the immutability concept by the example given below:

    class Testimmutablestring{  
     public static void main(String args[]){  
       String s="Sachin";  
       s.concat(" Tendulkar");//concat() method appends the string at the end  
       System.out.println(s);//will print Sachin because strings are immutable objects  
     }  
    }  


Output:Sachin

Java String indexOf() method example

    public class IndexOfExample{  
    public static void main(String args[]){  
    String s1="this is index of example";  
    //passing substring  
    int index1=s1.indexOf("is");//returns the index of is substring  
    int index2=s1.indexOf("index");//returns the index of index substring  
    System.out.println(index1+"  "+index2);//2 8  
      
    //passing substring with from index  
    int index3=s1.indexOf("is",4);//returns the index of is substring after 4th index  
    System.out.println(index3);//5 i.e. the index of another is  
      
    //passing char value  
    int index4=s1.indexOf('s');//returns the index of s char value  
    System.out.println(index4);//3  
    }}  

Test it Now

2  8
5
3

Java String indexOf(String substring) Method Example

    public class IndexOfExample2 {  
        public static void main(String[] args) {  
            String s1 = "This is indexOf method";         
            // Passing Substring    
            int index = s1.indexOf("method"); //Returns the index of this substring  
            System.out.println("index of substring "+index);          
        }  
      
    }  

Test it Now

index of substring 16

Java String indexOf(String substring, int fromIndex) Method Example

    public class IndexOfExample3 {  
        public static void main(String[] args) {      
            String s1 = "This is indexOf method";         
            // Passing substring and index  
            int index = s1.indexOf("method", 10); //Returns the index of this substring  
            System.out.println("index of substring "+index);  
            index = s1.indexOf("method", 20); // It returns -1 if substring does not found  
            System.out.println("index of substring "+index);          
        }  
    }  

Test it Now

index of substring 16
index of substring -1

Java String indexOf(int char, int fromIndex) Method Example

    public class IndexOfExample4 {  
        public static void main(String[] args) {          
            String s1 = "This is indexOf method";         
            // Passing char and index from  
            int index = s1.indexOf('e', 12); //Returns the index of this char  
            System.out.println("index of char "+index);       
        }  
    }  

Test it Now

index of char 17

Java String intern() method example

    public class InternExample{  
    public static void main(String args[]){  
    String s1=new String("hello");  
    String s2="hello";  
    String s3=s1.intern();//returns string from pool, now it will be same as s2  
    System.out.println(s1==s2);//false because reference variables are pointing to different instance  
    System.out.println(s2==s3);//true because reference variables are pointing to same instance  
    }}  

Test it Now

false
true

Java String intern() Method Example 2

    public class InternExample2 {  
        public static void main(String[] args) {          
            String s1 = "Javatpoint";  
            String s2 = s1.intern();  
            String s3 = new String("Javatpoint");  
            String s4 = s3.intern();          
            System.out.println(s1==s2); // True  
            System.out.println(s1==s3); // False  
            System.out.println(s1==s4); // True       
            System.out.println(s2==s3); // False  
            System.out.println(s2==s4); // True        
            System.out.println(s3==s4); // False          
        }  
    }  

Test it Now

true
false
true
false
true
false

Now it can be understood by the diagram given below. Here Sachin is not changed but a new object is created with sachintendulkar. That is why string is known as immutable.

As you can see in the above figure that two objects are created but s reference variable still refers to "Sachin" not to "Sachin Tendulkar".

But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar" object.For example:

    class Testimmutablestring1{  
     public static void main(String args[]){  
       String s="Sachin";  
       s=s.concat(" Tendulkar");  
       System.out.println(s);  
     }  
    }  

Output:Sachin Tendulkar

In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not modified.

Why string objects are immutable in java?

Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

Java String compare

We can compare string in java on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc.

There are three ways to compare string in java:

  • By equals() method
  • By = = operator
  • By compareTo() method

1) String compare by equals() method

The String equals() method compares the original content of the string. It compares values of string for equality. String class provides two methods:

public boolean equals(Object another) compares this string to the specified object. public boolean equalsIgnoreCase(String another) compares this String to another string, ignoring case.

    class Teststringcomparison1{  
     public static void main(String args[]){  
       String s1="Sachin";  
       String s2="Sachin";  
       String s3=new String("Sachin");  
       String s4="Saurav";  
       System.out.println(s1.equals(s2));//true  
       System.out.println(s1.equals(s3));//true  
       System.out.println(s1.equals(s4));//false  
     }  
    }  


Output:true
       true
       false
	   
	   
	   
	       class Teststringcomparison2{  
     public static void main(String args[]){  
       String s1="Sachin";  
       String s2="SACHIN";  
      
       System.out.println(s1.equals(s2));//false  
       System.out.println(s1.equalsIgnoreCase(s2));//true  
     }  
    }  

Test it Now

Output:

false
true


2) String compare by == operator

The = = operator compares references not values.

    class Teststringcomparison3{  
     public static void main(String args[]){  
       String s1="Sachin";  
       String s2="Sachin";  
       String s3=new String("Sachin");  
       System.out.println(s1==s2);//true (because both refer to same instance)  
       System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)  
     }  
    }  


Output:true
       false

3) String compare by compareTo() method

The String compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string.

Suppose s1 and s2 are two string variables. If:

  • s1 == s2 :0
  • s1 > s2 :positive value
  • s1 < s2 :negative value
    class Teststringcomparison4{  
     public static void main(String args[]){  
       String s1="Sachin";  
       String s2="Sachin";  
       String s3="Ratan";  
       System.out.println(s1.compareTo(s2));//0  
       System.out.println(s1.compareTo(s3));//1(because s1>s3)  
       System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )  
     }  
    }  

Test it Now

Output:0
       1
       -1

String Concatenation in Java

In java, string concatenation forms a new string that is the combination of multiple strings. There are two ways to concat string in java:

  • By + (string concatenation) operator
  • By concat() method

1) String Concatenation by + (string concatenation) operator

Java string concatenation operator (+) is used to add strings. For Example:

    class TestStringConcatenation1{  
     public static void main(String args[]){  
       String s="Sachin"+" Tendulkar";  
       System.out.println(s);//Sachin Tendulkar  
     }  
    }  

Output:Sachin Tendulkar



    String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();  

In java, String concatenation is implemented through the StringBuilder (or StringBuffer) class and its append method. String concatenation operator produces a new string by appending the second operand onto the end of the first operand. The string concatenation operator can concat not only string but primitive values also. For Example:

    class TestStringConcatenation2{  
     public static void main(String args[]){  
       String s=50+30+"Sachin"+40+40;  
       System.out.println(s);//80Sachin4040  
     }  
    }  


80Sachin4040

Note: After a string literal, all the + will be treated as string concatenation operator.

2) String Concatenation by concat() method

The String concat() method concatenates the specified string to the end of current string. Syntax:

    public String concat(String another)  

Let's see the example of String concat() method.

    class TestStringConcatenation3{  
     public static void main(String args[]){  
       String s1="Sachin ";  
       String s2="Tendulkar";  
       String s3=s1.concat(s2);  
       System.out.println(s3);//Sachin Tendulkar  
      }  
    }  
	
Sachin Tendulkar

Substring in Java

A part of string is called substring. In other words, substring is a subset of another string. In case of substring startIndex is inclusive and endIndex is exclusive.

Note: Index starts from 0.

You can get substring from the given string object by one of the two methods:

  • public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified startIndex (inclusive).
  • public String substring(int startIndex, int endIndex): This method returns new String object containing the substring of the given string from specified startIndex to endIndex.

In case of string:

  • startIndex: inclusive
  • endIndex: exclusive

Let's understand the startIndex and endIndex by the code given below.

    String s="hello";  
    System.out.println(s.substring(0,2));//he  

In the above substring, 0 points to h but 2 points to e (because end index is exclusive).

Example of java substring

    public class TestSubstring{  
     public static void main(String args[]){  
       String s="SachinTendulkar";  
       System.out.println(s.substring(6));//Tendulkar  
       System.out.println(s.substring(0,6));//Sachin  
     }  
    }  


Tendulkar
Sachin

Java String class methods

The java.lang.String class provides a lot of methods to work on string. By the help of these methods, we can perform operations on string such as trimming, concatenating, converting, comparing, replacing strings etc.

Java String is a powerful concept because everything is treated as a string if you submit any form in window based, web based or mobile application.

Let's see the important methods of String class.

Java String toUpperCase() and toLowerCase() method

The java string toUpperCase() method converts this string into uppercase letter and string toLowerCase() method into lowercase letter.

    String s="Sachin";  
    System.out.println(s.toUpperCase());//SACHIN  
    System.out.println(s.toLowerCase());//sachin  
    System.out.println(s);//Sachin(no change in original)  



SACHIN
sachin
Sachin


Java String trim() method

The string trim() method eliminates white spaces before and after string.

 
   String s="  Sachin  ";  
    System.out.println(s);//  Sachin    
    System.out.println(s.trim());//Sachin  



  Sachin  
Sachin

Java String startsWith() and endsWith() method

    String s="Sachin";  
     System.out.println(s.startsWith("Sa"));//true  
     System.out.println(s.endsWith("n"));//true  



true
true

Java String charAt() method

The string charAt() method returns a character at specified index.

    String s="Sachin";  
    System.out.println(s.charAt(0));//S  
    System.out.println(s.charAt(3));//h  


S
h

Java String intern() method

A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    String s=new String("Sachin");  
    String s2=s.intern();  
    System.out.println(s2);//Sachin  


Sachin

Java String valueOf() method

The string valueOf() method coverts given type such as int, long, float, double, boolean, char and char array into string.

    int a=10;  
    String s=String.valueOf(a);  
    System.out.println(s+10);  

Output:
1010

Java String replace() method

The string replace() method replaces all occurrence of first sequence of character with second sequence of character.

    String s1="Java is a programming language. Java is a platform. Java is an Island.";    
    String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "Kava"    
    System.out.println(replaceString);    

Output:

Kava is a programming language. Kava is a platform. Kava is an Island.

Java StringBuffer class

Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in an order.

Important Constructors of StringBuffer class

Constructor Description
StringBuffer() creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str) creates a string buffer with the specified string
StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length

Important methods of StringBuffer class

Modifier and Type Method Description
public synchronized StringBuffer append(String s) is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.
public synchronized StringBuffer insert(int offset, String s) is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
public synchronized StringBuffer replace(int startIndex, int endIndex, String str) is used to replace the string from specified startIndex and endIndex.
public synchronized StringBuffer delete(int startIndex, int endIndex) is used to delete the string from specified startIndex and endIndex.
public synchronized StringBuffer reverse() is used to reverse the string.
public int capacity() is used to return the current capacity.
public void ensureCapacity(int minimumCapacity) is used to ensure the capacity at least equal to the given minimum.
public char charAt(int index) is used to return the character at the specified position.
public int length() is used to return the length of the string i.e. total number of characters.
public String substring(int beginIndex) is used to return the substring from the specified beginIndex.
public String substring(int beginIndex, int endIndex) is used to return the substring from the specified beginIndex and endIndex.

What is mutable string

A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string.

1) StringBuffer append() method

The append() method concatenates the given argument with this string.

    class StringBufferExample{  
    public static void main(String args[]){  
    StringBuffer sb=new StringBuffer("Hello ");  
    sb.append("Java");//now original string is changed  
    System.out.println(sb);//prints Hello Java  
    }  
    }  

2) StringBuffer insert() method

The insert() method inserts the given string with this string at the given position.

    class StringBufferExample2{  
    public static void main(String args[]){  
    StringBuffer sb=new StringBuffer("Hello ");  
    sb.insert(1,"Java");//now original string is changed  
    System.out.println(sb);//prints HJavaello  
    }  
    }  

3) StringBuffer replace() method

The replace() method replaces the given string from the specified beginIndex and endIndex.

    class StringBufferExample3{  
    public static void main(String args[]){  
    StringBuffer sb=new StringBuffer("Hello");  
    sb.replace(1,3,"Java");  
    System.out.println(sb);//prints HJavalo  
    }  
    }  

4) StringBuffer delete() method

The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.

    class StringBufferExample4{  
    public static void main(String args[]){  
    StringBuffer sb=new StringBuffer("Hello");  
    sb.delete(1,3);  
    System.out.println(sb);//prints Hlo  
    }  
    }  

5) StringBuffer reverse() method

The reverse() method of StringBuilder class reverses the current string.

    class StringBufferExample5{  
    public static void main(String args[]){  
    StringBuffer sb=new StringBuffer("Hello");  
    sb.reverse();  
    System.out.println(sb);//prints olleH  
    }  
    }  

6) StringBuffer capacity() method

The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

    class StringBufferExample6{  
    public static void main(String args[]){  
    StringBuffer sb=new StringBuffer();  
    System.out.println(sb.capacity());//default 16  
    sb.append("Hello");  
    System.out.println(sb.capacity());//now 16  
    sb.append("java is my favourite language");  
    System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
    }  
    }  

7) StringBuffer ensureCapacity() method

The ensureCapacity() method of StringBuffer class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

    class StringBufferExample7{  
    public static void main(String args[]){  
    StringBuffer sb=new StringBuffer();  
    System.out.println(sb.capacity());//default 16  
    sb.append("Hello");  
    System.out.println(sb.capacity());//now 16  
    sb.append("java is my favourite language");  
    System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
    sb.ensureCapacity(10);//now no change  
    System.out.println(sb.capacity());//now 34  
    sb.ensureCapacity(50);//now (34*2)+2  
    System.out.println(sb.capacity());//now 70  
    }  
    }  

Java StringBuilder class

Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.

Important Constructors of StringBuilder class

Constructor Description
StringBuilder() creates an empty string Builder with the initial capacity of 16.
StringBuilder(String str) creates a string Builder with the specified string.
StringBuilder(int length) creates an empty string Builder with the specified capacity as length.

Important methods of StringBuilder class

Method Description
public StringBuilder append(String s) is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc
public StringBuilder insert(int offset, String s) is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
public StringBuilder replace(int startIndex, int endIndex, String str) is used to replace the string from specified startIndex and endIndex.
public StringBuilder delete(int startIndex, int endIndex) is used to delete the string from specified startIndex and endIndex.
public StringBuilder reverse() is used to reverse the string.
public int capacity() is used to return the current capacity.
public void ensureCapacity(int minimumCapacity) is used to ensure the capacity at least equal to the given minimum.
public char charAt(int index) is used to return the character at the specified position.
public int length() is used to return the length of the string i.e. total number of characters.
public String substring(int beginIndex) is used to return the substring from the specified beginIndex.
public String substring(int beginIndex, int endIndex) is used to return the substring from the specified beginIndex and endIndex.

Java StringBuilder Examples

Let's see the examples of different methods of StringBuilder class.

1) StringBuilder append() method

The StringBuilder append() method concatenates the given argument with this string.

    class StringBuilderExample{  
    public static void main(String args[]){  
    StringBuilder sb=new StringBuilder("Hello ");  
    sb.append("Java");//now original string is changed  
    System.out.println(sb);//prints Hello Java  
    }  
    }  

2) StringBuilder insert() method

The StringBuilder insert() method inserts the given string with this string at the given position.

    class StringBuilderExample2{  
    public static void main(String args[]){  
    StringBuilder sb=new StringBuilder("Hello ");  
    sb.insert(1,"Java");//now original string is changed  
    System.out.println(sb);//prints HJavaello  
    }  
    }  

3) StringBuilder replace() method

The StringBuilder replace() method replaces the given string from the specified beginIndex and endIndex.

    class StringBuilderExample3{  
    public static void main(String args[]){  
    StringBuilder sb=new StringBuilder("Hello");  
    sb.replace(1,3,"Java");  
    System.out.println(sb);//prints HJavalo  
    }  
    }  

4) StringBuilder delete() method

The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.

    class StringBuilderExample4{  
    public static void main(String args[]){  
    StringBuilder sb=new StringBuilder("Hello");  
    sb.delete(1,3);  
    System.out.println(sb);//prints Hlo  
    }  
    }  

5) StringBuilder reverse() method

The reverse() method of StringBuilder class reverses the current string.

    class StringBuilderExample5{  
    public static void main(String args[]){  
    StringBuilder sb=new StringBuilder("Hello");  
    sb.reverse();  
    System.out.println(sb);//prints olleH  
    }  
    }  

6) StringBuilder capacity() method

The capacity() method of StringBuilder class returns the current capacity of the Builder. The default capacity of the Builder is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

    class StringBuilderExample6{  
    public static void main(String args[]){  
    StringBuilder sb=new StringBuilder();  
    System.out.println(sb.capacity());//default 16  
    sb.append("Hello");  
    System.out.println(sb.capacity());//now 16  
    sb.append("java is my favourite language");  
    System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
    }  
    }  

7) StringBuilder ensureCapacity() method

The ensureCapacity() method of StringBuilder class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

    class StringBuilderExample7{  
    public static void main(String args[]){  
    StringBuilder sb=new StringBuilder();  
    System.out.println(sb.capacity());//default 16  
    sb.append("Hello");  
    System.out.println(sb.capacity());//now 16  
    sb.append("java is my favourite language");  
    System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
    sb.ensureCapacity(10);//now no change  
    System.out.println(sb.capacity());//now 34  
    sb.ensureCapacity(50);//now (34*2)+2  
    System.out.println(sb.capacity());//now 70  
    }  
    }  

Difference between String and StringBuffer

There are many differences between String and StringBuffer. A list of differences between String and StringBuffer are given below:

No. String StringBuffer
1 String class is immutable. StringBuffer class is mutable.
2 String is slow and consumes more memory when you concat too many strings because every time it creates new instance. StringBuffer is fast and consumes less memory when you cancat strings.
3 String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method. StringBuffer class doesn't override the equals() method of Object class.

Performance Test of String and StringBuffer

    public class ConcatTest{  
        public static String concatWithString()    {  
            String t = "Java";  
            for (int i=0; i<10000; i++){  
                t = t + "Tpoint";  
            }  
            return t;  
        }  
        public static String concatWithStringBuffer(){  
            StringBuffer sb = new StringBuffer("Java");  
            for (int i=0; i<10000; i++){  
                sb.append("Tpoint");  
            }  
            return sb.toString();  
        }  
        public static void main(String[] args){  
            long startTime = System.currentTimeMillis();  
            concatWithString();  
            System.out.println("Time taken by Concating with String: "+(System.currentTimeMillis()-startTime)+"ms");  
            startTime = System.currentTimeMillis();  
            concatWithStringBuffer();  
            System.out.println("Time taken by Concating with  StringBuffer: "+(System.currentTimeMillis()-startTime)+"ms");  
        }  
    }  

Time taken by Concating with String: 578ms
Time taken by Concating with  StringBuffer: 0ms

String and StringBuffer HashCode Test

As you can see in the program given below, String returns new hashcode value when you concat string but StringBuffer returns same.

    public class InstanceTest{  
        public static void main(String args[]){  
            System.out.println("Hashcode test of String:");  
            String str="java";  
            System.out.println(str.hashCode());  
            str=str+"tpoint";  
            System.out.println(str.hashCode());  
       
            System.out.println("Hashcode test of StringBuffer:");  
            StringBuffer sb=new StringBuffer("java");  
            System.out.println(sb.hashCode());  
            sb.append("tpoint");  
            System.out.println(sb.hashCode());  
        }  
    }  

Hashcode test of String:
3254818
229541438
Hashcode test of StringBuffer:
118352462
118352462

Difference between StringBuffer and StringBuilder

Java provides three classes to represent a sequence of characters: String, StringBuffer, and StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder classes are mutable. There are many differences between StringBuffer and StringBuilder. The StringBuilder class is introduced since JDK 1.5

A list of differences between StringBuffer and StringBuilder are given below:

No. StringBuffer StringBuilder
1 StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously. StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
2 StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.

StringBuffer Example

    //Java Program to demonstrate the use of StringBuffer class.  
    public class BufferTest{  
        public static void main(String[] args){  
            StringBuffer buffer=new StringBuffer("hello");  
            buffer.append("java");  
            System.out.println(buffer);  
        }  
    }  

hellojava

StringBuilder Example

    //Java Program to demonstrate the use of StringBuilder class.  
    public class BuilderTest{  
        public static void main(String[] args){  
            StringBuilder builder=new StringBuilder("hello");  
            builder.append("java");  
            System.out.println(builder);  
        }  
    }  

hellojava

Performance Test of StringBuffer and StringBuilder

Let's see the code to check the performance of StringBuffer and StringBuilder classes.

    //Java Program to demonstrate the performance of StringBuffer and StringBuilder classes.  
    public class ConcatTest{  
        public static void main(String[] args){  
            long startTime = System.currentTimeMillis();  
            StringBuffer sb = new StringBuffer("Java");  
            for (int i=0; i<10000; i++){  
                sb.append("Tpoint");  
            }  
            System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");  
            startTime = System.currentTimeMillis();  
            StringBuilder sb2 = new StringBuilder("Java");  
            for (int i=0; i<10000; i++){  
                sb2.append("Tpoint");  
            }  
            System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");  
        }  
    }  

Time taken by StringBuffer: 16ms
Time taken by StringBuilder: 0ms

How to create Immutable class?

There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes and String class is immutable. We can also create immutable class by creating final class that have final data members as the example given below:

Example to create Immutable class

In this example, we have created a final class named Employee. It have one final datamember, a parameterized constructor and getter method.

    public final class Employee{  
    final String pancardNumber;  
      
    public Employee(String pancardNumber){  
    this.pancardNumber=pancardNumber;  
    }  
      
    public String getPancardNumber(){  
    return pancardNumber;  
    }  
      
    }  

The above class is immutable because:

  • The instance variable of the class is final i.e. we cannot change the value of it after creating an object
  • The class is final so we cannot create the subclass.
  • There is no setter methods i.e. we have no option to change the value of the instance variable.

These points makes this class as immutable.

Java toString() method

If you want to represent any object as a string, toString() method comes into existence.

The toString() method returns the string representation of the object.

If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.

Advantage of Java toString() method

By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.

Understanding problem without toString() method

Let's see the simple code that prints reference.

    class Student{  
     int rollno;  
     String name;  
     String city;  
      
     Student(int rollno, String name, String city){  
     this.rollno=rollno;  
     this.name=name;  
     this.city=city;  
     }  
      
     public static void main(String args[]){  
       Student s1=new Student(101,"Raj","lucknow");  
       Student s2=new Student(102,"Vijay","ghaziabad");  
         
       System.out.println(s1);//compiler writes here s1.toString()  
       System.out.println(s2);//compiler writes here s2.toString()  
     }  
    }  

Output:Student@1fee6fc
       Student@1eed786

As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects but I want to print the values of these objects. Since java compiler internally calls toString() method, overriding this method will return the specified values. Let's understand it with the example given below:

Example of Java toString() method

Now let's see the real example of toString() method.

    class Student{  
     int rollno;  
     String name;  
     String city;  
      
     Student(int rollno, String name, String city){  
     this.rollno=rollno;  
     this.name=name;  
     this.city=city;  
     }  
       
     public String toString(){//overriding the toString() method  
      return rollno+" "+name+" "+city;  
     }  
     public static void main(String args[]){  
       Student s1=new Student(101,"Raj","lucknow");  
       Student s2=new Student(102,"Vijay","ghaziabad");  
         
       System.out.println(s1);//compiler writes here s1.toString()  
       System.out.println(s2);//compiler writes here s2.toString()  
     }  
    }  

download this example of toString method

Output:101 Raj lucknow
       102 Vijay ghaziabad

StringTokenizer in Java

The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break string.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.

Constructors of StringTokenizer class

There are 3 constructors defined in the StringTokenizer class.

Constructor Description
StringTokenizer(String str) creates StringTokenizer with specified string.
StringTokenizer(String str, String delim) creates StringTokenizer with specified string and delimeter.
StringTokenizer(String str, String delim, boolean returnValue) creates StringTokenizer with specified string, delimeter and returnValue. If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens.

Methods of StringTokenizer class

The 6 useful methods of StringTokenizer class are as follows:

>
Public method Description
boolean hasMoreTokens() checks if there is more tokens available.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
boolean hasMoreElements() same as hasMoreTokens() method.
Object nextElement() same as nextToken() but its return type is Object.
int countTokens() returns the total number of tokens.

Simple example of StringTokenizer class

Let's see the simple example of StringTokenizer class that tokenizes a string "my name is khan" on the basis of whitespace.

    import java.util.StringTokenizer;  
    public class Simple{  
     public static void main(String args[]){  
       StringTokenizer st = new StringTokenizer("my name is khan"," ");  
         while (st.hasMoreTokens()) {  
             System.out.println(st.nextToken());  
         }  
       }  
    }  

Output:my
       name
       is
       khan

Example of nextToken(String delim) method of StringTokenizer class

   
 import java.util.*;  
      
    public class Test {  
       public static void main(String[] args) {  
           StringTokenizer st = new StringTokenizer("my,name,is,khan");  
            
          // printing next token  
          System.out.println("Next token is : " + st.nextToken(","));  
       }      
    }  

Output:Next token is : my

StringTokenizer class is deprecated now. It is recommended to use split() method of String class or regex (Regular Expression).

bONEandALL
Visitor

Total : 9222

Today :7

Today Visit Country :

  • United States