Monday, 1 September 2025

The Ultimate Comparison: String vs StringBuffer vs StringBuilder in Java with methods

In Java, there are 3 classes used to create and manipulate strings:

  1. String

  2. StringBuffer

  3. StringBuilder

String
1.It is Non-Premetive Data Type.
2.String Objects are immutable.
     Immutable
                   a)Once created, cannot be changed.
                   b)Any modification creates a new object.
                   for eg: 
                      String s = new String ("Hello");
                      s = s.concat(" World"); // Creates a NEW String object
                      System.out.println(s); // Hello World
     Here, "Hello" is not changed. Instead, a new "Hello World" object is created.

String Storage in Java
Heap Area
  • When you create a String object using the new keyword (e.g., String  s = new String("Hello");
  • It is stored in the Heap Area.Even if the same string already exists in the pool, a new object is created in the heap.

SCP(String Content Pool)/SLP(String Literal Pool)
  • A special memory area inside the Heap that stores String literals.
  • Example: String s = "Hello"
  • The literal "Hello" is stored in the SCP.
  • If the same literal already exists, no new object is created, instead the reference points to the existing one.
String s1 = new String("Hello");
// Creates 2 objects → "Hello" in SCP + one new object in Heap

String s2 = "World";
// Creates 1 object → "World" in SCP

String s3 = new String("Hello");
// Creates 1 new object in Heap (no new SCP object because "Hello" already exists)




Note:
1. In SCP, Garbage Collection is generally not applicable because 
   String literals are internally managed by JVM for reusability.
2. A new String literal is not created inside SCP if it already exists.
   For example, "Hello" will not be created again since the literal 
   already exists in SCP.

== Operator

  • It is used for Reference Comparision/Address Comparision.
  • Checks if two references point to the same object in memory.
For eg:

two variables refer to different objects,then == will return false
 String s1=new String("Radhe");
 String s2=new String("Radhe");
System.out.println(s1 == s2); // false → s2 is in Heap, not SCP.

 Same object with different variable // true
 String s3=("Radhe");
 String s4=("Shyam");
System.out.println(s1 == s2); // true → same reference in SCP.

.equals() Method
  • It is the method of Object class
  • But In String it is used for Content Comparision.
  • But In object class it is used for reference comparision/Address comparision.
String s1 = new String("Radhe");
String s2 = new String("Radhe");
System.out.println(s1.equals(s2)); // true → content same
System.out.println(s1 == s2);      // false → different objects

Commonly Used String Methods in Java

  • Length & Character Access

1.length()Method

         int length() → returns the length of the string.

         char charAt(int index) → returns the character at given index.

        String s = "Hello";

        System.out.println(s.length());   // 5

        System.out.println(s.charAt(1));  // 'e'

2. isEmpty()Method

    String name="Radhe";

    System.out.println(name.isEmpty()); //false

   String name="";

    System.out.println(name.isEmpty()); //true

  • Comparison

3. equals()Method

    Compares the content of given 2 strings.

    It returns boolean type.

   String s1="Radhe";

   String s2="Radhe"

     System.out.println(s1.equals(s2)); //true

   String s1="Radhe";

   String s2="radhe"

     System.out.println(s1.equals(s2)); //false

4. equalsIgnoreCase()Method

    Avoid upperCase & lowerCase.

   String s1="Radhe";

   String s2="radhe"

     System.out.println(s1.equalsIgnoreCase(s2)); //true

5. CompareTo()Method

        String s1 = "Apple";

        String s2 = "apple";                              System.out.println(s1.compareTo(s2)); // false

6.CompareToIgnoreCase()Method

        Avoid upperCase & lowerCase.

        String s1 = "Apple";

        String s2 = "apple";

       System.out.println(s1.compareTo(s2)); // true

  •  Substring & Modification

7.      substring(int beginIndex)  

        String str = "HelloWorld";

        System.out.println(str.substring(5)); // Output: World 

8.     substring(int beginIndex, int endIndex) 

      String str = "HelloWorld";

      System.out.println(str.substring(0, 5)); // Output: Hello

9.    concat(String str)

        String s1 = "Hello";

        String s2 = "World";

 System.out.println(s1.concat(s2)); // Output: HelloWorld

10.  replace(char oldChar, char newChar)

     String str = "banana";

     System.out.println(str.replace('a', 'o')); // Output: bonono

11. replaceAll(String regex, String replacement)

     String str = "Java123Programming456"

     System.out.println(str.replaceAll("[0-9]", "")); 

          // Output: JavaProgramming

  •  Splitting & Joining

12. String join(CharSequence delimiter, CharSequence... elements)

      String joined = String.join("-", "apple", "banana", "orange");

        System.out.println(joined);// apple-banana-orange;

13. String[] split(String regex)

  • breaks a string into parts using regex.

         String str = "apple,banana,orange";

         // Split by comma

        String[] fruits = str.split(",");

        for (String fruit : fruits) {

            System.out.println(fruit); // apple banana orange

            }

  • Value Conversion

14. String valueOf(int/char/double/boolean etc.) → converts to string. 

         int s1=10;

         int s2=20;

      String s3= String.valueOf(s1);

      String s4= String.valueOf(s2);

     System.out.println(s1+s2); //1020;

15. char[] toCharArray() -> Converts a string into a character array.

     String s1 ="Radha";

     char[] s2=s1.tocharArray();

     System.out.println(s2); // 'Radha'

  •  Searching

16. boolean contains(CharSequence s)

     String s1="Radhe";

     System.out.println(s1.contains("dha")); //true

17. boolean startsWith(String prefix)

       String s1="Radhe";

     System.out.println(s1.contains("R")); //true  

18. boolean endsWith(String suffix)

      String s1="Radhe";

     System.out.println(s1.contains("e")); //true 

19. indexOf(String s) --> Return integer value.

                 01234 

      String s1="Radhe";

      System.out.println(s1.indexOf('d')); // 2

20. lastIndexOf(String s) --> Return integer value.

     String s1="Radhe";

     System.out.println(s1.lastIndexOf('a')); // 4 

StringBuffer

  • StringBuffer objects are mutable → their content can be changed without creating a new object.
  • StringBuffer are synchronized → meaning it is thread-safe.
  • Because of synchronization, it is slower than StringBuilder

       StringBuffer sb = new StringBuffer("Hello");

            sb.append(" World");

            System.out.println(sb); // Hello World

Commonly Used StringBuffer Methods

1. append() --> Adds text at the end.

    StringBuffer sb = new StringBuffer("Hello");

    sb.append(" World");

    System.out.println(sb); // Hello World

2. insert(int offset, String str)-->Inserts text at a given position.

      StringBuffer sb = new StringBuffer("Hello World");

      sb.insert(6, "Java ");

      System.out.println(sb); // Hello Java World

3. replace(int start, int end, String str) --> Replaces characters                     from start to end-1 with given string.

       StringBuffer sb = new StringBuffer("Hello World");

       sb.replace(6, 11, "Java");

       System.out.println(sb); // Hello Java

4. delete(int start, int end) --> Deletes characters between start and               end-1.

        StringBuffer sb = new StringBuffer("Hello Java World");

        sb.delete(5, 10);

        System.out.println(sb); // Hello World

5. reverse() --> Shows current capacity (default 16 + length of                          string).

     StringBuffer sb = new StringBuffer("Hello");

     System.out.println(sb.capacity()); // 21 (16 + 5)

6. length() -->Returns current length (number of characters).
     StringBuffer sb = new StringBuffer("Hello");
     System.out.println(sb.length()); // 5

StringBuilder(1.5v)
  •  StringBuffer, StringBuilder objects are mutable → you can modify       them without creating a new object.
  • It doesn’t have synchronization overhead.
  • StringBuilder is not thread-safe.
        StringBuilder sb = new StringBuilder("Hello");
        sb.append(" World");
        System.out.println(sb); // Hello World

                                          

🔑 Difference Between String, StringBuffer, and StringBuilder in Java

 

quotes

Make it easy for yourself.Get organized and live in the moment.





  
                   


No comments:

Post a Comment

Mastering Exception Handling in Java: From Basics to Best Practices

Quote "If you can change your mind, you can change your life." Exception Handling   An exception is an unwanted or unexpected eve...