• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Arrays

 
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Posts: 13082
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic