String_StringBufferAndBuilder In Java


Points to Note:

·      String is immutable class, which means we cannot modify once it is created.
·      String is class.
·      String is sequence of characters.
·      When we say String is class, which means we can create object of class.
·      There is two ways to create object of String class. (With new operator and without new operator)

E.g. for Immutable String

Example1:
public class Example1 {
           
            public static void main(String[] args) {
                        String s1 = "BhanuTest";
                        System.out.println(s1);
            }
}

Output:
BhanuTest

Example2: In this example when we try to concat the string, original sting will not change.

public class Example1 {
           
            public static void main(String[] args) {
                        String s1 = "BhanuPratap";
                        System.out.println("---Before concat---");
                        System.out.println(s1);
                        s1.concat("Test");
                        System.out.println("---After concat---");
                        System.out.println(s1);
            }
}

Output
---Before concat---
BhanuPratap
---After concat---
BhanuPratap

Important Points
·      We can see that in above example even after concat String is not changing.

·      As We know that concat method will append the string at the end of string

·      When We create string without new operator, then String object will get created in String constant pool.

Let’s understand the string concept in more details.
When we create string object without new operator, object will get created in constant pool area in heap. And when we create other object with same string value without new operator, then second object reference will also point to the same object in constant pool area in heap

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





Know More About Memory in Heap for String object
public class Example1 {
           
            public static void main(String[] args) {
                        String s1 = "Bhanu";              // String literal
                        String s2 = "Bhanu";              // String literal
                        String s3 = s1;                   // same reference
                        String s4 = new String("Bhanu");  // String object
                        String s5 = new String("Bhanu");  // String object
            }

}


In This Example we are changing the reference itself, so in memory first s1 would be pointing to Bhanu, when we change s1 = s1+”Bhanu”. Then s1 will point to “Bhanu Test”
public class Example1 {
           
            public static void main(String[] args) {
                        String s1 = "Bhanu";
                        s1 = s1+"Test";
                        System.out.println(s1);
            }
}


String Methods:

1.        String toLowerCase(Locale locale): It converts the string to lower case string .

public class Example1 {
           
            public static void main(String[] args) {
                        String s1 = "Bhanu";
                        System.out.println(s1.toLowerCase());
            }
}
Output: - bhanu

2.        String toUpperCase(Locale locale): Converts the string to upper case string.

public class Example1 {
           
            public static void main(String[] args) {
                        String s1 = "Bhanu";
                        System.out.println(s1.toUpperCase());
            }
}
Output: - BHANU
3.        String trim(): Returns the substring after omitting leading and trailing white spaces from the original string.

public class Example1 {
           
            public static void main(String[] args) {
                        String s1 = "Bhanu   ";
                        System.out.println(s1.trim());
            }
}
Output: - Bhanu

4.        char[] toCharArray(): Converts the string to a character array.

public class Example1 {
           
            public static void main(String[] args) {
                        String s1 = "Bhanu";
                        char[] ch = s1.toCharArray();                  
            }
}

5.        static String copyValueOf(char[] data): It returns a string that contains the characters of the specified character array.

public class Example1 {
           
            public static void main(String[] args) {
                        char[] ch = {'a','b','c'};
                        System.out.println(String.copyValueOf(ch));
            }
}
Output: -  abc
6.        static String copyValueOf(char[] data, int offset, int count): Same as above method with two extra arguments – initial offset of subarray and length of subarray.

public class Example1 {
           
            public static void main(String[] args) {
                        char[] ch = {'a','b','c','d'};
                        System.out.println(String.copyValueOf(ch,0,3));
            }
}
output: -abc

7.        boolean regionMatches(boolean ignoreCase, int srcoffset, String dest, int destoffset, int len): Another variation of regionMatches method with the extra boolean argument to specify whether the comparison is case sensitive or case insensitive.
8.        boolean startsWith(String prefix, int offset): It checks whether the substring (starting from the specified offset index) is having the specified prefix or not.

public class Example1 {
           
            public static void main(String[] args) {
                        char[] ch = {'a','b','c','d'};
                        String s1="BhanuTest";
                        System.out.println(s1.startsWith("Bh",0));
            }
}

Output: - True
9.        boolean startsWith(String prefix): It tests whether the string is having specified prefix, if yes then it returns true else false.

public class Example1 {
           
            public static void main(String[] args) {
                        char[] ch = {'a','b','c','d'};
                        String s1="BhanuTest";
                        System.out.println(s1.startsWith("Bh”));
            }
}

10.      boolean endsWith(String suffix): Checks whether the string ends with the specified suffix.

public class Example1 {
           
            public static void main(String[] args) {
                        char[] ch = {'a','b','c','d'};
                        String s1="BhanuTest";
                        System.out.println(s1.endsWith("st"));
            }
}
Output: - true
11.      int hashCode(): It returns the hash code of the string.

public class Example1 {
           
            public static void main(String[] args) {
                        char[] ch = {'a','b','c','d'};
                        String s1="BhanuTest";
                        System.out.println(s1.hashCode());
            }
}
Output: - 984143732

12.      char charAt(int index): It returns the character at the specified index. Specified index value should be between 0 to length() -1 both inclusive. It throws IndexOutOfBoundsException if index<0||>= length of String.

public class Example1 {
           
            public static void main(String[] args) {
                        //char[] ch = {'a','b','c','d'};
                        String s1="BhanuTest";
                        System.out.println(s1.charAt(3));
            }
}
Output: -n
13.      int codePointAt(int index):It is similar to the charAt method however it returns the Unicode code point value of specified index rather than the character itself.
14.      void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin): It copies the characters of src array to the dest array. Only the specified range is being copied(srcBegin to srcEnd) to the dest subarray(starting fromdestBegin).
15.      boolean equals(Object obj): Compares the string with the specified string and returns true if both matches else false.

public class Example1 {
           
            public static void main(String[] args) {
                        //char[] ch = {'a','b','c','d'};
                        String s1="BhanuTest";
                        String s2="BhanuTest";
                        String s3="BhanuTest";
                       
                        System.out.println(s1.equals(s2));
                        System.out.println(s1.equals(s3));
                        System.out.println(s2.equals(s3));
            }
}
Output: -
true
true
true

16.      boolean contentEquals(StringBuffer sb): It compares the string to the specified string buffer.

public class Example1 {
           
            public static void main(String[] args) {
                        //char[] ch = {'a','b','c','d'};
                        String s1="BhanuTest";
                        System.out.println(s1.contentEquals("BhanuTest"));
            }
}
Output: - true
17.      boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t consider the case while comparing strings. It does a case insensitive comparison.

public class Example1 {
           
            public static void main(String[] args) {
                        //char[] ch = {'a','b','c','d'};
                        String s1="BhanuTest";
                        System.out.println(s1.equalsIgnoreCase("BhanuTest"));
            }
}
Output: - true

18.      int compareTo(String string): This method compares the two.

public class Example1 {
           
            public static void main(String[] args) {
                        //char[] ch = {'a','b','c','d'};
                        String s1="BhanuTest";
                        System.out.println(s1.compareTo("BhanuTest"));
            }
}
Output: - 0
19.      int compareToIgnoreCase(String string): Same as CompareTo method however it ignores the case during comparison.

public class Example1 {
           
            public static void main(String[] args) {
                        //char[] ch = {'a','b','c','d'};
                        String s1="BhanuTest";
                        System.out.println(s1.compareToIgnoreCase("bhanutest"));
            }
}
Output: -0
20.      boolean regionMatches(int srcoffset, String dest, int destoffset, int len): It compares the substring of input to the substring of specified string.
21.      int indexOf(int ch): Returns the index of first occurrence of the specified character ch in the string.
22.      int indexOf(int ch, int fromIndex): Same as indexOf method however it starts searching in the string from the specified fromIndex.
23.      int lastIndexOf(int ch): It returns the last occurrence of the character ch in the string.
24.      int lastIndexOf(int ch, int fromIndex): Same as lastIndexOf(int ch) method, it starts search from fromIndex.
25.      int indexOf(String str): This method returns the index of first occurrence of specified substring str.
26.      int lastindexOf(String str): Returns the index of last occurrence of string str.
27.      String substring(int beginIndex): It returns the substring of the string. The substring starts with the character at the specified index.


public class Example1 {
           
            public static void main(String[] args) {
                        //char[] ch = {'a','b','c','d'};
                        String s1="BhanuTest";
                        System.out.println(s1.substring(3));
            }
}

OutPut:- nuTest

28.      String substring(int beginIndex, int endIndex): Returns the substring. The substring starts with character at beginIndex and ends with the character at endIndex.

public class Example1 {
           
            public static void main(String[] args) {
                        //char[] ch = {'a','b','c','d'};
                        String s1="BhanuTest";
                        System.out.println(s1.substring(2,7));
            }
}
Output: - anuTe


29.      String concat(String str): Concatenates the specified string “str” at the end of the string.

public class Example1 {
           
            public static void main(String[] args) {
                        //char[] ch = {'a','b','c','d'};
                        String s1="BhanuTest";
                        s1 = s1.concat("Pratap");
                        System.out.println(s1);
            }
}
Output: - BhanuTestPratap
30.      String replace(char oldChar, char newChar): It returns the new updated string after changing all the occurrences of oldChar with the newChar.
31.      boolean contains(CharSequence s): It checks whether the string contains the specified sequence of char values. If yes then it returns true else false. It throws NullPointerException of ‘s’ is null.
32.      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.
33.      String replaceAll(String regex, String replacement): It replaces all the occurrences of substrings that fits the regular expression regex with the replacement string.
34.      String[] 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.
35.      String[] split(String regex): Same as split(String regex, int limit) method however it does not have any threshold limit.
36.      static String valueOf(data type): This method returns a string representation of specified data type.
37.      byte[] getBytes(String charsetName): It converts the String into sequence of bytes using the specified charset encoding and returns the array of resulted bytes.
38.      byte[] getBytes(): This method is similar to the above method it just uses the default charset encoding for converting the string into sequence of bytes.
39.      int length(): It returns the length of a String.
40.      boolean matches(String regex): It checks whether the String is matching with the specified regular expression regex.


equals and == operator

equals will check for contents
== operator will check for reference

In below example s1==s4 would be false, since s4 object we are creating with new operator, so in memory address would be different

public class Example1 {
           
            public static void main(String[] args) {
                        String s1="BhanuTest";
                        String s2="BhanuTest";
                        String s3="BhanuTest";
                        String s4=new String("BhanuTest");

                        System.out.println(s1.equals(s2));
                        System.out.println(s1.equals(s3));
                        System.out.println(s1.equals(s4));
                        System.out.println(s4.equals(s2));
                        System.out.println("---------------");
                        System.out.println(s1==s2);
                        System.out.println(s1==s3);
                        System.out.println(s1==s4);
            }
}

true
true
true
true
---------------
true
true

false


String Buffer: -

As we know that string is immutable class. To overcome this problem, we have String Buffer class in Java

public class Example3 {
           
            public static void main(String[] args) {
                        StringBuffer sb = new StringBuffer("Bhanu");
                        sb.append("Test");
                        System.out.println(sb);
                       
            }          
}

Output: - BhanuTest

String builder: -


The only difference between string buffer and string builder is, String builder is thread safe. Which means when multiple thread access String build data, data corruption will not happen

public class Example3 {
           
            public static void main(String[] args) {
                        StringBuilder sb = new StringBuilder("Bhanu");
                        sb.append("Test");
                        System.out.println(sb);
                       
            }          
}
 Output: - BhanuTest 

Comments

  1. Good Post! Thank you so much for sharing the nice post, it was so good to read and useful to improve
    Java Training in Electronic City

    ReplyDelete
  2. This is a simple and good way to explain us to the concept of string function. All this string function is very useful for programming languages. Thanks for sharing with us.

    hire python developers in US

    ReplyDelete

Post a Comment

Popular posts from this blog

CollectionFramework-Part-2 In Java

OOPs concepts In Java