Java Strings


In Java, a String is a sequence of characters and is one of the most commonly used data types. Strings are objects in Java, representing text and are part of the java.lang package. Java provides a wide range of methods to manipulate and work with strings, making them versatile and powerful.

Key Concepts of Strings in Java

  1. Immutability: Strings in Java are immutable, meaning once a string is created, it cannot be changed. Any operation that alters a string actually creates a new string object in memory rather than modifying the original string.

  2. String Pool: Java optimizes memory usage by storing string literals in a special memory area called the String Pool. When a string is created using double quotes (" "), Java first checks if the same literal is already in the pool. If it exists, it returns a reference to the existing object; otherwise, it adds the new string to the pool.

  3. String Class: Strings in Java are instances of the String class, which provides various methods for string manipulation, comparison, and conversion.

Creating Strings in Java

There are two ways to create strings in Java:

  1. String Literal: Using double quotes, which automatically places the string in the String Pool.
String str1 = "Hello";
  1. Using the new Keyword: This creates a new string object in the heap, even if the same string already exists in the pool.
String str2 = new String("Hello");

Common String Methods

Here are some commonly used methods of the String class:

  1. Length: Returns the length (number of characters) of the string.

    String str = "Hello"; int length = str.length(); // Output: 5
  2. Concatenation: Combines two strings using the concat method or the + operator.

    String str1 = "Hello"; String str2 = " World"; String result = str1.concat(str2); // Output: "Hello World" String result2 = str1 + str2; // Output: "Hello World"
  3. charAt(): Returns the character at a specified index.

    String str = "Hello"; char ch = str.charAt(1); // Output: 'e'
  4. substring(): Extracts a substring from the string.

    String str = "Hello World"; String subStr = str.substring(6); // Output: "World" String subStr2 = str.substring(0, 5); // Output: "Hello"
  5. toUpperCase() and toLowerCase(): Converts the string to uppercase or lowercase.

    String str = "Hello"; String upper = str.toUpperCase(); // Output: "HELLO" String lower = str.toLowerCase(); // Output: "hello"
  6. equals(): Compares two strings for equality. Use equals() to compare strings, not ==, which checks for reference equality.

    String str1 = "Hello"; String str2 = "Hello"; boolean isEqual = str1.equals(str2); // Output: true
  7. replace(): Replaces occurrences of a character or substring with another character or substring.

    String str = "Hello"; String replacedStr = str.replace('e', 'a'); // Output: "Hallo"
  8. contains(): Checks if the string contains a particular sequence of characters.

    String str = "Hello World"; boolean contains = str.contains("World"); // Output: true
  9. split(): Splits the string based on a specified delimiter and returns an array of substrings.

    String str = "Apple,Banana,Cherry"; String[] fruits = str.split(","); // Output: ["Apple", "Banana", "Cherry"]

Example Program with String Methods

Here’s a simple program that demonstrates a few commonly used string methods:

public class StringExample { public static void main(String[] args) { String str = "Hello World"; // Length of the string System.out.println("Length: " + str.length()); // Extract a substring System.out.println("Substring: " + str.substring(6)); // Convert to uppercase System.out.println("Uppercase: " + str.toUpperCase()); // Check if the string contains "World" System.out.println("Contains 'World': " + str.contains("World")); // Replace 'l' with 'x' System.out.println("Replaced: " + str.replace('l', 'x')); // Splitting the string by space String[] words = str.split(" "); for (String word : words) { System.out.println(word); } } }

Output

Length: 11 Substring: World Uppercase: HELLO WORLD Contains 'World': true Replaced: Hexxo Worxd Hello World

String Immutability in Detail

As mentioned earlier, strings in Java are immutable. This means once a string object is created, its internal state cannot be changed. Any method that seems to modify a string (such as concat, replace, etc.) actually creates a new string object with the modified value.

String str = "Hello"; str.concat(" World"); // This does not modify `str` System.out.println(str); // Output: "Hello"

To modify the original string, you would need to assign the result to a new variable or the same variable:

str = str.concat(" World"); // Now `str` holds "Hello World" System.out.println(str); // Output: "Hello World"

String vs StringBuilder vs StringBuffer

  • String: Immutable and stored in the String Pool. Any modification creates a new string.
  • StringBuilder: Mutable, meaning it can be modified without creating new objects. It is not thread-safe but offers better performance when used in a single-threaded environment.
  • StringBuffer: Mutable like StringBuilder, but it is thread-safe, meaning it can be used in a multithreaded environment. However, it is slower than StringBuilder.

Example of StringBuilder:

StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); System.out.println(sb.toString()); // Output: "Hello World"

Summary

  • Java String is a sequence of characters, stored as an object.
  • Strings are immutable, meaning their content cannot be changed once created.
  • The String class provides various methods for string manipulation, such as length(), substring(), concat(), replace(), etc.
  • Use StringBuilder or StringBuffer if you need to modify strings frequently, as they are mutable.

Understanding how to effectively work with strings is essential for mastering Java programming, as they are used extensively in various applications.