String Datatype in Java

A string literal is made up of one or more characters between double quotes. An example of string literals is the statement in lines 16–17 of the Circle program. We can define a string to be a variable by using the String data type. For example, in the Circle program, we could declare String variables string1 and string2, as follows:

String string1 = "A circle of radius ";

String string2 = " has area of”;




Replace the lines from the Multiply .java (16–17) can now be replaced byl

System.out.println(string1 + args[0] + string2 + area);

The + is used as a concatenation operator. Where a String is concatenated with a value that is not a String, such as args[0] or area, the compiler will convert that value to a String.

A String is actually an object in Java; we discuss objects in detail in Chapter 4. A string can be created using the following objectlike syntax:

String string1 = new String("A circle of radius ");

This statement, and the statement

String string1 = "A circle of radius ";

Are both legal in Java. An exception has been made in the Java language to allow initialization of a String in a manner similar to nonobject-oriented languages. An exception also has been made in the use of the + operator to allow String concatenation:
We would expect to use a method to concatenate objects.

Since a String is an object, a large number of methods are provided for manipulating strings. For example, the java.lang.String.length method gives the length of a String, as in

string1.length ()


The java.lang.String.charAt (position) method returns the character at the specified position, starting at 0. For example,

string1.charAt (3)

will return the fourth character in the string, namely, i.

Strings are immutable in Java. One cannot change individual characters in a String. There is no method to change the nth character in a String. When we perform String concatenation, we are not modifying the original String but creating a new String object. The following example of java.lang.String.concat method illustrates String immutability:

String s1, s2;
s1 = ''abc";
s2 = s1.concat ("def");


The value of s1 after the concat method is executed remains an unchanged "abc". S2 is equal to "abcdef" since concat returns a new object with the concatenated result, which
is assigned to s2. The main advantage of String immutability is that the Java compiler can save space by sharing Strings. If a program repeatedly performs String concatenation, when processing a file, for example, then the repeated creation of new objects becomes inefficient. To cater for this, Java provides a mutable StringBuffer class,

Convert all primitive data types to String using the java.lang.String.valueOf method. For example, the following converts an int to a String:

int count = 123;
String countString = String.valueOf(count);

No comments:

Post a Comment