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
Related
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.
I have a map: Map abc = new HashMap(). Why is it mandatory for me to use only objects as keys and not primitives?
As for why: The implementations of a Map require Object keys (with an equals() function) to (efficiently) order/store your values for quick retrieval. Primitives do not have an equals() function and are therefore unsuited for the task. (this is basically what #MadProgrammer suggested, except that equals is used in the defintion, and hashCode is just optional for possible implementations).
There is no reason that it would not be possible to programm this, however: in fact you could argue that primitives have the easiest equality and hashCodes to compute! This is probably what is done in TIntArrayList as suggested by Narendra Pathai. And as Jens Schauder states: it would not be worth the hassle, also because autoboxing hides the problem from you most of the time.
In java there is a big divide between primitives and objects/classes.
When you define a method that takes and Object as an argument, you might as well pass a String, or a AbstractSingletonFactoryFacade. But you can't pass a primitive. There is just no way to abstract over multiple primitives. This didn't change with generics.
What one could do is define separate interfaces accepting (and returning) the various primitives. While this would be feasible for thing like List, which have only one type parameter, for Map with two type parameters you would end up with 81 interfaces (8 primitive types + Object squared). Which just isn't worth the hassle.
Of course most of the time this doesn't matter since Autoboxing makes the problem invisible most of the time.
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){ ... }
I would like to be able to retrieve the available operators for an object at runtime, possibly in a similar way as the getMethod() call.
In particular, I need to be able to call the less-than/greater-than operators of an object at runtime.
Basically, I have a bunch of primitives that have been cast to the Object object-type. I need to perform comparisons between them at run-time. (I do know that the objects being compared will be of the same original type, and have implemented my own type-checking).
Alternatively.. Maybe there is a way to programatically cast these objects back to their original type, and use their native comparison operators.. somehow?
Thanks for any assistance.
There is no way in Java to get available operators. For comparison the class should (you may do this thru reflection also) implement the Comparable interface.
If they are auto-boxed primitive types, the set of arithmetic operators is identical for all types other than Boolean, and the set of bitwise operators ditto apart from the two FP types.
Is there any reason why an array in Java is an object?
Because the Java Language Specification says so :)
In the Java programming language arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.
So, unlike C++, Java provides true arrays as first-class objects:
There is a length member.
There is a clone() method which overrides the method of the same name in class Object.
Plus all the members of the class Object.
An exception is thrown if you attempt to access an array out of bounds.
Arrays are instanciated in dynamic memory.
Having arrays be objects means that you can do operations with them (e.g., someArray.count('foo')) instead of just doing it against them (e.g., count(someArray, 'foo')), which leads to more natural syntax.
Another point is that objects are mutable and are passed by reference. In arrays there aren't any fields/methods that you can use to change "properties" of the array, but you sure can mutate the element values. And the benefits of passing arrays by reference are pretty obvious (though functional programmers probably wish Java had immutable lists passed by value).
Edit: forgot to mention. In the period before autoboxing, it was helpful to be able to store arrays in collections, write them to ObjectStreams etc.
Probably because they wanted to get as close as possible to making everything an object. Native types are there for backward compatibility.
So that they get all the benefits thereof:
getHashCode()
toString()
etc.
And arrays aren't 'primitive', so if they can't be primitive, they must be objects.
I'm not sure about the official reason.
However, it makes sense to me that they are objects because operations can be performed on them (such as taking the length) and it made more sense to support these operations as member functions rather than introduce new keywords. Other operations include clone(), the inherited operations of object, etc. Arrays are also hashable and potentially comparable.
This is different from C (and native arrays in C++), where your arrays are essentially pointers to a memory offset.