I tested this in eclipse, and it didn't give me any exceptions. However I wasn't able to specify the value x. Can toString() take an argument (I know that my example below isn't the greatest)?
Test.java
public class Test {
public String toString(int x){
return "Hey "+ x;
}
}
Main.java
public class Main {
public static void main(String[] args){
System.out.println(new Test());
}
}
toString() is an inbuilt method in Java which is used to return the String object representing this Integer's value. Parameters: The method does not accept any parameters.
The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler. Else, the user implemented or overridden toString() method is called.
toString() Method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error. toString() Method does not throw an exception at the time of string representation about the exception.
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.
Can
toString()
take an argument?
Yes, and in this case you'll have an overloaded toString()
method.
When invoking System.out.println(t)
, however, the Object#toString()
will be invoked anyway (and you can verify that by checking the PrintStream#println(Object t)
method's source).
In order to invoke your custom .toString()
method, you have to do (for example):
System.out.println(t.toString(5));
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