How to find int[].length on Java Documentation ? [duplicate] - java

This question already has answers here:
Where is array's length property defined?
(7 answers)
Closed 7 years ago.
I am just curious ! When I use an int table, I can get to .length, which returns the length of the current table. For exemple :
int b[] = {0,1,2};
int l = b.length; // which is equal to 3
What I want is to get to ".length" in the Java documentation. In order, to figure out if ".length" is a static method or instance variable , and things like that.

From the JLS
10.7. Array Members
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.
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.

Related

length field in array

As well known in java String class there is a length() method (why not getLength()?). If we look into this method we can see:
public int length() {
return value.length;
}
and value is an array. Why do we access a field? I know that this field is final and nobody can change it, but still what about polymorphism? And where can I see that field? In which class? I've found java.lang.reflect.Array,
but there is no such field as length.
Where can i see that field? In which class?
If you are looking for char array declaration
That's a char array declared on top. You can see that.
The value is used for character storage.
112
113 private final char value[];
And if you are looking for length field of an array
Array's are the part JVM implementation. You need to get the source code of JVM to analyze/see it.
And why we access a field?
That's how the length of an array can be known .
How about polymorthism? I know that this field is final and nobody can change it, but still what about polimorthis?
Never heard of it and if you mean Polymorphism, nothing to do here about it.
I think you might be expecting Java to be a pure OO language... It's not... It's a mixture of Objects and primitives. Primitives do not behave like objects and have language level native stuff, like public length fields etc.
Consider the following... a character array... Its length field is NOT a field in the traditional sense, it is baked into the language at the JVM level. This difference means that you cannot use reflection to access it via Field.getDeclaredField(). Java provides a special mechanism for this case - java.lang.reflect.Array.getLength(Object)
Object obj = new char[] { 'a', 'b' };
int length = ((char[]) obj).length; // .length looks like a field access but done by JVM
int lengthViaRelection = Array.getLength(obj);
This is very different from a standard field on a class where reflection can be used.
private static class ClassWithField {
public int length;
}
ClassWithField obj = new ClassWithField();
int length = obj.length; // .length is normal field access
int lengthViaRelection = (int) ClassWithField.class.getDeclaredField("length").get(obj);
value is an array of char (primitive, not java.lang.Character) and arrays of primitive types have a field named length:
final char[] chars = new char[1];
final int length = chars.length;
String is a final class, so extending String is not possible / permitted and the compiler won't let you do so.
The Strings private member(!) value is an array of chars (the primitive). This can be considered an implementation detail and you should not mess with it.
All arrays in Java got a field named length. It is accessible via property-access, there is no need for something like a "getter".
The length field of an array is not static; so each array will have its own field with its own value. The fact that it is readily has nothing to do with polymorphism; it's just a convenient way to find out information about the array.
The class java.lang.reflect.Array does not describe an array; it is a class that provides static methods to dynamically create and access Java arrays. So it is correct that there is no field length in that class.

Java array declaration syntax difference? [duplicate]

This question already has answers here:
Difference between int[] array and int array[]
(26 answers)
Closed 7 years ago.
Is there any difference in declaring array argument in java like:
public void method(Type[] arg) { ... }
and in that way:
public void method(Type arg[]) { ... }
Just curiosity...
It is better practice to place them after the type, it is for understanding purposes. Also note that:
String[] firstArray[], secondArray;
Here you have firstArray variable referring to a two dimensional array and secondArray variable refering to an one dimension array;
No difference.
In SCJP Sun Certified Programmer for Java 6:
When declaring an array reference, you should always put the array brackets immediately after the declared type, rather than after the identifier (variable name). That way, anyone reading the code can easily tell that, for example, key is a reference to an int array object, and not an int primitive.

Array-instance of class [duplicate]

This question already has answers here:
How do I declare and initialize an array in Java?
(31 answers)
Closed 8 years ago.
I found an instantiation wich I do not understand how works.
The instantiation looks like this:
public static Class instance[] = new Class[arraySize];
If my guessing is right, the instance is an array?
How will this work?
This declares an array of Class objects references. It is equivalent to the other syntax of [] after the type.
You would access it just like a normal array:
instance[0] = ...
instance[1] = ...
public static Class instance[] = new Class[arraySize];
public is the access modifier. This one means that this variable is visible in your entire project
static means that this variable is a "class" field it means that it belongs to the entire class and you can access it by ClassName.nameOfTheVariable or if you are accessing it from inside of class it is declared you could use just nameOfTheVariable.
Class in this context is a type and you should treat is as a type of object
[] means that this is an array you could also write Class[]
= is assignment operator
new is the word that annunciates that there will be memory allocation and constructor invokation after it
After new there is initialization of array of arraySize length.

Java Memory, Pass-by-Value, Pass-by-Reference [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is Java pass by reference?
I have a question about passing by value and passing by reference in java.
I have a "Graph" class that I wrote to display a long array of doubles as a graph, The (simplified) constructor looks like this.
private double[] Values;
public Graph(double[] values) {
Values = values;
}
The array can be quite long and take up a reasonable amount of memory.
Essentially my question is this: If I call the constructor to create a new graph, will the array "Values" be a copy of the array that's passed to it, or will it be a reference?
In my mind, Primitives are "pass by value" and Objects are "pass by reference", which should mean that the array would be a copy. Although I'm aware that this definition is not technically correct.
If I am correct, and the array is a copy, what would be the best way to reduce the amount of memory this class uses, and reference the array from another class?
Would an abstract GetValues() method be a good way of achieving this?
Thanks in advance,
Chris.
While double is a primitive type, double[] is an Object type (array), so, no, the entire array will not be passed to the constructor, instead the array will be passed as "value of a reference". You will not be able to replace the array inside the constructor, but you could, if you wanted, replace individual values in the array.
Java is pass-by-value, period.
See the JLS, 4.12.3 Kinds of Variables:
Method parameters (§8.4.1) name argument values passed to a method. For every parameter declared in a method declaration, a new parameter variable is created each time that method is invoked (§15.12). The new variable is initialized with the corresponding argument value from the method invocation. The method parameter effectively ceases to exist when the execution of the body of the method is complete.
EDIT: To clarify my answer: The types of Java are divided in two categories: The primitives and the reference types. Whenever you call a method (or a constructor), the parameters get copied (because Java is pass-by-value). The primitives get copied entirely and for reference types, the reference gets copied. Java will never automatically deep copy anything, so as arrays are reference types, only the reference to the array gets copied.
It will be a reference of values. Java is Pass-by-value, but what's passed by value is a reference to the array, as the array is an object.
See also this answer, from just a few days ago.
It will be a reference. the parameter values is passed "reference by value", and the reference is attached to Values.
Thus - any cahnge to Graph.Value will also be reflected to values and vise versa.
Array is a reference type, passing by copy applies only to primitive types, which an array isn't. The other reference types include classes and interfaces, by the way.
// Points:
// 1) primitive variables store values
// 2) object variables store addresses(location in the heap)
// 3) array being an object itself, the variables store addresses again (location in the heap)
// With primitives, the bit by bit copy of the parameters, results in the
// value being copied. Hence any changes to the variable does not propagate
// outside
void changePrimitive(int a) {
a = 5;
}
// With objects, the bit by bit copy of the parameters, results in the address
// begin copied. Hence any changes using that variable affects the same object
// and is propogated outside.
class obj {
int val;
}
void changeObject(obj a) {
a.val = 10;
}
// Array is itself an object which can hold primitives or objects internally.
// A bit by bit copy of the parameters, results in the array's address
// being copied. Hence any changes to the array contents reflects in all
// the locations having that array.
void changeArray(int arr[]) {
arr[0] = 9;
arr[1] = 8;
}
// NOTE: when object/array variable is assigned a new value, the original
// object/array is never affected. The variable would just point to the
// new object/array memory location.
void assignObj(obj a) {
a = new obj();
a.val = 10;
}

constructor calling in array creation

int[] a=new int[4];
i think when the array is created ..there will be
the constructor calling (assigning elements to default values)
if i am correct..where is that constructor..
No, there is no such thing. Primitive array elements are initialized to the default primitive value (0 for int). Object array elements are initialized to null.
You can use java.util.Arrays.fill(array, defaultElementValue) to fill an array after you create it.
To quote the JLS
An array is created by an array creation expression (§15.10) or an array initializer (§10.6).
If you use an initializer, then the values are assigned. int[] ar = new int[] {1,2,3}
If you are using an array creation expression (as in your example), then (JLS):
Each class variable, instance variable, or array component is initialized with a default value when it is created
No, there is no such constructor. There is a dedicated opcode newarray in the java bytecode which is called in order to create arrays.
For instance this is the disassembled code for this instruction int[] a = new int[4];
0: iconst_4 // loads the int const 4 onto the stack
1: newarray int // instantiate a new array of int
3: astore_1 // store the reference to the array into local variable 1
From a conceptual level, you could see the array creation as a array constructor, but there is no way for a programmer to customize the constructor, as array types have no source code, and thus can't have any constructors (or methods, by the way).
See my answer here for a conceptual view of arrays.
Actually, creating arrays is a primitive operation of the Java VM.

Categories