Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String syntax

 
Mahalakshmi Chandru
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,
the below method has a different syntax for assigning values to a String object. Can anybody explain how does this work internally:

 
Campbell Ritchie
Sheriff
Pie
Posts: 48968
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does it work at all? Assuming it compiles at all, it is a weird bit of code. If you look at the array initialiser syntax, and remembering that [x] is array member access, please tell us how you think it works.

It does compile, but you have a tiny logic error, so please also suggest how you can get it to return a different value every time.
 
Mahalakshmi Chandru
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It does work. I got to understand the syntax now. We are declaring a String array as a 2 dimensional one and also we are initializing the same in the same line itself.

Here the 2nd dimension will be passed dynamically. Hence the value for "RandomName" returned varies each time depending upon the 2nd index passed. I got this code snippet under the topic "Overloaded Constructors" from SCJP 5 - Chapter 2.
 
Omar Al Kababji
Ranch Hand
Posts: 357
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the only problem you have is that the x value will be always evaluated to zero you should have multiplied by 5 and then casting to (int).

 
Mahalakshmi Chandru
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Omar,
I realized the misplaced brackets. After placing them correctly, it is producing random values for 'x'. Also , i do understand the wierd syntax in the code snippet.
 
Mahalakshmi Chandru
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Omar,
Got a doubt now. What is the difference between the below 2 code snippets:





both of them declares a single dimentional String array. but in the first declaration, we are assigning the new String object to the String ref "RandomName", whereas in the second decl we are not creating a new String object. Please clarify.Thanks
 
Omar Al Kababji
Ranch Hand
Posts: 357
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They just create a string array and assign it to the randomNames[]. they are the same however the first one is more understandable ;)
 
Mahalakshmi Chandru
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it. Thank you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic