Chapter: Java The Complete Reference - The Java Library - String Handling

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Special String Operations - Java

Because strings are a common and important part of programming, Java has added special support for several string operations within the syntax of the language.

Special String Operations

 

Because strings are a common and important part of programming, Java has added special support for several string operations within the syntax of the language. These operations include the automatic creation of new String instances from string literals, concatenation of multiple String objects by use of the + operator, and the conversion of other data types to a string representation. There are explicit methods available to perform all of these functions, but Java does them automatically as a convenience for the programmer and to add clarity.

 

String Literals

 

The earlier examples showed how to explicitly create a String instance from an array of characters by using the new operator. However, there is an easier way to do this using a string literal. For each string literal in your program, Java automatically constructs a String object. Thus, you can use a string literal to initialize a String object. For example, the following code fragment creates two equivalent strings:

 

char chars[] = { 'a', 'b', 'c' }; String s1 = new String(chars);

 

String s2 = "abc"; // use string literal

 

Because a String object is created for every string literal, you can use a string literal any place you can use a String object. For example, you can call methods directly on a quoted string as if it were an object reference, as the following statement shows. It calls the length( ) method on the string "abc". As expected, it prints "3".

System.out.println("abc".length());

String Concatenation

In general, Java does not allow operators to be applied to String objects. The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result. This allows you to chain together a series of + operations. For example, the following fragment concatenates three strings:

 

String age = "9";

 

String s = "He is " + age + " years old.";

 

System.out.println(s);

 

This displays the string "He is 9 years old."

 

One practical use of string concatenation is found when you are creating very long strings. Instead of letting long strings wrap around within your source code, you can break them into smaller pieces, using the + to concatenate them. Here is an example:

 

// Using concatenation to prevent long lines.

class ConCat {

 

public static void main(String args[]) { String longStr = "This could have been " +

 

"a very long line that would have " +

 

"wrapped around. But string concatenation " + "prevents this.";

 

System.out.println(longStr);

 

}

 

}

 

String Concatenation with Other Data Types

 

You can concatenate strings with other types of data. For example, consider this slightly different version of the earlier example:

 

int age = 9;

 

String s = "He is " + age + " years old."; System.out.println(s);

 

In this case, age is an int rather than another String, but the output produced is the same as before. This is because the int value in age is automatically converted into its string representation within a String object. This string is then concatenated as before. The compiler will convert an operand to its string equivalent whenever the other operand of the + is an instance of String.

Be careful when you mix other types of operations with string concatenation expressions, however. You might get surprising results. Consider the following:

 

String s = "four: " + 2 + 2;

 

System.out.println(s);

This fragment displays

four: 22

rather than the

 

four: 4

 

that you probably expected. Here’s why. Operator precedence causes the concatenation of "four" with the string equivalent of 2 to take place first. This result is then concatenated with the string equivalent of 2 a second time. To complete the integer addition first, you must use parentheses, like this:

 

String s = "four: " + (2 + 2);

 

Now s contains the string "four: 4".

 

String Conversion and toString( )

 

When Java converts data into its string representation during concatenation, it does so by calling one of the overloaded versions of the string conversion method valueOf( ) defined by String. valueOf( ) is overloaded for all the primitive types and for type Object. For the primitive types, valueOf( ) returns a string that contains the human-readable equivalent of the value with which it is called. For objects, valueOf( ) calls the toString( ) method on the object. We will look more closely at valueOf( ) later in this chapter. Here, let’s examine the toString( ) method, because it is the means by which you can determine the string representation for objects of classes that you create.

 

Every class implements toString( ) because it is defined by Object. However, the default implementation of toString( ) is seldom sufficient. For most important classes that you create, you will want to override toString( ) and provide your own string representations. Fortunately, this is easy to do. The toString( ) method has this general form:

 

String toString( )

 

To implement toString( ), simply return a String object that contains the human-readable string that appropriately describes an object of your class.

By overriding toString( ) for classes that you create, you allow them to be fully integrated into Java’s programming environment. For example, they can be used in print( ) and println( ) statements and in concatenation expressions. The following program demonstrates this by overriding toString( ) for the Box class:

 

// Override toString() for Box class.

class Box {

 

double width; double height; double depth;

 

Box(double w, double h, double d) { width = w;

 

height = h; depth = d;

 

}

 

public String toString() {

 

return "Dimensions are " + width + " by " +

 

depth + " by " + height + ".";

 

}

 

}

 

class toStringDemo {

 

public static void main(String args[]) { Box b = new Box(10, 12, 14);

 

String s = "Box b: " + b; // concatenate Box object

 

System.out.println(b); // convert Box to string

System.out.println(s);

 

}

 

}

 

The output of this program is shown here:

 

Dimensions are 10.0 by 14.0 by 12.0

 

Box b: Dimensions are 10.0 by 14.0 by 12.0

 

As you can see, Box’s toString( ) method is automatically invoked when a Box object is used in a concatenation expression or in a call to println( ).

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.