Converting Primitive Values and Objects to Strings – Selected API Classes

Converting Primitive Values and Objects to Strings

The String class overrides the toString() method in the Object class and returns the String object itself:

Click here to view code image

String toString()                   
From the
 CharSequence
interface (p. 444)
.

The String class also defines a set of static overloaded valueOf() methods to convert objects and primitive values into strings:

Click here to view code image

static String valueOf(Object obj)
static String valueOf(char[] charArray)
static String valueOf(boolean b)
static String valueOf(char c)

All of these methods return a string representing the given parameter value. A call to the method with the parameter obj is equivalent to obj.toString() when obj is not null; otherwise, the “null” string is returned. The boolean values true and false are converted into the strings “true” and “false”. The char parameter is converted to a string consisting of a single character.

Click here to view code image

static String valueOf(int i)
static String valueOf(long l)
static String valueOf(float f)
static String valueOf(double d)

The static valueOf() method, which accepts a primitive value as an argument, is equivalent to the static toString() method in the corresponding wrapper class for each of the primitive data types ((6a) and (6b) in §8.3, p. 430). Note that there are no valueOf() methods that accept a byte or a short.

Examples of string conversions:

Click here to view code image

String anonStr   = String.valueOf(“Make me a string.”);      // “Make me a string.”
String charStr   = String.valueOf(new char[] {‘a’, ‘h’, ‘a’});// “aha”
String boolTrue  = String.valueOf(true);                      // “true”
String doubleStr = String.valueOf(Math.PI);                   // “3.141592653589793”

Transforming a String

The transform() method allows a function to be applied to a string to compute a result. The built-in functional interface Function<T, R>, and writing lambda expressions to implement such functions, are covered in the following sections: §13.8, p. 712, and §13.2, p. 679, respectively.

Click here to view code image

<R> R transform(Function<? super String,? extends R> f)

The specified function f is applied to this string to produce a result of type R.

The example below illustrates using the transform() method to reverse the characters in a string via a StringBuilder (p. 464). Its versatility becomes apparent when the string contains lines of text or a text block that needs to be processed (p. 458).

Click here to view code image String message = “Take me to your leader!”;
String tongueSpeake = message.transform(s ->
    new StringBuilder(s).reverse().toString().toUpperCase());
System.out.println(tongueSpeake); // !REDAEL RUOY OT EM EKAT


Comments

Leave a Reply

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