constructor calling in array creation - java

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.

Related

Array Creation Method with a 'name' Parameter: Scope Error

I'm creating some helper methods for a class project. One of the methods I wanted to create was a simple create an array of type int, called 'name', of 'size' size. The problem arises in the body of the method where I try to use the 'name' parameter to create the array.
public int[] createArray(String name, int size){
int[] name = new int[size];
}
In addition to getting a "Variable 'name' is already defined in the scope." error, I think the issue is that I can't use a variable in the construction of an array. If that's the case, should I not be using 'String name' as a parameter here? Is there some sort of parse/conversion I can do? Conclusively, what do I have to use/do to pass a parameter from the method call into "int[] _____ = new int[size];"?
I'll probably just make the 2 arrays I need normally in the main method, but I wanted to learn what I was doing wrong.
Best,
Corey
Rename you variable name in
int[] name = new int[size];
to
int[] otherName = new int[size];
and it should work fine. Since there is another variable with the same name in the scope because of String name used as your argument to the method.
Also in case you want to use the parameter to actually name your array variable, then you would probably be trying to modify the source code during its runtime, which you can't. That said, the variable String name doesn't seem useful in the method anymore.
What you try to do is impossible (unless you resort to "reflection" which I wouldn't recommend to a relative beginner).
You want to create an array variable with a name that you want to decide at runtime. You want to do something like
int[] array1;
int[] array2;
createArray("array1", 17);
createArray("array2", 25);
The variable names array1 and array2 exist at compile time. When the program runs, they are no longer available (to normal Java code). The "array1" and "array2" parameters that you want to pass to the createArray() method are strings, and the Java runtime will not associate the characters in these strings with the array variables.
The Java way for the thing you tried to achieve is:
int[] array1 = createArray(17);
int[] array2 = createArray(25);
private int[] createArray(int size) {
return new int[size];
}

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.

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

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.

Is it an Anonymous Array if the resulting array is assigned to a variable

(I am studying for the Java Associate Exam OCJP 7)
A question asked to select examples of illegal initializations.
One of the answers was:-
int [] k= new int[2]{5,10};
The explanation said that when creating an anonymous array it was illegal to specify the size of the array.
From what I know this is NOT an anonymous array as it is named "k".
Calling a method such as :-
operateOnArray(new int[]{5,10});
Would have been an example of an anonymous array since it is not declared.
I can see that the "2" makes it illegal - but that does not make it anonymous,
Please can someone advise me?
Mmmm... from what I've been taught (and also from what I've read), the definition of an Anonymous Array is: "Array without any name, it is an array just for create and use it". And since it does not have any name, you should not be able to reuse that array.
The best references I had when I prepared for the OCJP was:
anonymous int array : new int[] { 1, 2, 3, 4};
anonymous String array : new String[] {"one", "two", "three"};
anonymous char array : new char[] {'a', 'b', 'c');
You can notice that (and also you already know) these type of arrays have the creation and initialization at the same time (as you initialize them in the same line you create them using the new() keyword without assigning to any variable and you would not be able to reuse it later).
So, from what you have mentioned, when you assign an array to a variable, even when you create it and initialize at the same line, it is being assigned to a variable so it is able to be reused later, it is not anonymous, it can be referenced, so I wonder why in the examples of "anonymous arrays" you see something like:
int [] k= new int[2]{5,10};
Anonymous means "not known by name" which is not the case in the line you specified since the array is assigned to a variable called "k". However, this one shows the property of anonymous array-object creation which is pointed by a reference variable "k", so if we write just "new int[]{1,2,3};" then this is how anonymous array-object can be created...
When I prepared for OCJP 7 I read many articles from this page, I would recommend it to you to go deeply in Java in the future :)
Reference: http://javarevisited.blogspot.com/2012/01/anonymous-array-example-java-create.html
You can find also good examples and articles there :)
I think it will be like an anonymous method...
The anonymous array would be like myListView.setAdapter(this, new String [] {"Peter", "Paul", "Marry"});
Where the (new String [] {"Peter", "Paul", "Marry"}) is the anonymous array :-)
So a normal (not anonymous) array would be decleared (maybe in onCreate) like
String [] array = new String []...
While the anonymous one won't be decleared before usage...
It is not so clear what exactly is the question, but I get the point clearly that there is a confusion with regards how to correctly use the concept of an anonymous array in Java. You can only declare an anonymous array as an argument to a function. All else attempts to declare anonymous array not in this context, failed. This quick video shows it:
anonymous array as argument to function
If you see this part of the code:
new int[2]{5,10}
in the first declaration and then
new int[]{5,10}
from the second declaration. It's basically the same
So, a declaration like:
new int[]{5,10}
is an anonymous array, no matters what happen next. If you do not set it to a variable, it remains anonymous.

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;
}

Categories