I'm reading Kb book and it says that when we create an array of objects it gets initialized with the default value of that type. so far well and good. it also says that when we do String  s = new String; we are in effect declaring a string array and initializing it(giving it a size of 10). this statement will create a array object of type string which will hold 10 string objects. to be more accurate it will hold references , which will point to string objects. that means s will hold reference to "one" object which has been created on heap. so when i did System.out.println(s); how come the value "one" gets printed ? should not the reference value must be printed ? as i was finishing this it came to my mind is it that toString() method gets called on s which causes "one" to be printed ?? if yes why and from where toString() method gets called??
OCPJP 6(100 %) OCEWCD 6(91 %)
Praveen Kumar M K
Joined: Jul 03, 2011
Consider this scenario :
This would print 'Hello' and not a memory address.(verify!)
Now consider this scenario :
This would print a memory address and not "Hello". Now what do you think is the difference between the 2 scenarios? The answer lies in the question that you yourself asked...(hint : toString())
Md. Minhajur Rahman
Joined: Apr 10, 2012
When calling System.out.println(object), if the object itself override toString() method, the println() function forces to call toString() on that object . so in your case, object is a String object and it does overrride toString() method, so the output is "one" resulting from toString() and if the object does not override toString() method, then println() then gives the output of the format like classname@HashCode of that object.