Benefits of using wrapper classes over primitives in Java - java

At a very abstract level I do know that wrapper classes, create an object of the primitive data type but I was curious as to why do we need to use wrapper classes and what benefits do they offer over primitive data types.

Collections in the first place, for example,List<Integer>, you cannot use primitive int here.
Actually any generic class / interface that can work with different object types like
public interface Callable<V> {
V call() throws Exception;
}
Note that wrapping is best done using not new Integer(i) but Integer.valueOf(i) the latter will try to use cache. Unwrapping is done as Integer.intValue(). These wrapping / unwrapping of primitives are so typical operations that Java 5 introduced autoboxing / unboxing
List<Integer> list = new ArrayList<>();
list.add(1);
int i = list.get(0);
this code is automatically converted by Java compiler into
list.add(Integer.valueIf(1));
int i = list.get(0).intValue(); // this is where NullPointerException sometimes happens

Wrapper classes are designed to add more functionality to the primitive types, so that they are compatible with generic code, using the Collection Framework, and many other benefits. However, they are not mean't to replace primitive types.
So, you should use wrappers only when necessary, such as when dealing with generics, because creating an object adds substantial overheads to your program. So, in normal cases, you should stick to primitives.

A wrapper type enables a primitive to hold more contextual meaning. For instance an integer could be anything, whereas a class called Hours, for example, gives the number meaning wherever it is used.
They also enable methods to be written that mutate the said primitive in a consistent and obvious way to consumers. Have a look at Domain Driven Design for more information surrounding this point.

The primitive types just hold value, the wrapper class gives it a name.
With a class name, the compiler can do some static check for you. It makes the interface more meaningful. And you can also defined some method in wrapper classes to validate the primitive values.
Normally, for a small project, i think use primitive types is just fine.

Wrapper objects are normal objects and there references can be null. This allows the usage of a "not set" state which is impossible with primitives.
Integer no = null; // not set
You have to use a magic value like -1 to indicate that a primitive variable is "unset".

Just imagine : your playing a game in that you need to save the status and you want to play in different computer(same game) then u decided to take status (level) to the other computer then you can continue from that state(not from the beginning).. Okay come to the questions if your current weapons status is 3. like { int weapons=1; if(you add weapons by playing some levels okay now its 3) } but you cannot able to store it as object because primitives are different.(lives in stack). so you need weapons as objects (( solution : create Integer Object))
Integer weapon = new Integer(1){ ... }

Related

Relation between Integer Class and int [duplicate]

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.
So why do we need it and why do we use autoboxing and unboxing in Java?
Some context is required to fully understand the main reason behind this.
Primitives versus classes
Primitive variables in Java contain values (an integer, a double-precision floating point binary number, etc). Because these values may have different lengths, the variables containing them may also have different lengths (consider float versus double).
On the other hand, class variables contain references to instances. References are typically implemented as pointers (or something very similar to pointers) in many languages. These things typically have the same size, regardless of the sizes of the instances they refer to (Object, String, Integer, etc).
This property of class variables makes the references they contain interchangeable (to an extent). This allows us to do what we call substitution: broadly speaking, to use an instance of a particular type as an instance of another, related type (use a String as an Object, for example).
Primitive variables aren't interchangeable in the same way, neither with each other, nor with Object. The most obvious reason for this (but not the only reason) is their size difference. This makes primitive types inconvenient in this respect, but we still need them in the language (for reasons that mainly boil down to performance).
Generics and type erasure
Generic types are types with one or more type parameters (the exact number is called generic arity). For example, the generic type definition List<T> has a type parameter T, which can be Object (producing a concrete type List<Object>), String (List<String>), Integer (List<Integer>) and so on.
Generic types are a lot more complicated than non-generic ones. When they were introduced to Java (after its initial release), in order to avoid making radical changes to the JVM and possibly breaking compatibility with older binaries, the creators of Java decided to implement generic types in the least invasive way: all concrete types of List<T> are, in fact, compiled to (the binary equivalent of) List<Object> (for other types, the bound may be something other than Object, but you get the point). Generic arity and type parameter information are lost in this process, which is why we call it type erasure.
Putting the two together
Now the problem is the combination of the above realities: if List<T> becomes List<Object> in all cases, then T must always be a type that can be directly assigned to Object. Anything else can't be allowed. Since, as we said before, int, float and double aren't interchangeable with Object, there can't be a List<int>, List<float> or List<double> (unless a significantly more complicated implementation of generics existed in the JVM).
But Java offers types like Integer, Float and Double which wrap these primitives in class instances, making them effectively substitutable as Object, thus allowing generic types to indirectly work with the primitives as well (because you can have List<Integer>, List<Float>, List<Double> and so on).
The process of creating an Integer from an int, a Float from a float and so on, is called boxing. The reverse is called unboxing. Because having to box primitives every time you want to use them as Object is inconvenient, there are cases where the language does this automatically - that's called autoboxing.
Auto Boxing is used to convert primitive data types to their wrapper class objects.
Wrapper class provide a wide range of function to be performed on the primitive types. The most common example is :
int a = 56;
Integer i = a; // Auto Boxing
It is needed because of programmers easy to be able to directly write code and JVM will take care of the Boxing and Unboxing.
Auto Boxing also comes in handy when we are working with java.util.Collection types. When we want to create a Collection of primitive types we cannot directly create a Collection of a primitive type , we can create Collection only of Objects. For Example :
ArrayList<int> al = new ArrayList<int>(); // not supported
ArrayList<Integer> al = new ArrayList<Integer>(); // supported
al.add(45); //auto Boxing
Wrapper Classes
Each of Java's 8 primitive type (byte,short,int,float,char,double,boolean,long) hava a seperate Wrapper class Associated with them. These Wrapper class have predefined methods for preforming useful operations on primitive data types.
Use of Wrapper Classes
String s = "45";
int a = Integer.parseInt(s); // sets the value of a to 45.
There are many useful functions that Wrapper classes provide. Check out the java docs here
Unboxing is opposite of Auto Boxing where we convert the wrapper class object back to its primitive type. This is done automatically by JVM so that we can use a the wrapper classes for certain operation and then convert them back to primitive types as primitives result int faster processing. For Example :
Integer s = 45;
int a = s; auto UnBoxing;
In case of Collections which work with objects only auto unboxing is used. Here's how :
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(45);
int a = al.get(0); // returns the object of Integer . Automatically Unboxed .
The primitive (non-object) types have there justification in efficiency.
The primitive types int, boolean, double are immediate data, whereas Objects are references. Hence fields (or variables)
int i;
double x;
Object s;
would need local memory 4+8+8? where for the object only the reference (address) to memory is stored.
Using the Object wrappers Integer, Double and others, one would introduce an indirection, reference to some Integer/Double instance in the heap memory.
Why boxing is needed?
That is a question of relative scope. In a future java it is planned to be able to have an ArrayList<int>, lifting primitive types.
Answer: For now an ArrayList only works for Object, reserving room for an object reference, and managing garbage collection likewise. Hence generic types are Object children.
So if one wanted an ArrayList of floating point values, one needed to wrap a double in a Double object.
Here Java differs from the traditional C++ with its templates: C++ classes vector<string>, vector<int> would create two compilation products. Java design went for having one ArrayList.class, not needing for every parameter type a new compiled product.
So without boxing to Object one would need to compile classes for every occurrence of a parameter type. In concreto: every collection or container class would need a version for Object, int, double, boolean. The version for Object would handle all child classes.
In fact, the need for such diversification already existed in Java SE for IntBuffer, CharBuffer, DoubleBuffer, ... which operate on int, char, double. It was solved in a hacky way by generating these sources from a common one.
Starting with JDK 5, java has added two important functions: autoboxing and autounboxing. AutoBoxing is the process for which a primitive type is automatically encapsulated in the equivalent wrapper whenever such an object is needed. You do not have to explicitly construct an object. Auto-unboxing is the process whereby the value of an encapsulated object is automatically extracted from a type wrapper when its value is required. You do not need to call a method such as intValue() or doubleValue().
The addition of autoboxing and auto-unboxing greatly simplifies writing algorithms, eliminating the bait manually boxing and unboxing of values. It is also helpful to avoid mistakes. It is also very important for generics, who only operate on objects. Lastly, autoboxing facilitates work with the Collections Framework.
Some data structures can accept only objects, no primitive types.
Example: the key in a HashMap.
See this question for more: HashMap and int as key
There are other good reasons, such as a "int" field in a database, which could be NULL as well.
An int in Java cannot be null ; an Integer reference can. Autoboxing and unboxing provide with a facility to avoid writing extraneous code in the conversions back and forth.
why do we have (un)boxing?
to make writing code where we mix primitives and their Object Oriented (OO) alternatives more comfortable/less verbose.
why do we have primitives and their OO alternatives?
primitive types are not classes (unlike in C#), thus they are not subclasses of Object and can not be overridden.
we have primitives like int for performance reasons, and the Object alternatives like Integer for the benefits of OO programming, and as a minor point, to have a good location for utility constants and methods (Integer.MAX_VALUE and Integer.toString(int)).
The OO benefits are visible most easily with Generics (List<Integer>), but are not limited to that, for example:
Number getMeSome(boolean wantInt) {
if (wantInt) {
return Integer.MAX_VALUE;
} else {
return Long.MAX_VALUE;
}
}
ArrayList does not support primitive types only support class. but we need to use primitive types e.g int, double etc.
ArrayList<String> strArrayList = new ArrayList<String>(); // is accepted.
ArrayList<int> intArrayList = new ArrayList<int>(); // not accepted.
The Integer class wraps a value of the primitive type int in an object.so bellow code is accepted.
ArrayList<Integer> intArrayList = new ArrayList<Integer>(); // is accepted.
we can add a value with add(value) method.
To add a String value say "Hello" in strArrayList code is just
strArrayList.add("Hello");
and add a int value say 54 we can write
intArrayList.add(54);
but when we write intArrayList.add(54); compiler convert to the following line
intArrayList.add(Integer.valueOf(54));
As intArrayList.add(54) is easy and more acceptable from user side so compiler does the hard job which is `intArrayList.add(Integer.valueOf(54)); it is autoBoxing.
Similarly to retrieve value we just type
intArrayList.get(0) and compiler convert to <code>intArrayList.get(0).intValue(); which is autoUnboxing.
Because they are different types, and as a convenience. Performance is likely the reason for having primitive types.
Autoboxing: Converting a primitive value into an object of the corresponding wrapper class.
Unboxing: Converting an object of a wrapper type to its corresponding primitive value
// Java program to illustrate the concept
// of Autoboxing and Unboxing
import java.io.*;
class GFG
{
public static void main (String[] args)
{
// creating an Integer Object
// with value 10.
Integer i = new Integer(10);
// unboxing the Object
int i1 = i;
System.out.println("Value of i: " + i);
System.out.println("Value of i1: " + i1);
//Autoboxing of char
Character gfg = 'a';
// Auto-unboxing of Character
char ch = gfg;
System.out.println("Value of ch: " + ch);
System.out.println("Value of gfg: " + gfg);
}
}
Another Special Case is,
Integer intval = null;
int toPrimitive = intval;
System.out.println(toPrimitive);
We are getting NullPointerException for above scenario. that means we can catch NPE

Why do we use autoboxing and unboxing in Java?

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.
So why do we need it and why do we use autoboxing and unboxing in Java?
Some context is required to fully understand the main reason behind this.
Primitives versus classes
Primitive variables in Java contain values (an integer, a double-precision floating point binary number, etc). Because these values may have different lengths, the variables containing them may also have different lengths (consider float versus double).
On the other hand, class variables contain references to instances. References are typically implemented as pointers (or something very similar to pointers) in many languages. These things typically have the same size, regardless of the sizes of the instances they refer to (Object, String, Integer, etc).
This property of class variables makes the references they contain interchangeable (to an extent). This allows us to do what we call substitution: broadly speaking, to use an instance of a particular type as an instance of another, related type (use a String as an Object, for example).
Primitive variables aren't interchangeable in the same way, neither with each other, nor with Object. The most obvious reason for this (but not the only reason) is their size difference. This makes primitive types inconvenient in this respect, but we still need them in the language (for reasons that mainly boil down to performance).
Generics and type erasure
Generic types are types with one or more type parameters (the exact number is called generic arity). For example, the generic type definition List<T> has a type parameter T, which can be Object (producing a concrete type List<Object>), String (List<String>), Integer (List<Integer>) and so on.
Generic types are a lot more complicated than non-generic ones. When they were introduced to Java (after its initial release), in order to avoid making radical changes to the JVM and possibly breaking compatibility with older binaries, the creators of Java decided to implement generic types in the least invasive way: all concrete types of List<T> are, in fact, compiled to (the binary equivalent of) List<Object> (for other types, the bound may be something other than Object, but you get the point). Generic arity and type parameter information are lost in this process, which is why we call it type erasure.
Putting the two together
Now the problem is the combination of the above realities: if List<T> becomes List<Object> in all cases, then T must always be a type that can be directly assigned to Object. Anything else can't be allowed. Since, as we said before, int, float and double aren't interchangeable with Object, there can't be a List<int>, List<float> or List<double> (unless a significantly more complicated implementation of generics existed in the JVM).
But Java offers types like Integer, Float and Double which wrap these primitives in class instances, making them effectively substitutable as Object, thus allowing generic types to indirectly work with the primitives as well (because you can have List<Integer>, List<Float>, List<Double> and so on).
The process of creating an Integer from an int, a Float from a float and so on, is called boxing. The reverse is called unboxing. Because having to box primitives every time you want to use them as Object is inconvenient, there are cases where the language does this automatically - that's called autoboxing.
Auto Boxing is used to convert primitive data types to their wrapper class objects.
Wrapper class provide a wide range of function to be performed on the primitive types. The most common example is :
int a = 56;
Integer i = a; // Auto Boxing
It is needed because of programmers easy to be able to directly write code and JVM will take care of the Boxing and Unboxing.
Auto Boxing also comes in handy when we are working with java.util.Collection types. When we want to create a Collection of primitive types we cannot directly create a Collection of a primitive type , we can create Collection only of Objects. For Example :
ArrayList<int> al = new ArrayList<int>(); // not supported
ArrayList<Integer> al = new ArrayList<Integer>(); // supported
al.add(45); //auto Boxing
Wrapper Classes
Each of Java's 8 primitive type (byte,short,int,float,char,double,boolean,long) hava a seperate Wrapper class Associated with them. These Wrapper class have predefined methods for preforming useful operations on primitive data types.
Use of Wrapper Classes
String s = "45";
int a = Integer.parseInt(s); // sets the value of a to 45.
There are many useful functions that Wrapper classes provide. Check out the java docs here
Unboxing is opposite of Auto Boxing where we convert the wrapper class object back to its primitive type. This is done automatically by JVM so that we can use a the wrapper classes for certain operation and then convert them back to primitive types as primitives result int faster processing. For Example :
Integer s = 45;
int a = s; auto UnBoxing;
In case of Collections which work with objects only auto unboxing is used. Here's how :
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(45);
int a = al.get(0); // returns the object of Integer . Automatically Unboxed .
The primitive (non-object) types have there justification in efficiency.
The primitive types int, boolean, double are immediate data, whereas Objects are references. Hence fields (or variables)
int i;
double x;
Object s;
would need local memory 4+8+8? where for the object only the reference (address) to memory is stored.
Using the Object wrappers Integer, Double and others, one would introduce an indirection, reference to some Integer/Double instance in the heap memory.
Why boxing is needed?
That is a question of relative scope. In a future java it is planned to be able to have an ArrayList<int>, lifting primitive types.
Answer: For now an ArrayList only works for Object, reserving room for an object reference, and managing garbage collection likewise. Hence generic types are Object children.
So if one wanted an ArrayList of floating point values, one needed to wrap a double in a Double object.
Here Java differs from the traditional C++ with its templates: C++ classes vector<string>, vector<int> would create two compilation products. Java design went for having one ArrayList.class, not needing for every parameter type a new compiled product.
So without boxing to Object one would need to compile classes for every occurrence of a parameter type. In concreto: every collection or container class would need a version for Object, int, double, boolean. The version for Object would handle all child classes.
In fact, the need for such diversification already existed in Java SE for IntBuffer, CharBuffer, DoubleBuffer, ... which operate on int, char, double. It was solved in a hacky way by generating these sources from a common one.
Starting with JDK 5, java has added two important functions: autoboxing and autounboxing. AutoBoxing is the process for which a primitive type is automatically encapsulated in the equivalent wrapper whenever such an object is needed. You do not have to explicitly construct an object. Auto-unboxing is the process whereby the value of an encapsulated object is automatically extracted from a type wrapper when its value is required. You do not need to call a method such as intValue() or doubleValue().
The addition of autoboxing and auto-unboxing greatly simplifies writing algorithms, eliminating the bait manually boxing and unboxing of values. It is also helpful to avoid mistakes. It is also very important for generics, who only operate on objects. Lastly, autoboxing facilitates work with the Collections Framework.
Some data structures can accept only objects, no primitive types.
Example: the key in a HashMap.
See this question for more: HashMap and int as key
There are other good reasons, such as a "int" field in a database, which could be NULL as well.
An int in Java cannot be null ; an Integer reference can. Autoboxing and unboxing provide with a facility to avoid writing extraneous code in the conversions back and forth.
why do we have (un)boxing?
to make writing code where we mix primitives and their Object Oriented (OO) alternatives more comfortable/less verbose.
why do we have primitives and their OO alternatives?
primitive types are not classes (unlike in C#), thus they are not subclasses of Object and can not be overridden.
we have primitives like int for performance reasons, and the Object alternatives like Integer for the benefits of OO programming, and as a minor point, to have a good location for utility constants and methods (Integer.MAX_VALUE and Integer.toString(int)).
The OO benefits are visible most easily with Generics (List<Integer>), but are not limited to that, for example:
Number getMeSome(boolean wantInt) {
if (wantInt) {
return Integer.MAX_VALUE;
} else {
return Long.MAX_VALUE;
}
}
ArrayList does not support primitive types only support class. but we need to use primitive types e.g int, double etc.
ArrayList<String> strArrayList = new ArrayList<String>(); // is accepted.
ArrayList<int> intArrayList = new ArrayList<int>(); // not accepted.
The Integer class wraps a value of the primitive type int in an object.so bellow code is accepted.
ArrayList<Integer> intArrayList = new ArrayList<Integer>(); // is accepted.
we can add a value with add(value) method.
To add a String value say "Hello" in strArrayList code is just
strArrayList.add("Hello");
and add a int value say 54 we can write
intArrayList.add(54);
but when we write intArrayList.add(54); compiler convert to the following line
intArrayList.add(Integer.valueOf(54));
As intArrayList.add(54) is easy and more acceptable from user side so compiler does the hard job which is `intArrayList.add(Integer.valueOf(54)); it is autoBoxing.
Similarly to retrieve value we just type
intArrayList.get(0) and compiler convert to <code>intArrayList.get(0).intValue(); which is autoUnboxing.
Because they are different types, and as a convenience. Performance is likely the reason for having primitive types.
Autoboxing: Converting a primitive value into an object of the corresponding wrapper class.
Unboxing: Converting an object of a wrapper type to its corresponding primitive value
// Java program to illustrate the concept
// of Autoboxing and Unboxing
import java.io.*;
class GFG
{
public static void main (String[] args)
{
// creating an Integer Object
// with value 10.
Integer i = new Integer(10);
// unboxing the Object
int i1 = i;
System.out.println("Value of i: " + i);
System.out.println("Value of i1: " + i1);
//Autoboxing of char
Character gfg = 'a';
// Auto-unboxing of Character
char ch = gfg;
System.out.println("Value of ch: " + ch);
System.out.println("Value of gfg: " + gfg);
}
}
Another Special Case is,
Integer intval = null;
int toPrimitive = intval;
System.out.println(toPrimitive);
We are getting NullPointerException for above scenario. that means we can catch NPE

Why Java doesn't support structures ? (Just out of curiosity)

I know you can use public fields, or some other workarounds. Or maybe you don't need them at all. But just out of curiosity why Sun leave structures out.
Here's a link that explains Sun's decision:
2.2.2 No More Structures or Unions
Java has no structures or unions as complex data types. You don't need structures and unions when you have classes; you can achieve the same effect simply by declaring a class with the appropriate instance variables.
Although Java can support arbitrarily many kinds of classes, the Runtime only supports a few variable types: int, long, float, double, and reference; additionally, the Runtime only recognizes a few object types: byte[], char[], short[], int[], long[], float[], double[], reference[], and non-array object. The system will record a class type for each reference variable or array instance, and the Runtime will perform certain checks like ensuring that a reference stored into an array is compatible with the array type, but such behaviors merely regard the types of objects as "data".
I disagree with the claim that the existence of classes eliminates the need for structures, since structures have semantics which are fundamentally different from class objects. On the other hand, from a Runtime-system design perspective, adding structures greatly complicates the type system. In the absence of structures, the type system only needs eight array types. Adding structures to the type system would require the type system to recognize an arbitrary number of distinct variable types and array types. Such recognition is useful, but Sun felt that it wasn't worth the complexity.
Given the constraints under which Java's Runtime and type system operate, I personally think it should have included a limited form of aggregate type. Much of this would be handled by the language compiler, but it would need a couple of features in the Runtime to really work well. Given a declaration
aggregate TimedNamedPoint
{ int x,y; long startTime; String name; }
a field declaration like TimedNamedPoint tpt; would create four variables: tpt.x, tpt.y of type int, tpt.startTime of type long, and tpt.name of type String. Declaring a parameter of that type would behave similarly.
For such types to be useful, the Runtime would need a couple of slight additions: it would be necessary to allow functions to leave multiple values on the stack when they return, rather than simply having a single return value of one the five main types. Additionally, it would be necessary to have a means of storing multiple kinds of things in an array. While that could be accomplished by having the creation of something declared as TimedNamedPoint[12] actually be an Object[4] which would be initialized to identify two instances of int[12], a long[12], and a String[12], it would be better to have a means by which code could construct a single array instance could hold 24 values of type int, 12 of type long, and 12 of type String.
Personally, I think that for things like Point, the semantics of a simple aggregate would be much cleaner than for a class. Further, the lack of aggregates often makes it impractical to have a method that can return more than one kind of information simultaneously. There are many situations where it would be possible to have a method simultaneously compute and report the sine and cosine of a passed-in angle with much less work than would be required to compute both separately, but having to constructing a SineAndCosineResult object instance would negate any speed advantage that could have been gained by doing so. The execution model wouldn't need to change much to allow a method to leave two floating-point values on the evaluation stack when it returns, but at present no such thing is supported.

Do custom wrapper classes take more/less space than Java wrapper classes?

Public class A
{
int a;
}
vs.
java.lang.Integer
Or Longs, Doubles, etc.
Do they take the same amount of memory? Or more/less? If I'm not missing anything the answer should be same...
The purpose of the wrapper classes are to be able to treat a primitive as an object by wrapping it in an Integer object, allowing you to call methods from it, or pass it as a parameter value for parameters that require an Object rather than a primitive.
Creating your own wrapper for a primitive, such as you are doing now, is not advised, as it will not allow for auto-boxing and unboxing of primitives. There's more functionality you are losing, but if we're talking memory, you'll save more memory over-time using Integer rather than your personal wrapper, since there is a constant pool for integer objects, allowing you to re-use a pre-existing value from the pool if one exists, instead of creating a new object every time. You'd need to implement the flyweight pattern to achieve the same kind of memory-saving system.

When should I use Boolean instead of boolean? [duplicate]

This question already has answers here:
Boolean vs boolean in Java
(8 answers)
Closed 9 years ago.
When should I use Boolean instead of boolean?. I mean, why would I want to have a null value in a variable which should contain either "true" or "false".. One spontaneous answer (of most people) would be if the value is unknown. i.e, if we don't know whether the value is true or false. But from a programming perspective, I think using Boolean may break the code as we will not know whats inside. So, I think using the primitive type is better than the wrapper.. Correct me if I am wrong.
Generally speaking, the wrapper classes are used in cases where an object is required or strongly preferred. Outside of these situations, it's better to use the primitive types, since they have lower overhead, you can use ==, etc. There are two and a half major situations where this is frequently seen:
Collections. This is now a subset of the next case, but even before Java 5 the Collections classes only supported objects as keys and values, and this hasn't changed.
Generics. Generic types can only work with objects, not primitives, and so if you're using "boolean" as a type parameter, it has to be the wrapper class. For example, if you're using a Future, you have to use a Boolean instead of a boolean. (HT #user949300)
ORM. JPA and other ORM systems technically can use primitive fields, but it's customary to use the wrapper classes, since the overhead is high enough that that doesn't really matter anyway, and the wrapper classes can represent a NULL value that might be present in the database. It's usually still better to forbid nulls and use a primitive for booleans, though, since semantically a default is usually better than "undefined".
Since boolean values are restricted to either true or false, it's uncommon to see them used in Collections or Generics; generally speaking, if you'd have a boolean as a value, you'll just use Collection#contains instead.
IMHO the primitive is better.
Always favor primitives over wrappers. Wherever I am able to use primitives, I go for them because at run time, if we use wrappers, boxing conversions and unboxing conversions happen, and obviously that takes more time. If you use the primitive there, you save that time.
And as usual it depends on your requirements whether you need a Object (which can be null) or you can use a primitive (which cannot be null) in your situation.
For example: Assume you are dealing with collection's then you have no option's,You have to use wrappers :).
Boolean have 3 possible values (null, true, false) while boolean can only be (true, false).
I greatly prefer primitives. However, Booleans are necessary:
When they go into Collections
When you need to allow for a null value. In my experience, this is mainly if they are stored in a database and you need null to indicate that they haven't been read yet, or the user hasn't filled in some form yet.
What if you need to use collections?
Collection will not store primitive types, you need to store object there.
Collections provide so many utility apis, so if you want to use them them a Boolean object is need as collection will need objects.
Although you can always use autoboxing which means you are shielded from object creation and collection takes care of it internally.
Boolean is an object, so you can use it with generics. For example, you can have Map<String,Boolean> to store a true\false value for each string(=key). You can't do Map<String,boolean>, because boolean is not an object - specifically, it's not a subclass of Object. Generics are compile-time wrappers, so Map<Foo,Bar> is actually Map<Object,Object> with smart casting, no matter what Foo and Bar are - as long as they are classes or array types. But they can't be primitives.
The Wrapper classes will be in cases where an object is required or strongly preferred like storing the objects in Collections, cache or session etc, where it requires an object (if not, JRE will convert the primitives to Wrapper classes before they are stored in secondary cache). The below link will explain in better:
Boolean vs boolean in Java
Booolean is an object/reference type that wraps a boolean whereas boolean in a primitive type.
Boolean - You would get more methods which will be useful.
boolean - Will save you lot of memory. But if you use Boolean.valueOf(value) of new Boolean(value), that shouldn't be a cause.
Converting between primitives and objects like this is known as boxing/unboxing.
Click on the below links for more info:
http://javaeye.wordpress.com/2008/06/17/boxing-and-unboxing-conversion/
http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html
http://www.javapractices.com/topic/TopicAction.do?Id=197

Categories

Resources