Wednesday, June 20, 2007

Converting Java Primitives To Strings

It’s fairly easy to convert the primitives in Java; byte, short, char, int, long, float, double and boolean, into Strings; simply use the toString() method of the respective wrapper classes. But there’s a far easier way.

It’s pretty well known that the String class overrides the ‘+’ operator for concatenation of strings. It’s also often mentioned that one should be careful while using code like

String total = “The sum is ” + 2 + 4; 

since this will create the string as “The sum is 24” instead of the ( assumedly ) expected “The sum is 6” since the role of ‘+’ as the concatenation operator takes precedence over addition.

This very side-effect can be utilized for all primitives. Simply concatenate the required primitive with an empty string ( “” ) and you get the value as a String! Consider the sample below:

public class ConvertToString
{
    public static void main(String[] args)
    {
        String finalOutput = "";

        byte b = 1;
        short s = 3;
        char c = 'd';
        int i = 14;
        long l = 1234;
        float f = 2.0F;
        double d = 1.55;
        boolean bn = true;

        // finalOutput = b; //will not compile
        // finalOutput = (String)b; //will not compile

        // finalOutput = Byte.toString(b); //using the corresponding wrapper class

        finalOutput = b + "";
        System.out.println("The byte as String " + finalOutput);

        finalOutput = s + "";
        System.out.println("The short as String " + finalOutput);

        finalOutput = c + "";
        System.out.println("The char as String " + finalOutput);

        finalOutput = i + "";
        System.out.println("The int as String " + finalOutput);

        finalOutput = l + "";
        System.out.println("The long as String " + finalOutput);

        finalOutput = f + "";
        System.out.println("The float as String " + finalOutput);

        finalOutput = d + "";
        System.out.println("The double as String " + finalOutput);

        finalOutput = bn + "";
        System.out.println("The boolean as String " + finalOutput);
    }
}

As you can see, there’s no need to be messing around with the wrapper classes. Admittedly, it’s not that big a deal, but it does make the code a little neater.

No comments: