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,194
  • 1
  • 21
  • 48

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
  • 191,680
  • 20
  • 149
  • 239
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
  • 67,488
  • 40
  • 178
  • 299
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
  • 172,063
  • 28
  • 262
  • 343