DEV Community

Mohamed Ajmal
Mohamed Ajmal

Posted on

String in Java.

String is an object that represents a sequence of characters. Unlike some other languages where strings are primitive types or arrays of characters, Java treats every string as an instance of the java.lang.String class.

Creation Methods:

You can create strings in two primary ways:

String Literal: Most common and memory-efficient.String s = "Hello";

Using new Keyword: Creates a new object in heap memory even if the same string already exists in the pool.
String s = new String("Hello");

Key Concepts:

Immutability: Once created, a String object cannot be changed. It actually create a Brand new String objects.

Memory Management: Java uses a special memory area called the String Constant Pool (SCP) to store string literals. If you create multiple strings with the same literal value, they all point to the same object in the pool to save memory.

Essential String Methods:

The Java String Class provides dozens of built-in methods for manipulation:

  1. length() - Returns the number of characters in the string.

  2. charAt - (int index)Returns the character at the specified index.

  3. equals(String another)Compares the actual content of two strings.

  4. substring(int start, int end)Extracts a portion of the string.

  5. toUpperCase() / toLowerCase()Converts the string case.

  6. trim()Removes leading and trailing whitespace.

Mutable Alternatives:

If your program needs to modify strings frequently (like in a loop), use these mutable classes to avoid creating excessive temporary objects.

StringBuilder: Best for single-threaded environments because it is faster (not synchronized).

StringBuffer: Used for multi-threaded environments as it is thread-safe (synchronized).

Top comments (0)