7

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


      }
}
aqibjr1
  • 651
  • 5
  • 21

2 Answers2

11

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));
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
4

Yes, but in this case you won't be overriding the Object::toString method, just creating your own overloading.

Your method is valid

public String toString(int x) {
     return "Hey "+ x;
}

Check this question to clarify

To execute it this won't be valid because you will be calling Test.toString() not Test.toString(int):

System.out.println(new Test());

Create an instance and call your method:

Test t = new Test();
System.out.println(t.toString(10);

OUTPUT:

Hey 10
Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109