Declaring / initializing primitives equal to creating new objects

declares / initializes primitives in the same way as creating new objects? from what I know when we create primitives, we also create wrapper classes for them. im implements on java btw.

+4
source share
5 answers

No, when assigning primitive values, do not create any objects.

May concern you the fact that primitive values ​​can be automatically placed in appropriate wrappers when they are used in a context where a reference type (for example, "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 

In addition, I will try to describe the difference between declaration and initialization:

 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 

The variable is "declared" when it is created for the first time (that is, the type and name of the variable are indicated). It is initialized when it is assigned a value during the declaration.

+5
source

No, declaring and initializing a primitive variable does not create an object. Let’s take a class with two integer values ​​- one using a wrapper type, and the other not.

 public class Foo { private int primitive = 10; private Integer wrapper = new Integer(10); } 

The value of the primitive variable is simply number 10. The value of the wrapper variable is a reference to the Integer object, which, in turn, contains the number 10. Thus, the Foo instance will save the state for the number in primitive and the link in wrapper .

In Java, there are wrapper classes for all primitive types, but you do not use them automatically.

+3
source

Creating a primitive DOES NOT NOT also create a wrapper class for them.

As for your initial question: declaring / initializing a primitive will create it on the stack, while declaring an object will contain a variable to hold a reference to the object. Initialization of the object will be allocated to the heap.

+2
source

Not. Primitives are not objects in java.

0
source

Source: https://habr.com/ru/post/1310394/


All Articles