I have a basic doubt, when I was analyzing object and reference.
int a; //here we are creating an object a of type integer
Integer b=new Integer(); // here we are creating a reference variable b points to an object of type Integer in heap.
What is the advantage of each one ? where to use "int a" and the other one?
In case of arrays:
int[] a=new int a[5];
if "int a" is possible why " int a[5] " is not possible, because the below code throws null pointer exception:
int a[5];
a[0]=10;
System.out.println(a[0]); //gives null pointer exception
The code works well when:
int[] a=new int[5];
a[0]=5;
System.out.println(a[0]);
Why in case the former case its excepting a reference needs to be created when "int a" works?
int a is declaring a primitive variable, called a, that is of type int. Primitives are not objects, but arrays are of primitives are objects.
Arrays are objects, but they are a special type of object that Java has special syntax for using. When you are using int[] a you are declaring an object, called a, whose type is an array of ints. When you assign it with a = new int[5], it is as though you are calling a constructor in a special way. It is as though you were really calling some constructor and passing the size as a parameter: a = new IntArray(5) or something. Java gives you special syntax so that this type of construct is not needed.
Similarly, when you say a[0] = 5, it is as though you are calling a method on your object a, but Java gives you special syntax for this. It's almost like you are calling a.setValue(0, 5), but Java gives nice syntax so that this type of thing is not necessary either.
So if you tried to declare int a[5], that would be like trying to declare a variable using new IntArray(5)...that doesn't make sense as a variable declaration. You would basically be using a call to the constructor to declare a variable, which wouldn't make much sense.
This is because int isn't Object - it's primitive type and it cannot be null.
Integer is object and reference can be null.
int a[] = new int[5]; //is legal and all elements has 0
Integer a[] = new Integer[5]; //is legal too but in this case you have null
Common case of using Integer is Collections, in this case it has to be object, e.g:
List<int> list = new ArrayList<int> // Illegal
List<Integer> list = new ArrayList<Integer> // OK
int is the primitive type that Integer uses. int is more efficient as Integer is a class with methods, thus uses more memory.
The first array example doesn't work because with just int a[5]; you're merely creating a reference, not the actual values (thus throwing a NullPointerException when you try to use it). With int[] a=new int[5]; you create the actual array to use, so after that you can use the values.
a) First of all, int a; doesn't declare an object. it's just a var to hold an integer.
b) Always use primitive datatypes over wrapper classes to avoid the overhead of creating an object just to represent a primitive.
c) int a[5] is a reference to an array of 5 integers pointing to null, hence a[0] makes no sense
d) the code int[] a = new int[5]; works properly because you've initialized a to an array of 5 integers, each of which will have a default value of 0.
e) int a is a primitive data type declaration hence it doesn't necessarily need to be initialized unless it's a local variable. int[] a, however, is an int array reference, and since arrays are Objects in Java, you've to initialize before using them.
int a[5]; is understood implicitly as int a[5] = null; (declaration is invalid in java). int[] a=new int[5]; creates an array of length 5 with each element of the array containing a default value of 0. Integer[] a = new Integer[5] creates an array of Integer of length 5, all elements have null as default value.
There are ways to initialize an array (Just an extra note). Example:
int a[] = {1, 2, 3, 4, 5};
This creates an array of int of length 5, and each element (counting from 0) are assigned values from the braces {} starting from the left to the right.
Furthermore, int is a primitive type, so JVM creates a memory space for the size of int (e.g 4 bytes int) while Integer is an Object so JVM creates a memory space to hold the full object of Integer (which is bigger than the memory space of int).
where to use "int a" and the other one
Use Integer if you need to use Generics (since you can't use primitive types in generics but int[] or primitive arrays are allowed) or need functions from the Integer class. Else, storage of values to a persistent storage, use int.
Related
This question already has answers here:
Assigning Array to new variable, changing original changes the new one
(4 answers)
Problem with assigning an array to other array in Java
(4 answers)
How can an integer array be a reference type?
(2 answers)
Closed last month.
public class Alle {
public static void main(String[] args) {
int[] arr = {1,2,3,4};
int [] y = arr;
y[0] = 15;
System.out.println(Arrays.toString(arr));
}
}
The Output is 15,2,3,4 but why? I never changed "arr".
In Java, arrays are objects, not primitive types. When you are assigning link to arr to the new variable, y still points to arr, so you are actually changing arr. Thats it. But if you want to copy the array, you can use this method: Arrays.copyOf(int[] original, int newLength)
Let's assume you have a son, named jackson.
You introduce him to your friend, "Hey Friend, meet my son Jackson".
The friend says, "Hi Jackson, I'll call you jake."
Later that friend calls him and says, "Hey Jake, here take a handful of candies".
your son Jackson comes to you, and you see he has a handful of candies.
But how ? You never gave jackson candies. But your friend gave to jake.
Makes sense ?
In your code, the arr, and the y are exactly the same entity, not equal, not copy, but the exact same Object. So you make changes at one place, it'll show at the other one as well.
When you initialized the integer array viz arr in your case, it allocated a space in the heap to your reference variable arr when you executed the following code:
int[] arr = {1,2,3,4};
This arr is referring to an integer array in heap as arrays are objects in java.
Now when you performed the following code:
int [] y = arr;
This created one more reference variable y which is referring to the same object in the heap that your reference variable arr was referring to, that is why whatever changes you make through your reference variable y or reference variable arr will reflect the changes of the object created in the heap as they are referring to the same object.
If you want a new object allocated to your reference variable y that resembles the elements of your arr array then you can clone it. The following code represents it:
public class Alle {
public static void main(String[] args) {
int[] arr = {1,2,3,4};
int [] y = arr.clone(); //change here
y[0] = 15;
System.out.println(Arrays.toString(arr));
}
}
This gives an output:
[1, 2, 3, 4]
Hence your arr array is not affected this time.
In the below code, EX1 and EX 2 prov the homogeneous theory but in EX3 it holds multiple types values. So then, how we can say arrays are homogeneous? What is the exact theory behind this?
public class Test {
public static void main(String[] args) {
// Ex 1
int [] intArr = new int[5];
intArr[0] = 1;
intArr[1] = 2;
// Ex 2
int [] intArr2 = new int[5];
intArr2[0] = 1;
intArr2[1] = "ss";
// Ex 3
Object [] objArr = new Object[5];
objArr[0] = 1;
objArr[1] = "ss";
objArr[3] = new Object();
}
}
There are a two concepts here: inheritance and auto-boxing
Inheritance -
A String inherits from Object and hence is an Object. This means that String gets all methods and properties defined in the Object class automatically at compile time. It is an Object plus additional stuff that is specific to the String. However, it can be viewed by Java as an Object because it is an Object. When it is added to the array, it is added as an Object, not as a String. That is because the Array is defined as an Array of objects.
char a = "ss".charAt(1); // Legal as charAt(..) is a method in the String class
Object [] objArr = new Object[5];
objArr[1] = "ss";
objArr[1].charAt(1); // Not legal because charAt(..) method is not defined for Object
See Oracle Tutorial.
Auto-Boxing -
Java performs a shortcut known as auto-boxing to a automatically convert primitives to a special set of wrapper Classes all of which inherit from Object. Hence, because of auto-boxing and inheritance, assigning a number to an Object will convert that number to an Object as well.
Hence, everything added to the array was added as an Object. It is true that the objects in the array may be classes that inherited from Object. However, as far as the array is concerned, they are of type Object. Even so, if you were to pull it out of the array and cast it as an Integer, you could do so. It still carries the Integer information with it but that information in not available without a cast. From the array's point of view, it is only an Object.
See Oracle Tutorial.
Can someone help me understand this piece of code?
int[] A = new int[2];
Object x = A; // All references are Objects
A[0] = 0; // Static type of A is array...
x[1] = 1; // But static type of x is not an array: ERROR
According to the Oracle Java SE site:
In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.
I understand that arrays can be assigned to Object type variables, however, my confusion perhaps lies in the concept of reference. When we say Object x = A, we are saying that x has a reference to the array A. However, my confusion lies in x[1] = 1. Why is it an error such that the x is considered an Object even though it is referencing an array? Do I think of [] as a kind of method that is only accessible in the "array" class?
While I would not unnecessarily throw away type information, you can use Array#setInt(Object, int, int) to access an int[] through an Object. That is,
Array.setInt(x, 1, 1); // x[1] = 1;
would work.
arrays are objects - This means that array for any type (reference or primitive) are the child class for Object class.
By using parent reference instance of child class can be accessed. Therefore the statement Object x = A; is syntactically correct.
By using Child reference child related methods/implementations can be accessed. Therefore the statement A[0] = 0; is syntactically correct.
By using parent reference child related methods/implementations cannot be accessed. Hence the statement x[1] = 1; is syntactically incorrect.
I was doing some exercises on arrays, and I was prompted to return a reference to an array after copying it element by element. What does this exactly mean?
My code is the following:
public static int[] cloneArray(int array[])
{
int[] arraycopy = new int[array.length];
for(int i = 0; i < array.length; i++)
{
arraycopy[i] = array[i];
}
return arraycopy;
}
I don't know what I should be returning though as a "reference": should I return an array of ints or an int? Whenever I try to print the array, I get a weird combination of characters and numbers (unless I invoke Arrays.toString()).
"Return a reference to an array" just means "return an array".
Java only returns values, which are either primitives or object references (ie for objects, the value is a reference).
Although Java is based on C, it doesn't sully itself with pointers etc like C does.
In Java, arrays and objects do not act like primitive types such as int. Consider the following code:
public class MyClass {
public static int method1(int ar[]) {
int x = ar[1];
ar[1] = 3;
return x;
}
}
Now suppose that somewhere else, the follow code is executed:
int abcd[] = new int[3];
abcd[0] = 0;
abcd[1] = 1;
abcd[2] = 2;
int d = MyClass.method1(abcd);
System.out.println(abcd[1]);
What would be printed? It's not 1, but 3. This is because the method was not given the data in the array, it was told the location of the array. In other words, it was passed a reference. Because it was using a reference, changing the value of an array index changed its value in the code that called it. This would not have happened if method1 had taken an int as an argument.
Basically, in Java, methods do not accept arrays as arguments or return arrays. They only use references to arrays. The same goes for objects (except for Strings, which are passed by value).
In Java, Objects are only accessed by reference. Just return the Array object.
is declaring/initializing primitives the same as creating new objects? from what i know when we create primitives, we also creating wrapper classes for them. im implementing on java btw.
No, assigning primitive values does not create any objects.
What you might be referring to is the fact that primitive values can be auto-boxed into the corresponding wrappers, when they are used in a context where a reference type (a.k.a "an object") is required:
int i = 13; // this line does not create an object
Integer i2 = i; // at this line 13 is auto-boxed into an Integer object
char c = 'x'; // again: no object created:
List<Character> l = new ArrayList<Character>();
l.add(c); // c is auto-boxed into a Character object
Also, I'll try to describe the difference between declare and initialize:
int i; // an int-variable is declared
int j = 0; // an int-variable is declared and initialized
i = 1; // an int-variable is assigned a value, this is *not* initialization
A variable is "declared" when it is created for the first time (i.e. you specify the type and name of the variable). It is initialized when it's assigned a value during declaration.
No, declaring and initializing a primitive variable does not create an object. Let's take a class with two integer values - one using the wrapper type and one not.
public class Foo
{
private int primitive = 10;
private Integer wrapper = new Integer(10);
}
The value of the primitive variable is just the number 10. The value of the wrapper variable is a reference to an Integer object which in turn contains the number 10. So an instance of Foo would keep state for the number in primitive and the reference in wrapper.
There are wrapper classes for all primitive types in Java, but you don't use them automatically.
Creating a primitive DOES NOT also create a wrapper class for them.
As for your original question: Declaring/initializing a primitive will create it on the stack, whereas declaring an object will allocate a variable to hold a reference to an object. Initializing the object will allocate it on the heap.
Answer: No.
Check this out: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html
No. Primitives are not objects in java.