Convert Primitive Data Type to String

This post will discuss how to convert any primitive data type to string in Java

Int to String

You convert a integer to a string by calling the valueOf method.

package octopuscodes.com.demo;

public class Demo {

	public static void main(String[] args) {
		int i = 678;
		String s = String.valueOf(i);
		System.out.println("s: " + s);
	}

}
s: 678
 

Long to String

You convert a long number to a string by calling the valueOf method.

package octopuscodes.com.demo;

public class Demo {

	public static void main(String[] args) {
		long l = 123;
		String s = String.valueOf(l);
		System.out.println("s: " + s);
	}

}
s: 123
 

Float to String

You convert a float to a string by calling the valueOf method.

package octopuscodes.com.demo;

public class Demo {

	public static void main(String[] args) {
		float f = 6.78f;
		String s = String.valueOf(f);
		System.out.println("s: " + s);
	}

}
s: 6.78
 

Double to String

You convert a double to a string by calling the valueOf method.

package octopuscodes.com.demo;

public class Demo {

	public static void main(String[] args) {
		double d = 6.78;
		String s = String.valueOf(d);
		System.out.println("s: " + s);
	}

}
s: 6.78
 

Boolean to String

You convert a boolean to a string by calling the valueOf method.

package octopuscodes.com.demo;

public class Demo {

	public static void main(String[] args) {
		boolean b1 = true;
		String s1 = String.valueOf(b1);
		System.out.println("s1: " + s1);
		
		boolean b2 = false;
		String s2 = String.valueOf(b2);
		System.out.println("s2: " + s2);
	}

}
s1: true
s2: false