File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes String.length() vs. Arrays.length Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "String.length() vs. Arrays.length" Watch "String.length() vs. Arrays.length" New topic
Author

String.length() vs. Arrays.length

showbit guppta
Greenhorn

Joined: Sep 09, 2007
Posts: 3
Hi to all
My question is that i want to know that as Arrays class has a static field length that stores the length of the array while initializing, which can be fetched later but for the same String class has a method length().Why??
as both arrays and string instances are immutable.So once string is initiallized its length can't be changed.So why we dont have a lenth field alike as we have for Arrays

Thanks in Advance


SCJP 1.4 -- 93%
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38340
    
  23
Welcome to the Ranch. Sounds more like a beginners' question.

Maybe . . . because different people designed String and arrays at different times.
Maybe . . . because classes use methods for their attributes.

But Strings have a length and Lists have a size.

Just one of those things which we have to get used to
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Strings use arrays internally. If Strings also would use a field to store their length, the information would actually be duplicated - once in the array itself, and once in the String's field.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38340
    
  23
Quoted by Ilja Preuss
Strings use arrays internally.
Yes, I had quite forgotten that.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[showbit guppta]: as Arrays class has a static field length that stores the length of the array while initializing

In Java, arrays are not classes. There is a class called Arrays, and another class called Array, but they have nothing to do with your question. The length of an array is absolutely not static in any way. Technically it's not a field either, but it does generally look and act like one, for most purposes (unless you use reflection).

[showbit guppta]: as both arrays and string instances are immutable.

Arrays are not immutable. The length of an array is immutable, but arrays in general are not.

----

As for the intended question, I think Campbell's first answer is the most relevant. If arrays, Strings, and collections were all redesigned today with what Sun engineers know now, and with plenty of time to carefully coordinate everything together - then I'm pretty sure that either all three would have a length() method, or all three would have a size() method. The inconsistency between length, length(), and size() is one of many errors that were made when Java was created. It's a minor error, and too much trouble to fix now - it would require Sun to break a lot of existing code if they made these three things more consistent. So we just live with the inconsistency.


"I'm not back." - Bill Harding, Twister
Sylven Yip
Ranch Hand

Joined: Aug 30, 2007
Posts: 42
.length is a property(is it the right word:confused of array.

String is a class,not an array,you can not visit the char array inside.so you can only get length by method invocation.
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

String is a class,not an array,you can not visit the char array inside

String#toCharArray


[My Blog]
All roads lead to JavaRanch
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

Which makes a copy of the internal array.

Face it, without evil tricks such as accessing the field through reflection, there is no way to modify it.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
showbit guppta
Greenhorn

Joined: Sep 09, 2007
Posts: 3
Thanks four ypur response, I just want to know that in a code
int[] nValue = new int[5];
nValue.length;

what length signifies? and to which object this int array is associated with?
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

Originally posted by Jim Yingst:

----

As for the intended question, I think Campbell's first answer is the most relevant. If arrays, Strings, and collections were all redesigned today with what Sun engineers know now, and with plenty of time to carefully coordinate everything together - then I'm pretty sure that either all three would have a length() method, or all three would have a size() method. The inconsistency between length, length(), and size() is one of many errors that were made when Java was created. It's a minor error, and too much trouble to fix now - it would require Sun to break a lot of existing code if they made these three things more consistent. So we just live with the inconsistency.


Perfect and convincing explanation Jim Yingst

Thank you


Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Jim Yingst:
Technically it [the array length] 's not a field either, but it does generally look and act like one, for most purposes (unless you use reflection).


The Java Language Specification disagrees with you:

from http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#10.7

The members of an array type are all of the following:

* The public final field length, which contains the number of components of the array (length may be positive or zero).
* ...


What happens when you try to access it via reflection?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

Originally posted by Ilja Preuss:


What happens when you try to access it via reflection?

I have seen code that can access the "classes" Vector that ClassLoaders use for storing the classes to read the classes loaded at a specific moment. This is a private field of the ClassLoader, but the code could make it accessible and read its values.

If you could do the same to the "value" char[] of String you could, theoretically, modify the unmodifiable

Keep in mind that this is by no means the way to treat Strings.
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

Originally posted by showbit guppta:
Thanks four ypur response, I just want to know that in a code
int[] nValue = new int[5];
nValue.length;

what length signifies? and to which object this int array is associated with?


Howdy showbit guppta,

Welcome to JavaRanch

for your question, you may plese have a look at this thread.

Hope that helps!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

Originally posted by Rob Prime:

I have seen code that can access the "classes" Vector that ClassLoaders use for storing the classes to read the classes loaded at a specific moment. This is a private field of the ClassLoader, but the code could make it accessible and read its values.

If you could do the same to the "value" char[] of String you could, theoretically, modify the unmodifiable

Keep in mind that this is by no means the way to treat Strings.

I found the code again:

Terrifyingly, the output is the following:

I knew that when you create a string using another string they share the same array, but this code shows the dangers of abusing reflection. String are unmodifyable indeed!
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Ilja]: The Java Language Specification disagrees with you:

Good point, I forgot that. I was partly confusing it with the .class notation, which looks like a static field, but isn't. But also:

[Ilja]: What happens when you try to access it via reflection?

When you use getFields() or getDeclaredfields() on an array-type Class instance, you get an empty array. If you use getField("length") or getDeclaredField("length"), you get NoSuchFieldException. It's not the first time that reflection gives a different answer than the specification, unfortunately.

[Rob']: this code shows the dangers of abusing reflection.

Yup. Pretty much any time we discuss immutability in Java, we mean "unless you use reflection". I believe some older versions of Java prevented you from using reflection to change final fields, but this was later changed - either to allow for deserialization using reflection, or to enable System.setOut() and setErr() to change the final fields System.out and System.err. Which probably should never been exposed as public members of the API in the first place, or never made modifiable by other methods - more strange decisions from Java's early days.

Note that even when Java prevented reflection from altering final fields, that doesn't prevent the particular String modification shown in the code above, which takes advantage of the fact that arrays are always mutable, and reflection doesn't prevent you from accessing private data (unless your security manager settings are different than the defaults, or unless you're using an Applet, which has more restrictive default security settings).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String.length() vs. Arrays.length