• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

need help in an array of strings?

 
gurpeet singh
Ranch Hand
Posts: 924
1
Fedora Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 924
1
Fedora Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rahman . Problem is resolved.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic