Win a copy of Bad Programming Practices 101 (e-book) this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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: 12626
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.
 
Uh oh, we're definitely being carded. Here, show him this tiny ad:
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!