File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes need help in an array of strings? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "need help in an array of strings?" Watch "need help in an array of strings?" New topic

need help in an array of strings?

gurpeet singh
Ranch Hand

Joined: Apr 04, 2012
Posts: 924

Suppose i have following code listing

code listing:

//which produces output of "one"

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[10]; 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[0] will hold reference to "one" object which has been created on heap. so when i did System.out.println(s[0]); 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[0] which causes "one" to be printed ?? if yes why and from where toString() method gets called??

Praveen Kumar M K
Ranch Hand

Joined: Jul 03, 2011
Posts: 256
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
Ranch Hand

Joined: Apr 10, 2012
Posts: 33
Hello gurpeet,
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.
gurpeet singh
Ranch Hand

Joined: Apr 04, 2012
Posts: 924

Thanks Rahman . Problem is resolved.
I agree. Here's the link:
subject: need help in an array of strings?
It's not a secret anymore!