Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Tuesday, June 30, 2020

Convert Any primitive to String Using ValueOf() in Java 8 - int to String

1. Introduction


In this article, You'll learn how to convert any primitive value to a String. Let us see the examples to convert int, long, double, char, boolean, float, and char[] array to String objects.

All of these primitive conversions are done using the String API valueOf() method. valueOf() method is an overloaded method in String class and declared a static method.

Java String ValueOf() - Primitive to String


Convert Any primitive to String Using ValueOf() in Java 8 - int to String



2. String valueOf() Syntax


All of the below methods are from Java String API.

public static String valueOf​(boolean b)
public static String valueOf​(char c)
public static String valueOf​(char[] data)
public static String valueOf​(char[] data, int offset, int count)
public static String valueOf​(double d)
public static String valueOf​(float f)
public static String valueOf​(int i)
public static String valueOf​(long l) 
public static String valueOf​(Object obj)

All of these are static methods and directly can be accessed with a class name like String.valueOf(100).

Look at more on String Interview Programs.

3. Convert Primitive Int or Long to a String


We are going to write a program that converts boolean, int, float, double, and char array into a string.

package com.javaprogramto.w3schools.programs.string;

public class PrimitiveToString {

    public static void main(String[] args) {

        int age = 30;

        String ageString = String.valueOf(age);
        System.out.println("String age : "+ageString);

        float PI = 3.14f;

        String floatString = String.valueOf(PI);
        System.out.println("String float : "+floatString);

        double salary = 1000000;

        String doubleString = String.valueOf(salary);
        System.out.println("String double : "+doubleString);

        long size = 15098;

        String longString = String.valueOf(size);
        System.out.println("String Long : "+longString);

        boolean isValid = false;
        String booleanString = String.valueOf(isValid);
        System.out.println("String boolean : "+booleanString);

        char[] chars = {'a', 'e', 'o', 'i', 'u'};
        String stringCharArray = String.valueOf(chars);
        System.out.println("String char array : "+stringCharArray);
    }
}

Output:

String age : 30
String float : 3.14
String double : 1000000.0
String Long : 15098
String boolean : false
String char array : aeoiu

4. Conclusion


In this article, We've seen how to convert primitive to a String object. This is done with the help of String.valueOf() method.

As usual, the code shown in this article is over the github.




No comments:

Post a Comment

Please do not add any spam links in the comments section.