πŸŽ‰ Special Offer !    Code: GET300OFF    Flat β‚Ή300 OFF on every Java Course
Grab Deal πŸš€

String Class in Java  


Introduction
  • The String class in Java represents a sequence of characters enclosed in double quotes (" ").
  • String class is present in java.lang package.
  • Syntax :-
    package java.lang;
                                        
    public final class String extends Object implements Serializable, Comparable, CharSequence
    {
        // Fields
        // Constructors
        // Methods
    }
  • Unlike primitive types, String is an object.
    int rollno = 101;         // Primitive data type
    String name = "Deepak";   // Reference type (object) 
  • Strings are used to represent textual data in programming.
    • Commonly used for displaying messages, storing names, addresses and other textual data
Different Ways to Create String Object in Java:
  1. Using String Literal:
    • This is the most common and efficient way way to create strings in Java.
    • In this case, the JVM stores the string object in the String Constant Pool (SCP) for memory efficiency.
    • String s1 = "Hello";  
      String s2 = "Hello";   // s1 and s2 point to the same object in SCP
  2. Using new Keyword:
    • A new String object is created in heap memory, even if the same value already exists in the String Pool.
    • String s3 = new String("Hello");  // stored in heap
Methods of String Class:
  • Below are some common and important methods of String class with examples:
Method Description Example Output
length() Returns the number of characters in the string.
String s = "Java";
System.out.println(s.length());
4
charAt(int index) Returns the character at the specified index (0-based).
String s = "Java";
System.out.println(s.charAt(2));
v
substring(int begin, int end) Returns a substring from begin index (inclusive) to end index (exclusive).
String s = "Programming";
System.out.println(s.substring(0, 6));
Progra
equals(Object obj) Compares two strings for equality (case-sensitive).
String s1 = "Java";
String s2 = "Java";
System.out.println(s1.equals(s2));
true
equalsIgnoreCase(String str) Compares two strings ignoring case.
String s1 = "java";
String s2 = "JAVA";
System.out.println(s1.equalsIgnoreCase(s2));
true
toUpperCase() Converts all characters to uppercase.
String s = "hello";
System.out.println(s.toUpperCase());
HELLO
toLowerCase() Converts all characters to lowercase.
String s = "HELLO";
System.out.println(s.toLowerCase());
hello
trim() Removes leading and trailing spaces.
String s = "  Java  ";
System.out.println(s.trim());
Java
concat(String str) Concatenates (joins) two strings.
String s1 = "Hello";
String s2 = "World";
System.out.println(s1.concat(" "+s2));
Hello World
replace(char old, char new) Replaces all occurrences of a character with another.
String s = "Java";
System.out.println(s.replace('a','o'));
Jovo
contains(CharSequence s) Checks if the string contains a sequence of characters.
String s = "Programming";
System.out.println(s.contains("gram"));
true
compareTo(String another) Compares strings lexicographically (alphabetical order).
String s1 = "Apple";
String s2 = "Banana";
System.out.println(s1.compareTo(s2));
-1 (since "Apple" < "Banana")
intern() Returns the canonical representation of a string from the String Constant Pool (SCP). Helps save memory by avoiding duplicate String objects.
String s1 = new String("Hello");
String s2 = s1.intern();
String s3 = "Hello";

System.out.println(s1 == s2);
System.out.println(s2 == s3);
        
false
true
Properties of String Class:
  1. Immutable
    • String objects are immutable, meaning once a String object is created, its value cannot be changed.
  2. Stored in String Constant Pool (SCP):
    • For memory efficiency, string literals are stored in the String Constant Pool (SCP) and are reused to avoid creating duplicate objects.
  3. Unicode Support:
    • String objects store text as UTF-16 encoded Unicode characters, allowing support for multiple languages and symbols.
  4. Thread-Safe:
    • Since String objects are immutable, they are inherently thread-safe. Multiple threads can safely access the same string without the need for synchronization.

Why String class is final?
  1. Immutability Guarantee:
    • Making the String class final ensures that its methods cannot be overridden, preserving its immutable behavior.
  2. Security Reasons:
    • String is widely used for sensitive data like usernames, passwords, file paths, database URLs, and network connections. If it were not final, someone could subclass it and compromise security.
  3. Thread-Safety:
    • Since String objects are immutable and cannot be changed, they are automatically thread-safe. Declaring String as final ensures no subclass can alter this behavior.
  4. Performance Optimization:
    • String Constant Pool (SCP) depends on String being immutable. If String were mutable, reusing objects in the pool would not be safe, and performance benefits would be lost.
  5. Hashcode Caching:
    • The String class caches its hashcode after the first calculation. This is only possible because strings are immutable and final ensures no subclass can break this mechanism.
  6. Consistency Across JVM:
    • Since String is heavily used in class loading, reflection, collections, etc., making it final ensures consistent and predictable behavior everywhere.

CharSequence Interface:
  • CharSequence is a read-only interface that represents a sequence of characters.
  • String, StringBuilder, StringBuffer and CharBuffer implements the CharSequence Interface.
  • It provides methods to access characters and subsequences without modifying the original content.
  • Some commonly used methods are:
    • length() β†’ Returns the number of characters.
    • charAt(int index) β†’ Returns the character at the specified index.
    • subSequence(int start, int end) β†’ Returns a subsequence of the character sequence.
    • toString() β†’ Converts the sequence into a String object.
  • Example:
    CharSequence seq = "Deepak";
    System.out.println(seq.length());           // 6
    System.out.println(seq.charAt(0));          // D
    System.out.println(seq.subSequence(0, 4));  // Deep
    System.out.println(seq.toString());         // Deepak
  • Note: CharSequence allows uniform access to different character sequence implementations without modifying them.