Java Strings

Strings are a fundamental concept in Java, as in many other programming languages. A String in Java is an object that represents a sequence of characters. The java.lang.String class is used to create and manipulate strings.

Creating Strings

There are several ways to create a String object in Java:

  1. String Literal: This is the most common method to create a String object. When you create a string using string literal, it is stored in the string pool.

    java
    1String greeting = "Hello, World!";
  2. New Keyword: You can also create a String object using the new keyword. This will create a new string object in normal (non-pool) heap memory.

    java
    1String greeting = new String("Hello, World!");
  3. Character Array: You can create a string from an array of characters.

    java
    1char[] helloArray = { 'H', 'e', 'l', 'l', 'o', '!' }; 2String helloString = new String(helloArray); 3System.out.println(helloString);

String Methods

Java provides a number of methods to manipulate strings. Here are some of the most commonly used String methods:

  • length(): Returns the length of the string.
  • charAt(int index): Returns the character at the specified index.
  • substring(int beginIndex, int endIndex): Returns a new string that is a substring of this string.
  • concat(String str): Concatenates the specified string to the end of this string.
  • indexOf(String str): Returns the index within this string of the first occurrence of the specified substring.
  • toLowerCase(): Converts all of the characters in this string to lower case.
  • toUpperCase(): Converts all of the characters in this string to upper case.
  • trim(): Returns a copy of the string, with leading and trailing whitespace omitted.
  • replace(char oldChar, char newChar): Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

Immutability of Strings

In Java, strings are immutable, which means that once a String object is created, it cannot be changed. If you try to alter a String, a new String object is created instead.

java
1String s1 = "Hello"; 2s1.concat(", World!"); // This does not change s1 3System.out.println(s1); // Prints "Hello"

To actually change the string, you would have to assign it back to the variable:

java
1s1 = s1.concat(", World!"); 2System.out.println(s1); // Prints "Hello, World!"

String Comparison

When comparing strings in Java, it is important to use the methods provided by the String class rather than the == operator.

  • equals(Object anObject): Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
  • equalsIgnoreCase(String anotherString): Compares this String to another String, ignoring case considerations.
java
1String s1 = "Hello"; 2String s2 = new String("Hello"); 3 4System.out.println(s1 == s2); // false, because they are different objects in memory 5System.out.println(s1.equals(s2)); // true, because they have the same characters

StringBuilder and StringBuffer

If you need to create a string that changes frequently, it is better to use StringBuilder (non-synchronized, better performance) or StringBuffer (synchronized, thread-safe).

java
1StringBuilder sb = new StringBuilder("Hello"); 2sb.append(", World!"); 3String s = sb.toString(); 4System.out.println(s); // Prints "Hello, World!"

String Formatting

Java also provides the String.format() method to create formatted strings using a format string and arguments.

java
1String name = "John"; 2int age = 30; 3String formattedString = String.format("My name is %s and I am %d years old.", name, age); 4System.out.println(formattedString);