0
import java.util.Arrays;
class B {

    int i;

    B(int i) {
    this.i = i;
    }

     public String toString() {
          return "i = " + this.i;
       }
}

 public class MainClass{

        public static void main(String[] args) {
            B [] x = new B[2];
            x[0] = new B(90);
            x[1] = new B(100);
            B obj = new B(10);
            System.out.println(obj);
                    System.out.println(x);//toString method of class B is not called here.

    }
}

//When i printed obj the toString method of B class was called but when I tried to print x it was not called.Can anybody explain why!!!

Aamir
  • 2,380
  • 3
  • 24
  • 54

3 Answers3

1

Actually, the toString method of the Array class was called, and Array does not override the Object toString() - so you get a class name and (essentially) a reference address. What you wanted was probably Arrays.toString(Object[]) - like so,

// System.out.println(x); // <-- calls toString of java.lang.Array
System.out.println(Arrays.toString(x));
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Java does not automatically invoke toString on the members of an array. As mentioned here, you want Arrays.toString(x).

Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329
0

It's because you're printing the array itself, not the individual elements of the array. Arrays are objects, too, but they don't override toString() from Object. Try

System.out.println(Arrays.toString(x));
rgettman
  • 176,041
  • 30
  • 275
  • 357