Kindly let me know the difference between this two methods. Thanks in advance.
String. valueOf will transform a given object that is null to the String "null" , whereas . toString() will throw a NullPointerException . The compiler will use String.
The toString method is used to return the String representation of an object (converting an object to a String). Like equals , all Java objects have a toString method. However, also like equals not all classes provide particularly useful implementations.
A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.
Both these methods are used to convert a string. But yes, there is a difference between them and the main difference is that Convert. Tostring() function handles the NULL while the . ToString() method does not and it throws a NULL reference exception.
Java toString() method :
If you want to represent any object as a string, toString() method comes into existence.The toString() method returns the string representation of the object.
Example :
Student s1 = new Student(101,"Raj","lucknow");
Student s2 = new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
//Output : 101 Raj lucknow
102 Vijay ghaziabad
Java toPlainString() method :
The java.math.BigDecimal.toPlainString() returns a string representation of this BigDecimal without an exponent field.
Example :
MathContext mc = new MathContext(3); // 3 precision
BigDecimal bigDecimal = new BigDecimal("1234E+4", mc);
// Assign the plain string value of bigDecimal to s
String plainString = bigDecimal.toPlainString();
String str = "Plain string value of " + bigDecimal + " is " + plainString;
// print s value
System.out.println( str );
//Output : Plain string value of 1.23E+7 is 12300000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With