Wednesday, March 28, 2012

Data Conversion Using valueOf( )

The valueOf( ) method converts data from its internal format into a human-readable
form. It is a static method that is overloaded within String for all of Java’s built-in types,
so that each type can be converted properly into a string. valueOf( ) is also overloaded
for type Object, so an object of any class type you create can also be used as an argument.
(Recall that Object is a superclass for all classes.) Here are a few of its forms:


static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[ ])

As we discussed earlier, valueOf( ) is called when a string representation of some
other type of data is needed—for example, during concatenation operations. You can call
this method directly with any data type and get a reasonable String representation. All
of the simple types are converted to their common String representation. Any object that
you pass to valueOf( ) will return the result of a call to the object’s toString( ) method. In
fact, you could just call toString( ) directly and get the same result.
For most arrays, valueOf( ) returns a rather cryptic string, which indicates that it
is an array of some type. For arrays of char, however, a String object is created that
contains the characters in the char array. There is a special version of valueOf( ) that
allows you to specify a subset of a char array. It has this general form:

static String valueOf(char chars[ ], int startIndex, int numChars)
Here, chars is the array that holds the characters, startIndex is the index into the array of
characters at which the desired substring begins, and numChars specifies the length of
the substring.

Changing the Case of Characters
Within a String


The method toLowerCase( ) converts all the characters in a string from uppercase to
lowercase. The toUpperCase( ) method converts all the characters in a string from
lowercase to uppercase. Nonalphabetical characters, such as digits, are unaffected.
Here are the general forms of these methods:

String toLowerCase( )
String toUpperCase( )


Both methods return a String object that contains the uppercase or lowercase
equivalent of the invoking String.
Here is an example that uses toLowerCase( ) and toUpperCase( ):


// Demonstrate toUpperCase() and toLowerCase().

class ChangeCase {
public static void main(String args[])
{
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}
The output produced by the program is shown here:
Original: This is a test.
Uppercase: THIS IS A TEST.
Lowercase: this is a test.

No comments:

Post a Comment