Java Strings


In Java, Strings are one of the most commonly used objects. They are sequences of characters and are handled by the String class in Java's standard library. Strings are immutable in Java, meaning once a String object is created, it cannot be modified. This immutability makes Strings a very efficient and secure way of handling text data.

In this comprehensive guide, we will explore Java Strings in detail, covering various ways to create, manipulate, and perform operations on Strings.

Table of Contents

  1. What is a String in Java?
  2. Creating Strings
  3. String Immutability
  4. String Methods
  5. String Concatenation
  6. String Comparison
  7. String Formatting
  8. StringBuffer and StringBuilder
  9. Common String Operations

What is a String in Java?

A String in Java is a sequence of characters enclosed in double quotes. The String class is part of the java.lang package, and strings in Java are objects, not primitive data types. While primitive types (like int, float) store raw values, Strings store sequences of characters.

String in Java Example:

String greeting = "Hello, World!";

In this example, "Hello, World!" is a String object that contains the characters 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', and the length of the string is 13.


Creating Strings

There are two main ways to create a String in Java:

1. Using String Literals:

String literals are created by directly assigning a string value inside double quotes. When you use string literals, Java checks if the string already exists in the string pool (a special storage location for strings). If it exists, it simply reuses the reference; otherwise, it creates a new string object.

String str1 = "Java Programming";

2. Using the new Keyword:

You can also create a String object using the new keyword, which will always create a new object in memory.

String str2 = new String("Java Programming");

String Immutability

Strings in Java are immutable, meaning once a String object is created, its value cannot be changed. Any operation that modifies a string will actually create a new String object.

Example: String Immutability

String str1 = "Java";
str1 = str1 + " Programming";  // This creates a new string object
System.out.println(str1);  // Output: Java Programming

In the example above, when we concatenate " Programming" to "Java", the original str1 is not modified. Instead, a new String object is created, and str1 is now pointing to that new object.


String Methods

The String class in Java provides numerous built-in methods that allow you to manipulate and analyze strings. Some commonly used string methods are:

Common String Methods:

  • length(): Returns the number of characters in the string.

    String str = "Java";
    int length = str.length();  // Returns 4
    
  • charAt(int index): Returns the character at the specified index.

    String str = "Java";
    char ch = str.charAt(2);  // Returns 'v'
    
  • substring(int beginIndex, int endIndex): Returns a substring from the given indices.

    String str = "Java Programming";
    String subStr = str.substring(5, 16);  // Returns "Programming"
    
  • toUpperCase() and toLowerCase(): Converts the string to uppercase or lowercase.

    String str = "Java";
    String upperStr = str.toUpperCase();  // Returns "JAVA"
    String lowerStr = str.toLowerCase();  // Returns "java"
    
  • trim(): Removes leading and trailing whitespace from the string.

    String str = "   Java   ";
    String trimmedStr = str.trim();  // Returns "Java"
    
  • replace(char oldChar, char newChar): Replaces all occurrences of a character.

    String str = "Java Programming";
    String replacedStr = str.replace('a', 'o');  // Returns "Jovo Progromming"
    

String Concatenation

In Java, strings can be concatenated using the + operator or the concat() method. However, using + for concatenation in loops or large strings may be inefficient due to the creation of multiple temporary string objects.

Example: Concatenating Strings

String str1 = "Hello";
String str2 = "World";
String result = str1 + " " + str2;  // Concatenates "Hello World"
System.out.println(result);

You can also use the concat() method to combine strings:

String result = str1.concat(" ").concat(str2);
System.out.println(result);  // Output: Hello World

However, for large string manipulations, StringBuilder or StringBuffer is preferred due to better performance.


String Comparison

Java provides several methods to compare strings. Since strings are objects, using the == operator compares their references, not the content. To compare the content of strings, use methods like equals() or compareTo().

Example: String Comparison

  • equals(): Compares two strings for equality.

    String str1 = "Java";
    String str2 = "Java";
    boolean isEqual = str1.equals(str2);  // Returns true
    
  • compareTo(): Compares two strings lexicographically (alphabetically).

    String str1 = "Java";
    String str2 = "JavaScript";
    int result = str1.compareTo(str2);  // Returns negative because "Java" is lexicographically less than "JavaScript"
    

String Formatting

Java provides the String.format() method, which allows you to format strings using placeholders.

Example: String Formatting

int age = 25;
String name = "John";
String formattedStr = String.format("My name is %s and I am %d years old.", name, age);
System.out.println(formattedStr);

Output:

My name is John and I am 25 years old.

In this example, %s is a placeholder for a string, and %d is for an integer.


StringBuffer and StringBuilder

While String is immutable, StringBuffer and StringBuilder are mutable alternatives for handling strings. Both classes allow modifications to a string without creating new objects.

  • StringBuffer: This class is thread-safe, which means it can be used safely in multi-threaded environments.
  • StringBuilder: This class is similar to StringBuffer but is not synchronized, making it faster in single-threaded environments.

Example: Using StringBuilder

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

Common String Operations

Here are some additional operations you can perform on strings:

  • contains(CharSequence sequence): Checks if a string contains a specified sequence.

    String str = "Java Programming";
    boolean contains = str.contains("Pro");  // Returns true
    
  • startsWith(String prefix): Checks if a string starts with a specified prefix.

    boolean startsWith = str.startsWith("Java");  // Returns true
    
  • endsWith(String suffix): Checks if a string ends with a specified suffix.

    boolean endsWith = str.endsWith("ming");  // Returns true
    
  • indexOf(String str): Returns the index of the first occurrence of a substring.

    int index = str.indexOf("Pro");  // Returns 5