Java Program to convert a Primitive Type Value to a String


For converting a primitive type value to a string in Java, use the valueOf() method.Let’s say we want to convert the following double primitive to string.

double val4 = 8.34D;

For that, use the valueOf() method. It converts it into a string.

String str4 = String.valueOf(val4);

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      int val1 = 5;
      char val2 = 'z';
      float val3 = 9.56F;
      double val4 = 8.34D;
      System.out.println("Integer: "+val1);
      System.out.println("Character: "+val2);
      System.out.println("Float: "+val3);
      System.out.println("Double: "+val4);
      String str1 = String.valueOf(val1);
      String str2 = String.valueOf(val2);
      String str3 = String.valueOf(val3);
      String str4 = String.valueOf(val4);
      System.out.println("
Converted to string...");       System.out.println(str1);       System.out.println(str2);       System.out.println(str3);       System.out.println(str4);    } }

Output

Integer: 5
Character: z
Float: 9.56
Double: 8.34
Converted to string...
5
z
9.56
8.34

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements