Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No need for creating Short objects explicitly?

Tags:

java

Following code works perfect and adds 1 and 2 values to the list, but why? Why you don't need to create Short objects explicitly? e.g: list.add(new Short(1));

List<Short> list = new ArrayList();
list.add((short)1);
list.add((short)2);
System.out.println(list);
like image 713
Marco Avatar asked May 08 '12 19:05

Marco


1 Answers

This is called autoboxing. It is a feature that automatically converts primitives to their corresponding object type. It is present since Java 1.5.

The opposite of autoboxing is called autounboxing but beware of NullPointerException

like image 139
Guillaume Polet Avatar answered Oct 15 '22 13:10

Guillaume Polet