Java Strings: Immutable, String Pool, Methods

String in Java In Java, a String is a powerful and commonly used class that represents a sequence of characters. Despite its apparent simplicity, a String object in Java, such as `String name = "Java";`, is a part of the java.lang package and holds significant importance. Immutable Nature Once created, Strings in Java are immutable, meaning they cannot be altered. Any modifications to a String result in the creation of a new object in memory. For example, `String s1 = "Hello"; s1 = s1 + " World";` generates a new String object. String Pool Java optimizes memory usage by storing String literals in a String Constant Pool. This allows strings with the same value to reference the same object in memory, enhancing performance efficiency. String vs StringBuilder vs StringBuffer - String: Immutable and thread-safe but slower for frequent changes. - StringBuilder: Mutable and faster, but not thread-safe. - StringBuffer: Mutable, thread-safe, but slower compared to StringBuilder. Useful String Methods - s.length(); - s.charAt(2); - s.substring(1,4); - s.equalsIgnoreCase(" JAVA"); - `s.replace('a','e');` Understanding the intricacies of Strings in Java is crucial for writing efficient and memory-optimized Java code.

  • diagram

The intern() method in Java checks whether the string already exists in the String Constant Pool. If it exists, it returns a reference to that pooled string; if it does not exist, it adds the string to the pool and returns the reference to the newly added string. String Str6 str1 Wale String ko point karega == Check In Java, the == operator checks whether two string references point to the same object in memory if yes true otherwise false

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories