Primitive Values to Strings in Java

Understanding through Code

import java.text.NumberFormat;    public class PrimitiveToString {  	public static void main( String[] args ){  		int intVal = 24;  		String intToStr = Integer.toString(intVal);  		System.out.println(intToStr);    		boolean boolVal = true;  		String boolToStr = Boolean.toString(boolVal);  		System.out.println(boolToStr);    		long longVal = 12_400;  		NumberFormat formatter = NumberFormat.getNumberInstance();  		String longValFormatted = formatter.format(longVal);  		System.out.println(longValFormatted);  	}  }

Output

  • 24
  • true
  • 12,400

Notes

  • 12_400 is same as 12400 for the compiler. The underscore helps to make it more readable.
  • Using underscore as separators was introduced in Java V7.
  • NumberFormat is part of different package and not java.lang. So we need to import the package.