What is the difference between String.valueOf() and toString() in Java?


The toString() method of the String class returns itself a string.

Example

Live Demo

import java.io.*;
public class Test {
   public static void main(String args[]) {
      String Str = new String("Welcome to Tutorialspoint.com");
      System.out.print("Return Value :");
      System.out.println(Str.toString());
   }
}

Output

Return Value :Welcome to Tutorialspoint.com

The value of method variants of the String class accepts different variables such as integer, float, boolean etc.. and converts them into String.

Example

Live Demo

public class Sample {
   public static void main(String args[]){
      int i = 200;
      float f = 12.0f;
      char c = 's';
      char[] ch = {'h', 'e', 'l', 'l', 'o'};
      String data = String.valueOf(i);
      System.out.println(String.valueOf(i));
      System.out.println(String.valueOf(f));
      System.out.println(String.valueOf(c));
      System.out.println(String.valueOf(ch));
   }
}

Output

200
12.0
s
hello

Updated on: 26-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements