About box in java

Autoboxing & Unboxing With Examples – Wrapper Class in Java

In Java 1.5, Java community has introduced two more new concepts that are Autoboxing and Unboxing in Java. Because of autoboxing and unboxing, we can able to convert primitive datatype to corresponding Java wrapper classes and vice versa.

If you have used collections like ArrayList, hashmap before Java 1.5 version, that time, you may face a problem that you can not put the primitive types into the collections, to use the primitive datatype in the collection first we need to convert them to object after that only we can use them into the collections. For such scenario wrapper class like integer, double and boolean helps convert the primitive to object.

But in Java 1.5, there is some new feature introduced likes Autoboxing and Unboxing, which helps in converting the primitive datatype to object automatically by the java compiler because of this feature. The code will be more readable.

Both Autoboxing and Unboxing come with some warning, so we need to understand them very clearly before using them in the program because those things happen automatically, and if you do not implement them properly, then that may create bugs.

Читайте также:  Left absolute css что

So for a better understanding of Autoboxing and Unboxing, in this article, we are going to discuss:

Autoboxing & Unboxing

  • What is Autoboxing and Unboxing in Java?
  • When Autoboxing and Unboxing occurs?

Autoboxing in Java

Converting a primitive data type to object type of the corresponding wrapper class is called Autoboxing.
Example: Converting of int to an integer, long to Long, etc.

Java Compiler applies autoboxing when a primitive value is passed to a method, but the method is expected a wrapper class object.

class AutoboxingExample1 < public static void myMethod(Integer num) < System.out.println(num); >public static void main(String[] args) < /* passed int (primitive type), it would be * converted to Integer object at Runtime */ myMethod(2); >>

When you assign a primitive data type value to a wrapper class object?

Unboxing In Java

Converting a wrapper class object to a primitive data type is called unboxing. For example, Integer to int. Java compiler applies unboxing, when

When a passed a wrapper class object to a method but that method expecting a primitive data type value

class UnboxingExample1 < public static void myMethod(int num) < System.out.println(num); >public static void main(String[] args) < Integer inum = new Integer(100); /* passed Integer wrapper class object, it * would be converted to int primitive type * at Runtime */ myMethod(inum); >>

When are you trying to assign a wrapper class object to a primitive data type variable?

ArrayList ArrayList = new ArrayList() int num = ArrayList.get(0); // unboxing because get method returns an Integer object
Primitive type Wrapper class
boolean Boolean
byte Byte
char Character
float Float
int Integer
long Long
short Short
double Double

Important point About Autoboxing and Unboxing In Java

When Compiler converts the primitive data type to wrapper class object, that time compiler calls valueof() method, in the same when compiler convert wrapper class object to a primitive value that time compiler calls intValue() and doubleValue() methods During autoboxing when we are writing

Then Java compiler internally calls the valueOf() to convert the primitive data type to wrapper class object. so internally this statement is executed

Integer num=Integer.valueOf(100);

Similarly at the time of unboxing when we are trying to convert wrapper class object to the primitive data type for example

Integer num2 = new Integer(50); int inum = num2;

then Java compiler internally calls intValue() method like below

Integer num2 = new Integer(50); int inum = num2.intValue();

Similarly, for other primitive data types, such things happen internally.

Important Point to Keep in Mind during comparison:

When you are comparing that time, don’t mix primitive data type with an object; if you do so, then you may get an unpredictable result. Better at the time of comparing objects with objects, try to use equals() method, and while comparing with the primitive data type, try to use logical operators like “==,” “” etc.

Источник

Autoboxing and Unboxing

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. If the conversion goes the other way, this is called unboxing.

Here is the simplest example of autoboxing:

The rest of the examples in this section use generics. If you are not yet familiar with the syntax of generics, see the Generics (Updated) lesson.

Consider the following code:

List 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 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.

Consider the following method:

public static int sumEven(List li)

Because the remainder (%) and unary plus (+=) operators do not apply to Integer objects, you may wonder why the Java compiler compiles the method without issuing any errors. The compiler does not generate an error because it invokes the intValue method to convert an Integer to an int at runtime:

public static int sumEven(List li)

Converting an object of a wrapper type (Integer) to its corresponding primitive (int) value is called unboxing. The Java compiler applies unboxing when an object of a wrapper class is:

  • Passed as a parameter to a method that expects a value of the corresponding primitive type.
  • Assigned to a variable of the corresponding primitive type.

The Unboxing example shows how this works:

import java.util.ArrayList; import java.util.List; public class Unboxing < public static void main(String[] args) < Integer i = new Integer(-8); // 1. Unboxing through method invocation int absVal = absoluteValue(i); System.out.println("absolute value of " + i + " = " + absVal); Listld = new ArrayList<>(); ld.add(3.1416); // Π is autoboxed through method invocation. // 2. Unboxing through assignment double pi = ld.get(0); System.out.println("pi codeblock"> 
absolute value of -8 = 8 pi = 3.1416

Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The following table lists the primitive types and their corresponding wrapper classes, which are used by the Java compiler for autoboxing and unboxing:

Primitive type Wrapper class
boolean Boolean
byte Byte
char Character
float Float
int Integer
long Long
short Short
double Double

Previous page: Summary of Characters and Strings
Next page: Questions and Exercises: Characters and Strings

Источник

Autoboxing и unboxing в Java

Сегодня речь пойдет об автоупаковке (autoboxing) и распаковке (unboxing). Это одно из существенных изменений, внесенных в JDK 5. Теперь разработчики могут писать более чистый код, но непонимание работы этого механизма может привести к плохой производительности.

Автоупаковка

Это автоматическая инкапсуляция примитивного типа в эквивалентную ему класс-обёртку всякий раз, когда требуется объект данного типа. Про инкапсуляцию и другие принципы ООП существует замечательная статья от ffriend.

  1. При присвоении значения примитивного типа переменной соответствующего класса-обёртки.
  2. При передаче примитивного типа в параметр метода, ожидающего соответствующий ему класс-обёртку.

Примеры

public class Main < public static void main(String[] args) < Integer iOb = new Integer(7); Double dOb = new Double(7.0); Character cOb = new Character('a'); Boolean bOb = new Boolean(true); method(new Integer(7)); >public static void method(Integer iOb) < System.out.println("Integer"); >> 
public class Main < public static void main(String[] args) < Integer iOb = 7; Double dOb = 7.0; Character cOb = 'a'; Boolean bOb = true; method(7); >public static void method(Integer iOb) < System.out.println("Integer"); >> 

Автораспаковка

Это преобразование класса-обёртки в соответствующий ему примитивный тип. Если при распаковке класс-обёртка был равен null, произойдет исключение java.lang.NullPointerException.

  1. При присвоении экземпляра класса-обёртки переменной соответствующего примитивного типа.
  2. В выражениях, в которых один или оба аргумента являются экземплярами классов-обёрток (кроме операции == и !=).
  3. При передаче объекта класса-обёртки в метод, ожидающий соответствующий примитивный тип.

1. При присвоении

int i = iOb.intValue(); double d = dOb.doubleValue(); char c = cOb.charValue(); boolean b = bOb.booleanValue(); 
int i = iOb; double d = dOb; char c = cOb; boolean b = bOb; 

2. В выражениях

Так как арифметические операторы и операторы сравнения (исключение == и !=) применяются только к примитивным типам, приходилось делать распаковку вручную, что заметно снижало читабельность выражений, делая их громоздкими, и кода в целом.

Integer iOb1 = new Integer(5); Integer iOb2 = new Integer(7); System.out.println(iOb1.intValue() > iOb2.intValue());

Благодаря автораспаковке, мы смело можем писать выражения, не используя методы конвертации. Теперь за этим следит компилятор Java.

System.out.println(iOb1 > iOb2); System.out.println(iOb1 + iOb2);

При сравнении классов-обёрток оператором == или !=, происходит сравнение по ссылкам, а не по значениям и может возникнуть путаница. Например, как вы думаете, что выведется на экран при исполнении следующего кода?

Integer iOb1 = 100; Integer iOb2 = 100; System.out.println(iOb1 == iOb2); Integer iOb3 = new Integer(120); Integer iOb4 = new Integer(120); System.out.println(iOb3 == iOb4); Integer iOb5 = 200; Integer iOb6 = 200; System.out.println(iOb5 == iOb6);

Ответ: в первом случае — true, во втором и третьем — false.
В первом случае фактически вызывается статичный метод java.lang.Integer.valueOf(int), который кэширует значения от -128 до 127 (верхнюю границу можно изменять) и при повторном использовании достает их из так называемого pool (набор инициализированных и готовых к использованию объектов). Во втором происходит явное создание объектов, следовательно они имеют разные ссылки.

3. При передачи в метод

public class Main < public static void main(String[] args) < Integer iOb = 10; method(iOb); >public static void method(int i) < System.out.println("int"); >> 

На экран будет выведено int, но стоит отметить, что если для метода реализована перегрузка с соответствующим классом-обёрткой, вызовется именно он.

public class Main < public static void main(String[] args) < Integer iOb = 10; method(iOb); >public static void method(int i) < System.out.println("int"); >public static void method(Integer iOb) < //Будет вызван данный метод System.out.println("Integer"); >> 
public class Main < public static void main(String[] args) < Integer[] iObs = new Integer[] ; method(iObs); //Ошибка компиляции > public static void method(int . i) < System.out.println("int[]"); >> 

Плохая производительность

Классы-обёртки неизменяемые, поэтому при каждой автоупаковке (за исключением значений из pool) создается новый объект, что может привести к неразумному расходу памяти.

public static Integer sumBeforeInclusive(Integer number) < Integer iOb = number; if (number >1) iOb += sumBeforeInclusive(number - 1); return iOb; > 

Примитивные типы и их классы-обертки

Источник

Оцените статью