Strings in Java

Strings (java.lang.String) are pieces of text stored in your program. Strings are not a primitive data type in Java, however, they are very common in Java programs.

In Java, Strings are immutable, meaning that they cannot be changed. (Click here for a more thorough explanation of immutability.)

Comparing Strings

In order to compare Strings for equality, you should use the String object’s equals or equalsIgnoreCase methods.

For example, the following snippet will determine if the two instances of String are equal on all characters:

String firstString = "Test123";
String secondString = "Test" + 123;

if (firstString.equals(secondString)) {
// Both Strings have the same content.
}

Note that equalsIgnoreCase does not let you specify a Locale. For instance, if you compare the two words “Taki” and “TAKI” in English they are equal; however, in Turkish, they are different (in Turkish, the lowercase I is ı). For
cases like this, converting both strings to lowercase (or uppercase) with Locale and then comparing with equals is the solution.

String firstString = "Taki";
String secondString = "TAKI";

System.out.println(firstString.equalsIgnoreCase(secondString));                            //prints true

Locale locale = Locale.forLanguageTag("tr-TR");

System.out.println(firstString.toLowerCase(locale).equals(
      secondString.toLowerCase(locale))); //prints false

Do not use the == operator to compare Strings

Unless you can guarantee that all strings have been interned (see below), you should not use the == or != operators to compare Strings. These operators actually test references, and since multiple String objects can
represent the same String, this is liable to give the wrong answer.

Instead, use the String.equals(Object) method, which will compare the String objects based on their values. For a detailed explanation, please refer to Pitfall: using == to compare strings.

Comparing Strings in a switch statement

Version ≥ Java SE 7
As of Java 1.7, it is possible to compare a String variable to literals in a switch statement. Make sure that the String is not null, otherwise, it will always throw a NullPointerException. Values are compared using String. equals, i.e. case sensitive.

Related Article: String pool and heap storage

String stringToSwitch = "A";
switch (stringToSwitch) {
    case "a":
       System.out.println("a");
       break;
    case "A":
       System.out.println("A"); //the code goes here
       break;
    case "B":
       System.out.println("B");
       break;
    default:
       break;
}

Comparing Strings with constant values

When comparing a String to a constant value, you can put the constant value on the left side of equals to ensure
that you won’t get a NullPointerException if the other String is null.

"baz".equals(foo)

While foo.equals(“baz”) will throw a NullPointerException if foo is null, “baz”.equals(foo) will evaluate to false.

Version ≥ Java SE 7

A more readable alternative is to use Objects.equals(), which does a null check on both parameters: Objects.equals(foo, “baz”).

(Note: It is debatable as to whether it is better to avoid NullPointerExceptions in general, or let them happen and then fix the root cause; see here and here. Certainly, calling the avoidance strategy “best practice” is not justifiable.)

String orderings

The String class implements Comparable with the String.compareTo method (as described at the start of this example). This makes the natural ordering of String objects case-sensitive order. The String class provide a
Comparator constant called CASE_INSENSITIVE_ORDER suitable for case-insensitive sorting.

Comparing with interned Strings

The Java Language Specification (JLS 3.10.6) states the following:

“Moreover, a string literal always refers to the same instance of class String. This is because string literals or, more generally, strings that are the values of constant expressions – are interned so as to share unique instances, using the method String.intern.”

String orderings

The String class implements Comparable with the String.compareTo method (as described at the start of this example). This makes the natural ordering of String objects case-sensitive order. The String class provide a
Comparator constant called CASE_INSENSITIVE_ORDER suitable for case-insensitive sorting.

Comparing with interned Strings

The Java Language Specification (JLS 3.10.6) states the following:

“Moreover, a string literal always refers to the same instance of class String. This is because string literals or, more generally, strings that are the values of constant expressions – are interned so as to share unique instances, using the method String.intern.”

This means it is safe to compare references to two string literals using ==. Moreover, the same is true for references to String objects that have been produced using the String.intern() method.

For example:

String strObj = new String("Hello!");
String str = "Hello!";

// The two string references point two strings that are equal
if (strObj.equals(str)) {
System.out.println("The strings are equal");
}

// The two string references do not point to the same object
if (strObj != str) {
System.out.println("The strings are not the same object");
}

// If we intern a string that is equal to a given literal, the result is
// a string that has the same reference as the literal.
String internedStr = strObj.intern();

if (internedStr == str) {
System.out.println("The interned string and the literal are the same object");
}

Behind the scenes, the interning mechanism maintains a hash table that contains all interned strings that are still reachable. When you call intern() on a String, the method looks up the object in the hash table:

  • If the string is found, then that value is returned as the interned string.
  • Otherwise, a copy of the string is added to the hash table and that string is returned as the interned string.

It is possible to use interning to allow strings to be compared using ==. However, there are significant problems with doing this; see Pitfall – Interning strings so that you can use == is a bad idea for details. It is not recommended in most cases.

Changing the case of characters within a String

The String type provides two methods for converting strings between upper case and lower case:

  • toUpperCase to convert all characters to upper case
  • toLowerCase to convert all characters to lower case

These methods both return the converted strings as new String instances: the original String objects are not modified because String is immutable in Java. See this for more on immutability: Immutability of Strings in Java

String string = "This is a Random String";
String upper = string.toUpperCase();
String lower = string.toLowerCase();
System.out.println(string);  // prints "This is a Random String"
System.out.println(lower);   // prints "this is a random string"
System.out.println(upper);   // prints "THIS IS A RANDOM STRING"

Non-alphabetic characters, such as digits and punctuation marks, are unaffected by these methods. Note that these methods may also incorrectly deal with certain Unicode characters under certain conditions.

Note: These methods are locale-sensitive, and may produce unexpected results if used on strings that are intended to be interpreted independently of the locale. Examples are programming language identifiers, protocol keys, and HTML tags.

For instance, “TITLE”.toLowerCase() in a Turkish locale returns “tıtle”, where ı (\u0131) is the LATIN SMALL LETTER DOTLESS I character. To obtain correct results for locale insensitive strings, pass Locale.ROOT as a
the parameter to the corresponding case converting method (e.g. toLowerCase(Locale.ROOT) or toUpperCase(Locale.ROOT)).

Although using Locale.ENGLISH is also correct for most cases, the language invariant way is Locale.ROOT.

Changing case of a specific character within an ASCII string:

To change the case of a specific character of an ASCII string following algorithm can be used:
Steps:

  1. Declare a string.
  2. Input the string.
  3. Convert the string into a character array.
  4. Input the character that is to be searched.
  5. Search for the character into the character array.
  6. If found, check if the character is lowercase or uppercase.
    If Uppercase, add 32 to the ASCII code of the character.
    If Lowercase, subtract 32 from the ASCII code of the character.
  7. Change the original character from the Character array.
  8. Convert the character array back into the string. Voila, the Case of the character is changed.

An example of the code for the algorithm is:

Scanner scanner = new Scanner(System.in);
System.out.println("Enter the String");
String s = scanner.next();
char[] a = s.toCharArray();
System.out.println("Enter the character you are looking for");
System.out.println(s);
String c = scanner.next();
char d = c.charAt(0);

for (int i = 0; i <= s.length(); i++) { 
    if (a[i] == d) { 
    if (d >= 'a' && d <= 'z') { 
        d -= 32; 
        } else if (d >= 'A' && d <= 'Z') {
          d += 32;
        }
        a[i] = d;
         break;
     }
}
s = String.valueOf(a);
System.out.println(s);

Leave a Comment