Wrapper Class - Converting primitive number to string object in Java


The code demonstrates how to convert primitive data types to their corresponding String object representations using the toString() method of the wrapper classes. The toString() method is a built-in method of every object in Java, including the wrapper classes. It returns a String representation of the object, which can be used for display, storage, or other purposes.

In this code, we create a short, byte, int, long, float, and double variable, and use the corresponding toString() method of their wrapper classes to convert them to String objects. We then print the resulting String objects to the console.

Source Code

public class wrapperClass3 {
    public static void main(String args[])
    {
        //Converting primitive number to string object.
        short s=25;
        String S=Short.toString(s);//"25"
        System.out.println("Short String Object : "+S);
        byte b=25;
        String B=Byte.toString(b);
        System.out.println("Byte String Object : "+B);
        int i=25;
        String I=Integer.toString(i);
        System.out.println("Integer String Object : "+I);
        long l=25;
        String L=Long.toString(l);
        System.out.println("Long String Object : "+L);
        float f=25.5f;
        String F=Float.toString(f);
        System.out.println("Float String Object : "+F);
        double d=25.525;
        String D=Double.toString(d);
        System.out.println("Double String Object : "+D);
    }
}
 

Output

Short String Object : 25
Byte String Object : 25
Integer String Object : 25
Long String Object : 25
Float String Object : 25.5
Double String Object : 25.525
To download raw file Click Here

Basic Programs