Forums Register Login

Arrays

+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
She still doesn't approve of my superhero lifestyle. Or this shameless plug:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 377 times.
Similar Threads
Compare() - from Master Exam
I am Confused !!!!! Pls Help
Sort an array alphabetically and by length
substring(int i)
A small request
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 09:14:51.