Header javaperspective.com
JavaPerspective.com  >   Beginner Tutorials  >   5. Java in Practice  >   5.3. Working with strings

5.3. Working with strings
Last updated: 23 January 2013.

In the Java language, a string is an object (an instance of the class String). This tutorial will show you how to create, concatenate and compare strings in Java. Also, the method toString provided by the class String will be discussed.


5.3.1. String creation

The following statements create string objects in two different ways:

String s1 = "Hello World";
String s2 =
new String("Hello World");

In both cases, the JVM allocates enough memory to store the string object but the instantiation of the string s1 is faster than that of the string s2. Therefore, you should never use the constructor of the class String unless you have a good reason to do so.

Another key point is that strings are constants. In other words, a string value cannot be changed after it is created. As a result, a number of operations that return a string value (such as string concatenations) do not update the strings they are working on but they rather create one or more strings when they are executed.


5.3.2. String concatenation

The statement shown below concatenates two strings:

String s = "Hello " + "World";

Because strings are constants, 3 objects are actually created in the statement above: one string object for "Hello ", another one for "World" and a third one for "Hello World". After the statement is executed, the temporary objects "Hello " and "World" become eligible for garbage collection.

As you can see, a simple concatenation of strings with the operator + is very costly in terms of memory and time. Likewise, the method concat provided by the class String also performs costly instantiations. For this reason, you should use the class StringBuffer or StringBuilder if performance matters to your application (which is usually the case). Unlike String objects, StringBuffer and StringBuilder objects can be modified and provide a number of methods to operate on a string value. For example, you can create a StringBuffer object and use it to efficiently concatenate strings like this:

StringBuffer s = new StringBuffer();
s.append
("Hello ").append("World");
System.out.println
(s);

The difference between StringBuffer and StringBuilder is how they behave in a multithreaded context. Multithreading will be discussed in the tutorials to come. For now, just bear in mind that StringBuffer is safer than StringBuilder whereas StringBuilder is potentially faster that StringBuffer .


5.3.3. String comparison

In order to check if two string objects have the same value or not, use the method equals. You should never use the operators == or != because they compare references rather than values. For example, the sample shown below creates two distinct references (s1 and s2) that have the same string values and compares them with the operator ==:

char[] c1 = {'H', 'e', 'l'};
char[] c2 = {'l', 'o'};

String s1 = String.valueOf
(c1) + String.valueOf(c2);
System.out.println
(s1);

String s2 =
"Hello";
System.out.println
(s2);

System.out.println
(s1 == s2);

The output is:

Hello
Hello
false

The comparison returns false because s1 and s2 are two different references (although they have the same values). The recommended way to compare two strings is to call the method equals provided by the class Object as follows:

boolean equals = s1.equals(s2);
boolean notEquals = ! s1.equals(s2);

System.out.println
(equals);
System.out.println
(notEquals);

More generally, you should always use the method equals to compare the values of two objects instead of the operator ==.

If you want to ignore case differences while comparing two strings, you can use the method equalsIgnoreCase provided by the class String.

In the same way, you should not use the operators <, >, <=, >= to compare two strings lexicographically. Instead, use one of the methods compareTo or compareToIgnoreCase provided by the class String.


5.3.4. The toString method

You may have noticed that most of the classes of the Java API provide a toString method that overrides the toString method implemented in the superclass Object. Typically, the purpose of a toString implementation is to return a string representation of the object it is called upon. It is recommended to override the toString method in the classes that you create. To take an example, the class River shown below does not override the method toString:

public final class River {

   
private String name;
   
private String continent;
   
private int length;

   
public River(String name, String continent, int length){
         
this.name = name;
         
this.continent = continent;
         
this.length = length;
   
}

   
// ...
    // ...

}

Now if you execute the following statements:

River river = new River("Nile", "Africa", 4180);
System.out.println
(river);

You will get an ouput like this:

River@29d22104

What is actually printed to the standard output is the value returned by the method toString provided by the superclass Object: a concatenation of the class name, the letter @ and the object's hash code. Needless to say, the result is not meaningful. To get a better output, you can override the method toString as shown below:

public final class River {

   
private String name;
   
private String continent;
   
private int length;

   
public River(String name, String continent, int length){
         
this.name = name;
         
this.continent = continent;
         
this.length = length;
   
}

   
// ...
    // ...

   
public String toString(){
         
StringBuffer s = new StringBuffer();

          s.append
("name : ").append(name)
         
.append(", continent : ").append(continent)
         
.append(", length : ").append(length);

         
return s.toString();
   
}

}

Now that you have overridden the toString method, the output will be the following:

name : Nile, continent : Africa, length : 4180


5.3.5. Code exercise

Write a method named reverseOrder(String str) that returns the string str in reverse order. If the value of str is "Hello", the method returns "olleH".


public String reverseOrder(String str){
   
StringBuffer stringBuffer = new StringBuffer(str);
   
return stringBuffer.reverse().toString();
}


You are here :  JavaPerspective.com  >   Beginner Tutorials  >   5. Java in Practice  >   5.3. Working with strings
Next tutorial :  JavaPerspective.com  >   Beginner Tutorials  >   5. Java in Practice  >   5.4. Working with files

Copyright © 2013. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7