• Post Reply Bookmark Topic Watch Topic
  • New Topic

why does the static initialize when object is created?  RSS feed

 
Arend van der Kolk
Ranch Hand
Posts: 78
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I understand that from below code we get the first "u " and another "u ".

But i dont understand why line 5 in OrderDriver results in a 3rd "u". I thought statics don't get initialized when you create an Object. Then "crcr" is clear to me as they are instance variables.

This is a test question.



 
Arend van der Kolk
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The fact that "result" is a concatenation of statics variables and instance varibles i find confusing.
 
Arend van der Kolk
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After debugging again in the IDE i realize it is the same "u" in variable result which was there in the beginning and still there when the Objects are created.
 
Junilu Lacar
Sheriff
Posts: 11486
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right, you'll only have one result value shared by all instances of Order. Every time you create an instance of Order, you will be adding another "cr" to result.
So, line 3 will print "u ", line 4 will print "u ", then line 5 will make result be "ucr", then line 6 will make result "ucrcr" and finally line 7 will print result and a space: "ucrcr ".  

That is why your output will look like this:

u u ucrcr

with a space at the end.
 
Arend van der Kolk
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Junilu for clarification.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!