Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can toString() method take an argument in Java?

Tags:

java

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());


      }
}
like image 656
aqibjr1 Avatar asked Dec 21 '15 11:12

aqibjr1


People also ask

Can a toString method accept parameters?

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.

What is the purpose of toString () method in Java?

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.

Can toString throw exception?

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.

What type of method is toString ()?

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.


1 Answers

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));
like image 167
Konstantin Yovkov Avatar answered Oct 03 '22 11:10

Konstantin Yovkov