This week's book giveaway is in the Android forum.
We're giving away four copies of Learning Java by Building Android Games and have Jean-Marcel Belmont on-line!
See this thread for details.
Win a copy of Learning Java by Building Android Games this week in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

Arrays  RSS feed

 
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ranchers,

String s[] = {"s1", "s2","3"};

one array object is created with three references
which are refering to values "s1" and "s2" and "3".that is s[0] is refering to "s1",s[1] is refering to "s2" and so on.
then how come s[0].length is displaying 2.i thought s[0].length will give only 1 since s[0] refers to "s1".

please clarify my doubt.
 
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
s[0].length() means, its the length of the very first element, which in this case is "s1" of two characters width ( s & 1 ).

In the following case, in which the first element is an array,


[ April 24, 2007: Message edited by: M Krishnan ]
[ April 24, 2007: Message edited by: M Krishnan ]
 
Ranch Hand
Posts: 558
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Siva,

s[0].length will not compile.

1) length Usage: String s[] = { "Hi" ,"How" ,"are", "you"};

s.length --> 4 // .length applicable on arrays

2) length() Usage:

s[0].length() --> 2 // .length() is method defined in String class.
s[0].length --> wrong usage // s[0] is not an array instead a String
 
lowercase baba
Bartender
Posts: 12628
50
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
s[0].length()

go through this as follows:

s - look at the s array

s[0] - look at the 0th element of this array. that happens to refer to a string, as you said, "s1".

so now what we have is

"s1".length()

which is asking for the length of this string. it's 2.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!