Java Tutorial – Java Strings Examples

Java Tutorial – Java Strings Examples

What is String?

The String class is by far the most often used class in Java. Its importance cannot be understated. In this tutorial we will cover many aspects of this all important class. The java.lang.String class stores a sequence of unicode characters internally in a char array. For example, the string “apple” is a sequence of five characters. In Java, Strings may be of any length up to the maximum allowed, which is Integer.MAX_VALUE 2,147,483,647 (231 – 1).

What’s Covered

  1. Creating a Java String
  2. String Literals
  3. Java String Pool
  4. Using the New Keyword
  5. Forcing use of String Pool with New Keyword
  6. String Length
  7. Escape Characters in Strings
  8. Changing String Case
  9. Comparing Strings
  10. Comparing String By Reference
  11. Comparing String By Value
    1. equals()
    2. equals() Output
    3. equalsIgnoreCase()
    4. equalsIgnoreCase() Output
    5. startsWith() and endsWith()
    6. startsWith() and endsWith() Output
    7. Regular Expression using matches()
    8. Regular Expression using matches() Output
  12. Searching Strings using indexOf()
  13. indexOf() Output

Creating a Java String

The String class can be created two different ways. We can create a String using the new keyword just like we would any other Java class. However, more often than not we simply use the String literal method described below.

String Literals

The typical way we create Strings in Java is by assigning a String literal to the String reference variable.

Reference variables are used to refer (store an address) to an object in memory.

String myStr1 = "Java Rocks!!!";
java_string_literal

The above example, creates a String object containing “Java Rocks!!!” and places it in the String Pool in the Java Heap then assigns the address of this object to the myStr1 reference variable.

If we were to create another String object (String myStr2) and assign it the literal “Java Rocks!!!” this object would not be created again and would instead come from the String Pool (discussed below). This will save the JVM some CPU cycles as it would not have to create new String instances. Instead the JVM will assign the address of the previously created String object to the myStr2 reference variable.

String myStr1 = "Java Rocks!!!";
String myStr2 = "Java Rocks!!!";
java_string_literal2

Using the New Keyword

When we use the new keyword, the JVM will create a new instance of String object. In essence, the JVM will create separate objects in the Java Heap and assign the address of these objects to the reference variables.

Forcing use of String Pool with New Keyword

What if you wanted to use the new keyword and wanted to ensure that only one object would be created, when required, otherwise the reference to the object already existing in the String pool would be returned just like it would for String literals. The Java String class contains a method called intern() to be used when creating Strings using the new keyword.

Using the following program we can see very clearly what is happening in the JVM when new objects are created and when they are reused from existing String objects in the String pool.

package com.avaldes.tutorial;

public class JavaStringExample {
 public static void main(String[] args) {
  String myStr1 = "Java Rocks!!!";
  String myStr2 = "Java Rocks!!!";

  String itRocks1 = new String("Java Rocks!!!");
  String itRocks2 = new String("Java Rocks!!!");

  String spRocks = new String("Java Rocks!!!").intern();

  System.out.println("myStr1.......: " + myStr1);
  System.out.println("myStr2.......: " + myStr2);
  
  System.out.println("itRocks1.....: " + itRocks1);
  System.out.println("itRocks2.....: " + itRocks2);
  System.out.println("spRocks......: " + spRocks);
  System.out.println();
  
  /*********************************************
  ** Use the identityHashCode method to
  ** try to get the memory address of the object
  ** in the JVM and convert to Hex Number
  *********************************************/
  System.out.format("myStr1 address...: 0x%08x%n", 
    System.identityHashCode(myStr1));
  System.out.format("myStr2 address...: 0x%08x%n",
    System.identityHashCode(myStr2));
  System.out.format("itRocks1 address.: 0x%08x%n",
    System.identityHashCode(itRocks1));
  System.out.format("itRocks2 address.: 0x%08x%n",
    System.identityHashCode(itRocks2));
  System.out.format("spRocks address..: 0x%08x%n",
    System.identityHashCode(spRocks));
 }
}

Output of JavaStringExample

As you can see from the results below you will notice how the first instantiation of the myStr1 variable creates an object in the Java String pool at address 0x3b05c7e1. Before we continue, let just say the following.

*NOTE: In Java there is no real way to get the exact physical memory location but using the System.identityHashCode is probably the closest we are going to get to a real physical memory address. For the purpose of this post I will refer to it as the memory address.

Having said that, let’s continue our analysis of what is happening in the Java JVM. Our next statement instantiates the variable myStr2 with the literal String “Java Rocks!!!” so the JVM looks to see if we already have that string in the Java String Pool. Since it does it simply returns the memory address of the String object from the String pool, which in this case is 0x3b05c7e1. At this point, both myStr1 and myStr2 reference variables point (refer) to the string object at the same location (0x3b05c7e1). Next, we instantiate the itRocks1 variable using the new keyword with the value of “Java Rocks!!!”. This method will always create a new instance of the String at a new memory location, specifically at 0x7885a30c. Instantiating the itRocks2 variable with new keyword also creates a new instance of the String at a different memory location, specifically at 0x0d93a6a5. Finally, we create our last reference variable spRocks with the new keyword, but this time we add the intern() method. When this method is called, it checks the String pool for the existence of the value, if it finds the object it will return the address which in this case is 0x3b05c7e1.

myStr1.......: Java Rocks!!!
myStr2.......: Java Rocks!!!
itRocks1.....: Java Rocks!!!
itRocks2.....: Java Rocks!!!
spRocks......: Java Rocks!!!

myStr1 address...: 0x3b05c7e1
myStr2 address...: 0x3b05c7e1
itRocks1 address.: 0x7885a30c
itRocks2 address.: 0x0d93a6a5
spRocks address..: 0x3b05c7e1
java_string_literal3

Java String Pool

The Java String Pool is used to store String literals and interned Strings in JVM to improve performance and to minimize space requirements for String constants. The String pool has undergone some important changes in Java 7 primarily in decision to move the String pool from the permanent generation (PermGen) space to heap space. This move was precipitated by the fact that PermGen space was quite limited fixed size area of memory causing numerous issues with the OutOfMemoryError.

java_string_pool

String Length

The String class’ length() method will return the number of characters contained in the String. Internally, Java Strings store the count (number of characters in the String) in a private variable. This count just the length of the char array that String internally uses.

String itRocks1 = new String("Java Rocks!!!");
int length = itRocks1.length();

Changing String Case

From time to time we come across a need to convert the case of a String to either UPPERCASE or LOWERCASE because of some business reason. Luckily for us, Java provides a fairly easy way of accomplishing that case conversion by using the utility methods toUpperCase() and toLowerCase().

Internally, Java does not modify the existing String as it is immutable (more on this later), it instead creates a new String in the appropriate case and returns the new reference to that newly created String object.

String author = "JK Rowling";
String lower = author.toLowerCase();
String upper = author.toUpperCase();

System.out.println("Author.....: " + author);
System.out.println("Lower......: " + lower);
System.out.println("Upper......: " + upper);

Output of String Change Case

Author.....: JK Rowling
Lower......: jk rowling
Upper......: JK ROWLING

Escape Characters in Strings

An escape character is a special character preceded by a backslash (\) which translates into into a different interpretation on subsequent characters in the sequence.

Special Characters

\t tab character
\b backspace character
\n linefeed
\f form feed
\r carriage return
\u Unicode character (\u00XX)
\” double quote
\’ single quote
\\ backslash

Let’s examine how escape characters affect a String in the following print statement. We can put quotes “” around the text Java World! by using the \” escape sequence. Additionally, we can add a linefeed between the title and the author by using the \n.

System.out.println("Welcome to \"Java World!\"\nBy Andrew Ng");

Output of Escape Characters

Welcome to "Java World!"
By Andrew Ng

Comparing Strings

The String class has several methods available to allow us to compare Strings by value. In addition to the methods available in String class, Java allows us to compare Strings by reference. Let’s start by comparing Strings by Reference (memory address).

Comparing String By Reference

We can compare two Strings using the == operator to compare whether or not both String variables are referencing the same physical String location in memory. In other words, using == is incorrect as it checks for reference equality not string value equality.

String myStr1 = "Java Rocks!!!";
String myStr2 = "Java Rocks!!!";

if (myStr1 == myStr2) {
   /* Strings Locations Match */
   ...
} else {
   ...
}

So using the example above, one would expect the two Strings (myStr1 and myStr2) to match and evaluate to true as they both point to the same physical memory location. As mentioned earlier in the “Using the New Keyword” section of this post, creating two String literals will cause the first one to be created in the String Pool and the second statement will simply get a reference from the already created String instance.

However, if would have created the two String variables using the new keyword the outcome would be vastly different. In this case, each variable will point to a different reference location. Now using (myStr1 == myStr2) will evaluate to false because each variable references different instances.

String myStr1 = new String("Java Rocks!!!");
String myStr2 = new String("Java Rocks!!!");

if (myStr1 == myStr2) {
   ...
} else {
   /* Strings Locations DO NOT Match */
   ...
}

Comparing String By Value

In most cases, what the developer really wants to do is compare the Strings by content. That is, compare that the content or value of the String are equal. Luckily for us, the Java String class contains several methods that make comparing Strings a simple task.

equals()

Using the method equals() compares values for equality. This method is case sensitive meaning that String “Christine” in variable name1 does not equate to the String “christine” in variable name2. The equals() method will return true if the values of the two Strings are equal, otherwise it returns false.

package com.avaldes.tutorial;

public class JavaStringEquality {

  public static void main(String[] args) {
    String name1 = "Christine";
    String name2 = "christine";
    String name3 = "Christine";
    String name4 = "CHRISTINE";
		
    System.out.format("Does %s equals %s? %s%n", 
                 name1, name2, name1.equals(name2));
    System.out.format("Does %s equals %s? %s%n", 
                 name1, name3, name1.equals(name3));
    System.out.format("Does %s equals %s? %s%n", 
                 name1, name4, name1.equals(name4));
  }
}

equals() Output

Does Christine equals christine? false
Does Christine equals Christine? true
Does Christine equals CHRISTINE? false

equalsIgnoreCase()

Using the method equalsIgnoreCase() compares values for equality ignoring case altogether. This method is case insensitive meaning that String “Christine” in variable name1 will equate to the String “christine” in variable name2. The equalsIgnoreCase() method will return true if the values of the two Strings are equal even though their case may differ, otherwise it returns false.

package com.avaldes.tutorial;

public class JavaStringEqualsIgnore {
  public static void main(String[] args) {
    String name1 = "Christine";
    String name2 = "christine";
    String name3 = "Christine";
    String name4 = "CHRISTINE";
    String name5 = "Chris";
		
    System.out.format("Does %s equalsIgnoreCase %s? %s%n", 
                name1, name2, name1.equalsIgnoreCase(name2));
    System.out.format("Does %s equalsIgnoreCase %s? %s%n", 
                name1, name3, name1.equalsIgnoreCase(name3));
    System.out.format("Does %s equalsIgnoreCase %s? %s%n", 
                name1, name4, name1.equalsIgnoreCase(name4));
    System.out.format("Does %s equalsIgnoreCase %s? %s%n", 
                name1, name5, name1.equalsIgnoreCase(name5));
  }
}

equalsIgnoreCase() Output

In this example, you now see how the equalsIgnoreCase() method is returning true for name1, name2 and name3 as the three names contain the same value, in our case “christine”, albeit in different case. In essense, Strings in mixed case, titlecase, camelcase, uppercase and lowercase would all be considered the same in terms of equality.

Does Christine equalsIgnoreCase christine? true
Does Christine equalsIgnoreCase Christine? true
Does Christine equalsIgnoreCase CHRISTINE? true
Does Christine equalsIgnoreCase Chris? false

startsWith() and endsWith()

The startsWith() method wll return true if the String begins with the substring specified in the parameter. By the same token, the endsWith() method wll return true if the String ends with the substring specified in the parameter.

package com.avaldes.tutorial;

public class JavaStartsEndsWith {
  public static void main(String[] args) {
    String phrase = "Between a Rock and a Hard Place";
    String start = "Between";
    String end = "ace";

    System.out.format("Does '%s' starts with %s? %s%n", 
          phrase, start, phrase.startsWith(start));
    System.out.format("Does '%s' starts with %s? %s%n", 
          phrase, end, phrase.startsWith(end));
    System.out.format("Does '%s' ends with %s? %s%n", 
          phrase, end, phrase.endsWith(end));
  }
}

startsWith() and endsWith() Output

Does 'Between a Rock and a Hard Place' start with Between? true
Does 'Between a Rock and a Hard Place' start with ace? false
Does 'Between a Rock and a Hard Place' end with ace? true

Regular Expression using matches()

The String class supports searching using matches(String regex) method passing the regular expression as a parameter and returns true if the string matches the regular expression.

In this example we use three different String phrases and five patterns to illustrate a variety of patterns and when the matches based on the regex will return true and when the pattern match will return false.

When this code is executed the first matches() check is performed to determine whether the phrase “Between a Rock and a Hard Place” matches the regular expression pattern Rock(.*), which it does not so the code returns false. This RegEx pattern is looking for ‘Rock’ at the beginning of the phrase.

In essense, the Rock(.*) pattern looks for Rock, the . ‘dot’ character means any character and the * (asterisk) says look for any number of characters.

The next regular expression pattern (.*)Rock(.*) checks for the word Rock anywhere in the phrase.

The regular expression pattern (.*)Rock checks for the word Rock in the end of the phrase.

The regular expression pattern (.*)Place checks for the word Rock in the end of the phrase.

The regular expression pattern (\\d+).* checks for numbers at the beginning of the phrase. These numbers may be followed by any number of alphanumeric characters.

package com.avaldes.tutorial;

public class JavaMatchesExample {
 public static void main(String[] args) {
  String phrase = "Between a Rock and a Hard Place";
  String phrase1 = "90210 Melrose Place";
  String phrase2 = "90210";
  String pattern = "Rock(.*)";
  String pattern1 = "(.*)Rock(.*)";
  String pattern2 = "(.*)Rock";
  String pattern3 = "(.*)Place";
  String pattern4 = "(\\d+).*";
    
  System.out.println("Is 'Rock' at beginning of phrase?");
  System.out.format("Matching '%s': %s%n", 
    phrase, phrase.matches(pattern));
   
  System.out.println("\nIs 'Rock' anywhere in the phrase?");
  System.out.format("Matching '%s': %s%n", 
    phrase, phrase.matches(pattern1));
    
  System.out.println("\nIs 'Rock' at end of phrase?");
  System.out.format("Matching '%s': %s%n", 
    phrase, phrase.matches(pattern2));
    
  System.out.println("\nIs 'Place' at end of phrase?");
  System.out.format("Matching '%s': %s%n", 
    phrase, phrase.matches(pattern3));
   
  System.out.println("\nDoes phrase have numbers at beginning?");
  System.out.format("Matching '%s': %s%n", 
    phrase, phrase.matches(pattern4));
   
  System.out.println("\nDoes phrase have numbers at beginning?");
  System.out.format("Matching '%s': %s%n", 
    phrase1, phrase1.matches(pattern4));
   
  System.out.println("\nDoes phrase have numbers at beginning?");
  System.out.format("Matching '%s': %s%n", 
    phrase2, phrase2.matches(pattern4));
 }
}

matches() Output

Is 'Rock' at beginning of phrase?
Matching 'Between a Rock and a Hard Place': false

Is 'Rock' anywhere in the phrase?
Matching 'Between a Rock and a Hard Place': true

Is 'Rock' at end of phrase?
Matching 'Between a Rock and a Hard Place': false

Is 'Place' at end of phrase?
Matching 'Between a Rock and a Hard Place': true

Does phrase have numbers at beginning?
Matching 'Between a Rock and a Hard Place': false

Does phrase have numbers at beginning?
Matching '90210 Melrose Place': true

Does phrase have numbers at beginning?
Matching '90210': true

Searching Strings using indexOf(str)

We can use indexOf(String str) to search for a substring within a String. The indexOf(String str) returns an int value representing the index location of the first occurence of the str parameter in the String. If no match is found, it returns -1.

package com.avaldes.tutorial;

public class JavaIndexOfExample {
 public static void main(String[] args) {
 
  String phrase = "Between a Rock and a Hard Place”"; 
  int index = phrase.indexOf("Rock");
  
  System.out.format("'%s', index=%d%n", phrase, index);
 }
}

indexOf() Output

'Between a Rock and a Hard Place', index=10

The illustration below will help make things easier to visualize. There is also another signature available indexOf(String str, int fromIndex) that allows you to start searching for the substring from a certain index.

string_indexof

Searching Strings using indexOf(str,idx)

package com.avaldes.tutorial;

public class JavaIndexOfExample {
 public static void main(String[] args) {

  String phrase = "The Rock: Between a Rock and a Hard Place”";	
  int index = phrase.indexOf("Rock");
  int index1 = phrase.indexOf("Rock", index + 1);
		
  System.out.format("'%s', index=%d%n", phrase, index);
  System.out.format("'%s', index=%d%n", phrase, index1);
 }
}

indexOf(str,idx) Output

'The Rock: Between a Rock and a Hard Place”', index=4
'The Rock: Between a Rock and a Hard Place”', index=20

That’s It!

I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

java_string

Core Java Related Tutorials

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *