DEV Community

Cover image for Autoboxing in Java
Wagner Negrão 👨‍🔧
Wagner Negrão 👨‍🔧

Posted on

Autoboxing in Java

First of all, this post is in Portuguese right below

Sometimes we hear about it when we are starting out in language and we wonder what it is. Autoboxing consists of switching between the wrapper class and the primitive type that represents it, such as Integer with int.

When creating applications we must instantiate the variables and many times we see or do things like:

private Integer age;

// or

private int age;
Enter fullscreen mode Exit fullscreen mode

Initially we know that int is a primitive type, something simpler, whereas Integer is a wrapper that behaves like a class, having much more than a primitive type.
When using an Integer type, we must be very careful not to make comparative or attribution changes directly, at this time we may be doing autoboxing or boxing unnecessarily, as they enhance the performance decrease of our code, the resource must be used available from the wrapper, for better performance.

Let's take the Student class's age variable as an example.

Class Student {
    private String name;
    private Integer age;
}
Enter fullscreen mode Exit fullscreen mode

In it we can see that the student's age is in a wrapper and at that moment we should have the following question, what is the real need to have a wrapper there? Because if you are not going to use the real advantages of the wrapper, you may be able to commit autoboxing on a regular basis without a real need.

So when faced with a situation that you can routinely use the features of Integer then use it without fear, but if you are going to use its advantages sporadically then it is better to choose the int type.

Portuguese

Às vezes escutamos falar sobre isso quando estamos iniciando na linguagem e nos perguntamos o que é isso. O autounboxing consiste em fazer a troca entre a classe wrapper e o tipo primitivo que a representa, como o Integer com o int.

Ao criarmos aplicações devemos instanciar as variáveis e em muitas vezes vemos ou fazemos coisas como:

private Integer age;

// or

private int age;
Enter fullscreen mode Exit fullscreen mode

Inicialmente sabemos que o int é um tipo primitivo, algo mais simples, já o Integer é um wrapper que se comporta como uma classe, possuindo bem mais coisas que um tipo primitivo.
Ao utilizarmos um tipo Integer devemos ter bastante cuidado para não realizarmos mudanças comparativas ou de atribuição de forma direta, nesse momento podemos está fazendo autoboxing ou boxing de forma desnecessária, pois elas potencializando a diminuição de desempenho do nosso código, deve-se utilizar o recursos disponíveis do wrapper, para melhor performance.

Vamos tomar como exemplo a variável idade da classe Aluno.

Class Student {
    private String name;
    private Integer age;
}
Enter fullscreen mode Exit fullscreen mode

Nela podemos ver que a idade do aluno está em um wrapper e nesse momento devemos ter a seguinte pergunta, qual a necessidade real de ter um wrapper ali? Pois se você não for utilizar as reais vantagens do wrapper possivelmente você poderá cometer o autoboxing corriqueiramente sem uma real necessidade.

Então ao se deparar com uma situação que você poderá utilizar rotineiramente as funcionalidades do Integer então utilize ele sem medo, mas se vai utilizar as vantagens dele de forma esporádica então é melhor escolher o tipo int.

Oldest comments (1)

Collapse
 
wldomiciano profile image
Wellington Domiciano

Muito bom!

E fora que, no exemplo que vc deu, se não inicializar com um número de verdade, o valor será null e isso pode não ser bem o que vc deseja.