Explain the usage of the valueOf() method of the String class in Java

JavaServer Side ProgrammingProgramming

The String class of the java.lang package represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are constant, their values cannot be changed after they are created.

The valueOf() method of the String class accepts a char or, char array or, double or, float or, int or, long or an object as a parameter and returns its String representation.

Example

Live Demo

import java.util.Scanner;
public class ConversionOfDouble {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a double value:");
      Double d = sc.nextDouble();
      String result = "".valueOf(d);
      System.out.println("The result is: "+result);
   }
}

Output

Enter a double value:
2548.2325
The result is: 2548.2325

Example

Live Demo

import java.util.Scanner;
public class Test {
   public static void main(String args[]) {
      String str = new String();      
      float floatVal = 2569.336f;
      String val1 = str.valueOf(floatVal);
      System.out.println(val1);      
      double doubleVal = 2569.336;
      String val2 = str.valueOf(doubleVal);
      System.out.println(val2);      
      int intVal = 5548;
      String val3 = str.valueOf(intVal);
      System.out.println(val3);      
      boolean boolVal = true;
      String val4 = str.valueOf(boolVal);
      System.out.println(val4);      
      char charVal = 'K';
      String val5 = str.valueOf(charVal);
      System.out.println(val5);      
   }
}

Output

2569.336
2569.336
5548
true
K
raja
Published on 08-Feb-2021 11:31:27
Advertisements