What's the difference between length and length()? [duplicate] - java

This question already has answers here:
length and length() in Java
(8 answers)
Closed 6 years ago.
I've noticed that when doing the length of an array you write something like:
arrayone.length;
However, for such things as array lists or a string, you write a bracket on the end, such as the following for the length of the String:
stringone.length();
What is the key reason for this and how do you know when to put the brackets or now?

.length;
directly accesses a field member.
.length();
invokes a method (i.e. an accessor) to access a field member.
in the case of String, this is to be expected since it's immutable.

Arrays are handled differently than Strings or ArrayLists or anything else that can be counted in Java. An Array is pretty much a native type and it's length can never be changed after it is initialized, so there's no need for encapsulation. The length variable can be directly exposed with no side effects.
The reason why String uses a method instead of a variable is because it internally uses a char[] that it doesn't want to expose publicly (for immutability/encapsulation), so it wraps the length variable in a length() method. It's the same reason ArrayList has a size() method instead of a length variable.
The only time you'll use the variable instead of the method is with arrays. Everything else will be methods. That is, you'll use the brackets for everything except arrays.

The only true way to know when to use which one is experience. Though an IDE with autocompletion will usually help you out when you don't remember.
For the most part (not always) array.length, System.out, and System.err are the most common 3 you'll run into that are actually member access instead of method calls.

int[] myArray = new int[10];
String myString = "hello world!";
List<int> myList = new ArrayList<int>();
myArray.length //gives the length of the array
myString.length() //gives the length of the string
myList.size() //gives the length of the list
Its very likely that strings and arrays were designed at different times and hence ended up using different conventions. One justification is that since Strings use arrays internally a method length() was used to avoid duplication of the same information. Ultimately this is just an inconsistently that evolved that would definitely be fixed if the language were ever redesigned from the ground up. :D

The main difference is that in the A) first case its Array Type for example int[], Object[], double[], ect.. that has a public field called lenght and the B) second case is a Object String that has a function called length(), the function could of been called getLength() or something else. The array type public field length is probably a hangover from C++ way of doing things.
Array Types have the following:
The public final field length, which contains the number of
components of the array (length may be positive or zero)
The public method clone, which overrides the method of the same name
in class Object and throws no checked exceptions
All the members inherited from class Object; the only method of
Object that is not inherited is its clone method
Take a look at this, Array Types.

.length() is a method of a String class and which returns the number of characters in the string.
.length will give the number of elements stored in an array.
public class length
{
public static void main(String args[])
{
String x="test";
int a[]={1,2,3,4};
System.out.println(x.length());
System.out.println(a.length);
}
}
// output
4
4

length is a pseudo-data member reference, and only works for (small-a) arrays (ignoring classes that you may define that implement the member).
Everything else is an object of a class, and all JDK classes that have this concept define either length() or size() instance methods. (I do wish they'd been consistent and picked one or the other, but that's water over the bridge.)

Array.length is a property of that Array, similar to a variable reference.
ArrayList.size() is an actual method call to the array list object.

Related

why need of "println(char[] x)" when there is already "println(Object x)" - java

I was reading about println function and I came across that there is println(char[ ] x) as well as println(Object x)
https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println(char[])
My question is that: As arrays in java are object so what is the need to specifically overload println() with char[] whereas rest arrays like int[] etc. uses the println(Object x) overloaded function.
println(Object x)
if you use it to print a char array (the char array is an object), it won't print the content but the objectClass#hashcode style. You can test it yourself to see the exact output.
Because they are implemented differently.
println(Object)
will (after checking for null, etc), call the parameter's toString() method and display the result of it.
The toString() method of an array is not useful: it will give you the array type and the hashcode of the array. So the overloaded form gives a more useful implementation in the case of a char[] parameter.
Note that, with most object types, the toString() method can be overridden (so overloading the println(...) method for every possible type is not necessary (or possible...). However, the toString() method cannot be overridden for arrays, so there is benefit to overloading println in this case.
Because it prints the char array as a string and otherwise prints in object form, and seeing the contents may be more convinient. You can try casting it to object first and see the difference.
Because print/ln(char[]) handles the actual printing of characters, toString() of the array object itself still provides the usual type+hash output, regardless of being an array of characters
char c[]={'a','b','c'};
Object o=c;
System.out.println(c);
System.out.println(c.toString());
System.out.println(o); // *
System.out.println(o.toString());
The * thing is interesting (and this is why I post at all, since the rest is already there in other answers) because it demonstrates that Java has single dispatch: the actual method to be invoked is decided in compilation time, based on the declared type of the argument(s). So it does not matter that o is a character array in runtime, in compilation time it seems to be an Object, and thus print/ln(Object) is going to be invoked for it.

Why java allows zero length index(in middle) array?

javac allows below syntax,
int[][][] i = new int[4][0][2];
which has zero length index that prevents access beyond.
1) There is no way to access third dimension. zero length dimension as last dimension(int[][][] i = new int[4][2][0];) looks fine.
2) It is not possible to write an initialiser for a multi-dimensional array with a zero length dimension unless that dimension is the last( for instance int[2][3][0]).
Why java allows such syntax?
Note: this question has nothing to do with int[0]
Because nothing in the multianewarray bytecode instruction prevents you from doing so.
There is really no better answer than that... The fact is that for any X, even if X is a primitive, then X[] is a class, X[][] is a class and so on; and you are free to choose the "dimensions" of the array.
Note how declaring a X[n][] and a X[n][m] array differ: in the first you'll declare a anewarray of X[] whereas in the second you'll declare a multianewarray of X.
Of course, in X[m][n][p], there is no possibility to ever have a "third dimension" (p) if n is 0, but... Well, the programmer knows what he's doing, right?
Just another bizarreness of arrays in the JVM... Think nothing of it except that "it can happen" ;)
I agree with #m0skit0 - I think this is a duplicate questions. However I will give a brief answer anyways.
Basically its an alternative for null. Consider simply, you have a method that returns an array, but it has no value to return. You could return null, but then you have to check for null in your code. On the other hand, you could return a 0 length array. Code such as the follows would automatically be skipped.
for(int p = 0; p < array.length; p++) {
So you can do perfectly acceptable stuff like:
public static final int[][][] EMPTYARRAY = new int[0][0][0];
note also things a much worse than you suppose because this is also legal:
public static final int[] SCREWEDARRAY = new int[-1];
which causes a runtime error:
java.lang.ExceptionInInitializerError
Caused by: java.lang.NegativeArraySizeException
First of all, it's not just in "the middle". You can easily define a one dimensional array just as easily:
int[] a = new int[0];
Second, an array with zero length is a bit like an empty collection. It's a legal data structure which might be returned by a method, but which happens to be empty.

What is the difference in using .length and .length() to find length [duplicate]

This question already has answers here:
How can I get the size of an array, a Collection, or a String in Java?
(3 answers)
Closed 8 years ago.
The former (.length) isn't even a function , how does it return length?
The reason length isn't function in an array is that it is a field. In particular, a public final one as specified by the Java Language Specification section 10.7.
While ArrayList (ad Vector of the 1.0 libraries) have a length() method, the key thing to realize is that this value can change. You call add(Object o) on a Vector, and you've changed its length.
On the other hand, you can't change the length of an array.
Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.
(from JLS Section 10.2 - Array Variables)
And thus, the simplest thing that works is to make the length a field. One that is public and can't change.
Realize in the Java 1.0 days, HotSpot wasn't quite as advanced as it is today. It wouldn't be able to do all the optimizations that it can now with inlining methods. And thus, to make array access that much faster for situations that needed it, its a field.
Related reading on Stack Overflow: length and length() in java

Use of Array of length 0? [duplicate]

This question already has answers here:
Why does Java allow arrays of size 0?
(9 answers)
Closed 9 years ago.
char[] arrNew = new char[0];
System.out.println(arrNew.length); // length = 0
arrNew[0]='c'; // ArrayIndexOutOfBoundsException .
In the above code as you can clearly see there is no point in having an array of size 0. As far as I can see there is no practical usage of 0 size array. Can someone explain why the compiler allows creation of 0 length array. And also how is a 0 length array different from an array initialized to null? (i.e, is memory allocated to it as if it were a normal array?). I am sorry if this question seems stupid.
We can return an empty array instead of null from a method, this is called Null object design pattern. Consider the following code
Person[] res = find(name);
for(String e : res) {
System.out.println(e);
}
if find() does not find anyone it returns an empty array. If find returned null then code would need to treat it as a special case.
We should keep in mind that empty array is immutable so it is logical to use a singleton instead of creating it each time
private static final Person[] NULL = new Person[0];
Person[] find(String name) {
...
if (notFound) {
return NULL;
}
...
It's best not to return null from a method that returns an array type. Always returning an array, even if the array has zero length, greatly improves the generality of algorithms. If you anticipate that your methods will return zero-length arrays frequently, you might be concerned about the performance implications of allocating many such arrays. To solve that problem, simply allocate a single array, and always return the same one, for example:
private static final int ZERO_LENGTH_ARRAY[] = new int[0];
This array is immutable (it can't be changed), and can be shared throughout the application.
So in Null Object pattern, a null object replaces check of NULL object instance. Instead of putting if check for a null value, Null Object reflects a do nothing relationship. Such Null object can also be used to provide default behaviour in case data is not available.
Compiler allows because that code its within the rules of the language.
And no, they are both not the same. If it were the same, you would get a NullPointerException rather than ArrayIndexOutOfBoundsException.
It can be of use, if you have a function returning reference to array, and if you have nothing to return then you might consider its better to return 0 length array than a null. If null were returned you would have to check this function for both null value, and if range is correct, if you return 0 length array - then you might only check the if range is correct - ie. in for loop.
Zero-length arrays are rarely "required," but are more often used simply to show that there is no data being passed to a method.
in java the memory allocation can be dynamic in nature. The java array enables the user to store values of the same type in contiguous memory allocations. Arrays are always a fixed length abstracted data structure which can not be altered when required. It just occupies the memory.

Why is string.length() a method, and int[].length a property? [duplicate]

This question already has answers here:
length and length() in Java
(8 answers)
Closed 10 years ago.
Why is String.length() a method, and int[].length a property (see below)?
int[] nums = {2,4,7,12,43};
String phrase = "Hello, world.";
System.out.length(nums.length);
System.out.length(phrase.length());
I don't think there has to be a good reason, and I think there could be many reasons.
But one is that by making String#length() a property, it can be declared in an interface instead (in this case CharSequence). Interfaces cannot declare public instance fields.
This is what the String::length() function looks like:
public int length() {
return count;
}
So essentially count could've been called length and made public to be similar to arrays (it is final after all).
It was probably just a design decision. There may have been some contributing factors that we can speculate about (one of which could've been the CharSequence thing mentioned by Mark Peters).
Because String is not an array as such. The designers of Java designed arrays (which are objects) to have a public field named length.
On the other hand, a String has a method which gives the length instead. In general it is a more conventional approach to make member fields private and use methods to access them, but in the case of arrays it is not.
They're different objects with different signatures as far as you are concerned. A String is not a char[] (although internally it might be implemented that way).
No particular reason, I think. In fact in C#, a very similar language, String.length is a property http://msdn.microsoft.com/en-us/library/system.string.length.aspx. But take a look at what C# designer has to say about this design:
The Length property returns the number of Char objects in this instance, not the number of Unicode characters.
The reason is that a Unicode character might be represented by more than one Char. Use the
System.Globalization.StringInfo class to work with each Unicode character instead of each Char.
Why int[].length a property?
Arrays are special objects in java, they have a simple attribute named length which is final.
There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.
The public final field length, which contains the number of components of the array. length may be positive or zero.
The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].
A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
All the members inherited from class Object; the only method of Object that is not inherited is its clone method.
Resource: JSL 10.7
Why String.length() a method?

Categories

Resources