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.
Related
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 have a basic doubt, we can increment reference of Integer class object, while not reference of any other class(D class has 1 Integer data member and one parameterized constructor).
Integer x=new Integer(10); x++;
D d=new D(10); d++;
here both x and d are reference still we are able to increment Integer reference while not any other reference. I am missing something very basic, please help me out.
Integer x=new Integer(10); x++;
Here java compiler will do the un-boxing of the object, which converting the Integer object into primitive int. Then the increment operation will be performed. This is only defied for java primitives, the auto-boxing is converting primitive to wrapper object and reverse of it is call un-boxing. This is what is happening here.
The auto-boxing or un-boxing which is an automatic conversion, it is defined for java primitives only. So it can not be performed on other objects. Remember, the object are not just memory references like C or C++ that we can increment them.
This is because of Autoboxing for wrapper classes which was introduced from jdk 1.5. Internally java will convert the integer reference to int and increment it. You can't increment the objects.
Java has no way of overloading operators for arbitrary classes. Thus, D d; d++ is just not available. You can do:
public class D {
private int value;
public D( int v ){
value = v;
}
public void increment(){
value++;
}
}
Now you can do
D d = new D(10);
d.increment();
and d's value will be 11.
According to Oracle Java Documentation, The automatic conversion of primitive data types into its equivalent wrapper type is known as autoboxing and opposite operation is known as unboxing. Whenever we use object of wrapper class in an expression, automatic unboxing and autoboxing is done by JVM.
Integer object;
object = 100; //Autoboxing of int
++object;
When we perform an increment operation on Integer object, it is first unboxed, then incremented and then again reboxed into Integer type object. You can also take a look at How java auto boxing/unboxing works?
Can someone please explain how/why is this allowed in Java?
public class Test {
private int text;
public Integer getText() {
return text;
}
I am basically having the wrapper class as the return type, while I am infact returning a primitive.
Because Java supports Autoboxing and Unboxing in versions 5 and up. That is an example of the former, but the later is equally important (and the reverse conversion). Per the link,
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.
Consider the following code: (From: http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html)
List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
li.add(i);
Although you add the int values as primitive types, rather than Integer objects, to li, the code compiles. Because li is a list of Integer objects, not a list of int values, you may wonder why the Java compiler does not issue a compile-time error. The compiler does not generate an error because it creates an Integer object from i and adds the object to li. Thus, the compiler converts the previous code to the following at runtime:
List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
li.add(Integer.valueOf(i));
Converting a primitive value (an int, for example) into an object of the corresponding wrapper class (Integer) is called autoboxing. The Java compiler applies autoboxing when a primitive value is:
Passed as a parameter to a method that expects an object of the corresponding wrapper class.
Assigned to a variable of the corresponding wrapper class.
From javadocs : Since java 5 Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on.
The java compiler applies autoboxing usually when -
Passed as a parameter to a method that expects an object of the
corresponding wrapper class.
Assigned to a variable of the corresponding wrapper class.
For the sake of performance, not everything in Java is an object. There are also primitives, such as int, long, float, double, etc.
For example java.lang.Integer class :-
It wraps an int.
Has two static final fields of type int: MIN_VALUE and MAX_VALUE.
MIN_VALUE contains the minimum possible value for an int (-2^31) and MAX_VALUE the maximum possible value for an int (2^31 - 1).
It also has two constructors - public Integer (int value) & public Integer (String value).
Integer has the no-arg byteValue, doubleValue, floatValue, intValue, longValue, and shortValue methods that convert the wrapped value to a byte, double, float, int, long, and short, respectively.
In addition, the toString method converts the value to a String.
Static methods parse a String to an int (parseInt) and convert an int to a String (toString).
class AutoBox {
public static void main(String args[]) {
// autobox an int
Integer a = 100;
// auto-unbox
int b = a;
System.out.println(b + " " + a); // displays 100 100
}
}
This feature has been added in Java 5.
text gets converted automatically into Integer by compiler. So basically its a syntactic sugar that can shorten your code (otherwise you would do conversions back and forth by yourself). Of course it has its price and if this happens a lot (I mean really a lot, big loops, frequent invocations and so forth), it can become a performance issue, so when using it, just remember the it happens under the hood and you'll be fine.
Integer.valueOf(text)
is called under the hood
The feature is called autoboxing btw
Hope this helps
What is the difference between these two lines?
int pInt = 500;
and
Integer wInt = new Integer(pInt);
Or
Integer wInt = new Integer(500);
None.
That's the exact same thing. In the first case you just have a supplementary variable.
Note that with autoboxing you rarely need to have both an int and an Integer variables. So for most cases this would be enough :
int pInt = 500;
The main case where the Integer would be useful is to distinguish the case where the variable is not known (ie null) :
Integer i = null; // possible
int i = null; // not possible because only Object variables can be null
But don't keep two variables, one is enough.
In Java, an instance of a primitve class holds the actual value of the instance, but instance of a wrapper class holds a reference to the object. i.e. The address of the place where the object would be found.
When you write a program with this line:
Integer integer = 500;
The compiler changes it to this:
Integer integer = new Integer(500);
This process is called autoboxing. That is automatically putting a primitive-instance in a "box" of Integer. Hence, output of the following program:
public class PrimitiveToObject {
public static void main(String[] args) {
printClassName(1);
printClassName(1L);
printClassName((char)1);
}
public static void printClassName(Object object){
System.out.println(object.getClass());
}
}
is this:
class java.lang.Integer
class java.lang.Long
class java.lang.Character
Also this:
int i = integer;
changes into this:
int i = integer.intValue();
This is called unboxing.
As you can see above, the dot operator(.) is used on the variable named integer but not on i. That is: a wrapper's object can be dereferenced, but not a primitive instance.
Boxing and unboxing may slow down the program a little bit. Hence, to a newbie, wrappers may look like added burden, but they are not so. Wrappers are used at places where the object needs to be a reference type. eg: Map<Integer,String>map=new HashMap<Integer,String>(); is a valid statement, but Map<int,String>map=new HashMap<int,String>(); is not a valid statement.
Another typical case where wrapper is very useful: In MySQL, NULL is a valid entry for a column of INT type. But in Java, int cannot have a null value, Integer can. This is because in SQL NULL symbolises Not Available. So if you are using JDBC to insert integer values in a MySQL table, a null in your java program will help in inserting NULL in the MySQL table.
A wrapper class can also be useful in a case similar or anologous to this:
Boolean decision; // Using wrapper for boolean.
if("YES".equalsIgnoreCase(consent))
decision = Boolean.TRUE; // In favour
else if("NO".equalsIgnoreCase(consent))
decision = Boolean.FALSE; // Not in favour
else if("CAN'T SAY".equalsIgnoreCase(consent))
decision = null; // Undecided
For starters
int pInt = 500; , here pInt is not an object whereas in
Integer wInt = new Integer(500);
wInt is an reference
This is also a reason why java is not pure Object Oriented Language. Because everything is not object with java.
Wrapper class will have a box in that box it will cover the primitive data types there are 8 primitive data types namely byte,int ,long ,double, float, short ,Boolean ,char these all covered in wrapper class .
to use primitive data types we use like int a;
but to use wrapper class we need to use like Integer a = new Integer(i);
The types of data are the same, but there are situations that manipulation of objects is more convenient than primitive types, like data structures, where you need more control of your data types.
For example, objects can be null and primitive types can't.
You also can't call methods in a primitive type (.compareTo(), .equals(), ...), but in wrapper classes you can.
The information below describe the types in primitive and wrapper class:
Primitive Types | Wrapper Class (Superclass = Object)
boolean - Boolean
char - Character
Primitive Types | Wrapper Class (Superclass = Number)
byte - Byte
short - Short
int - Integer
long - Long
float - Float
double - Double
To understand how the wapper classes works, consider the example below:
public final class IntWrapper {
private final int intVal;
IntWrapper(int intVal) {
this.intVal = intVal;
}
public int getInt() {
return intVal;
}
}
Now we can make an object out of our new IntWrapper class and 'box' the primitive int value 41:
int i = 41;
IntWrapper iw = new IntWrapper( i ); // box the primitive int type value into the object
i = iw.getInt(); // unbox the value from the wrapper object
My example IntWrapper class is immutable, immutable means that once its state has been initialized its state cannot be changed.
When the final keyword is applied to a class, the final class cannot be extended. In other words, a final class can never be the superclass of a subclass. A final class can be the subclass of superclass, not problem there. When a class is marked final, all of its methods are implicitly final as well.
It is important to note that when final is applied to a reference variable it does not prevent the members of the object instance from changing values.
This example is to better understanding how the wrapper classes works inside.
Next, to create Integer, Double and other wrapper classes, you can write:
Integer i = new Integer(4);
Double d = new Double(9.62);
Boolean b = new Boolean("true");
Character c = new Character('M');
To get the encapsulated number into wrapper objects, you can write:
long l = i.longValue();
double e = i.doubleValue();
float f = d.floatValue();
short s = d.shortValue();
Each wrapper class include special methods to convert between primitive type to wrapper objects, that represent not number values:
boolean bo = b.booleanValue();
char ch = c.charValue();
Up to Java 5 version, the creation of objects from wrapper classes had to be in the syntaxes like above, but to simplify these operations, mainly related to insertion of values in the data structures offered in Java collections (that only accept objects), now exists the autoboxing or boxing and autounboxing or unboxing options.
The autoboxing or boxing allows you to insert a primitive value to reference of equivalent wrapper types or Object type:
// Same result of Double d = new Double(-2.75);
Double objD = -2.75;
// Same result of Object objI = new Integer(13);
Object objI = 13;
The autounboxing or unboxing allows you to insert a wrapper object into a variable of primitive type, converting automatically between equivalent types:
// Same result of double vd = objD.doubleValue();
double vd = objD;
// Same result of int vi = objI.intValue();
int vi = objI;
The most important practical difference I've seen is Integer is way more slower to initialize and do calculations with, than int. I would avoid Integer unless necessary.
int x = 20_000_000;// 20 millions
for (int i = 0; i < x; i++) {
ix += 23;
}
it takes 138 ms(average over 50 trials) to complete the loop when ix is an Integer but only takes 10 ms when ix is an int
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.