Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring/initializing primitives equal to creating new objects

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.

like image 319
mixm Avatar asked Dec 23 '22 03:12

mixm


2 Answers

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.

like image 167
Joachim Sauer Avatar answered Dec 28 '22 09:12

Joachim Sauer


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.

like image 40
Jon Skeet Avatar answered Dec 28 '22 11:12

Jon Skeet