One new feature of Java 9 is to deprecate the constructor of wrapper objects. The only way to create new Wrapper objects is to use their valueOf() static methods.
For example for Integer objects, Integer.valueOf implements a cache for the values between -128 and 127 and returns the same reference every time you call it.
As API for Integer class says "The static factory valueOf(int) is generally a better choice, as it is likely to yield significantly better space and time performance." and JLS says "Given a value of the corresponding primitive type, it is generally unnecessary to construct new instances of these box classes. The recommended alternatives to construction are autoboxing or the valueOf static factory methods. In most cases, autoboxing will work, so an expression whose type is a primitive can be used in locations where a box class is required"
But what happens with the values outside this range?
For example Integer x = Integer.valueOf(456) is a new object every time the class was executed?
Both
Integer x = Integer.valueOf(456);
and
Integer x = 456;
will always result in a new instance of Integer being created, since 456 is outside the range of the Integer cache.
You can test it by writing
Integer x1 = Integer.valueOf(456);
Integer x2 = Integer.valueOf(456);
System.out.println(x1==x2);
which will print false.
First why bother with these details - the correct way to compare Integer objects is to use either:
if (x.intValue() == y.intValue()) or better x.equals(y)
Don't rely on the fact that there is a cache under any circumstances, since this cache's upper bound can be changed as a property, you can see it via:
java -XX:+PrintFlagsFinal | grep AutoBoxCacheMax
Read this on the oracle docs java.lang page:
Frequently it is necessary to represent a value of primitive type as if it were an object. The wrapper classes Boolean, Character, Integer, Long, Float, and Double serve this purpose.
I'm not sure I understand why these are needed. It says they have useful functions such as equals(). But if I can do (a==b), why would I ever want to declare them as Integer, use more memory and use equals()? How does the memory usage differ for the 2?
Java's generics system only supports class types. And since primitives are not classes, they can't be used with generics. However, a primitive's wrapper class can be used as a generic type. For example, you may not declare an ArrayList<int>, but you can achieve a similar functionality with an ArrayList<Integer>.
It is also of occasional use to initialize a variable's value to null. Primitives, however, cannot be set to null; that privilege is reserved for objects.
// This is OK
Integer iDontKnowValueYet = null;
// Compile error!
int iDontKnowThisYetEither = null;
Things like int, char, double are all primitives meaning they do not need to be instantiated by using "new". Things like Integer, Character, Double are objects that take up more room on the computer (since there is more overhead for objects) but you can use methods like Integer.parse(). In general, use the primitives and only use the object versions if you need one of the methods.
To answer the thing about a==b vs a.equals(b):
Integer a = new Integer(5);
Integer b = new Integer(5);
Even though they are the same value (which is what .equals tests for) they are not the same piece of memory since you said "new" twice. a!=b but a.equals(b)
Integer a = new Integer(5);
Integer b = a;
Now they use the same piece of memory meaning if you change one, you change them both (unless you use "new" again). a==b and a.equals(b)
//using last code block
b = new Integer(5);
Now once again a!=b but a.equals(b)==true since once again they have the same value but they are on different pieces of memory.
Your ints are usually wrapped in wrapper classes when you put them in a data structure. So, .equals method is used to determine when you call .contains method on the data structure.
Other usefule methods:
toString
toHexString
parseString
I have a program that creates lists and needs any assigned values to be 0. Its been running fine when I do with int[] humpty_dumpty = new int[20]; but to optimize the size of the lists I set them to Short[] and now my program is breaking because it takes the zero's as inputs(and Short[] humpty_dumpty = new Short[20]; is making the default value null).
Is there a way to set it to default zero without having to iterate through the entire list(I can do this via a for loop but was wondering if there was a way to make its behavior similar to int)?
There is a difference between a Short[] and a short[]. Elements of the latter will be initialized to 0 because short is a "primitive" type and cannot be null. The capitalized Short class will be initialized to null because it is really just an Object wrapping a short value.
You may create an array of primitive type instead of wrapper,
short []ar=new short[20];
Short[] doesn't 'optimize the size of the lists' at all, and it has a default value of null. short[] does, and it has a default value of zero.
Answers, in order:
1) Requirement first, optimization last. Don't use sparse arrays, or try to be 'smart', unless you specifically need to do this & deal with the extra code/ overhead.
2) Use common methods (possibly in an Instance or Static Helper class) to avoid repeating common code.
eg. short sparseGet (Short[] array, int i) {return (array[i] != null ? array[i] : 0);}
3) Perhaps use short[] rather than Short[]? Uppercase types are not primitives, but Value Wrapper classes -- and stored as object references (pointers) to instances, thus slower & more memory-intensive.
4) Uppercase 'Value Wrapper' types are appropriate where you may have null values, from a database. eg. Person.Age would ideally be Integer, if there's any possibility you/ the database might not have data for that field.
Cheers.
Is it valuable for using Integer i = NumberUtils.INTEGER_ONE instead of Integer i = 1? I don't know what happen behind auto boxing.
Thanks
Basically it will be compiled into:
Integer i = Integer.valueOf(NumberUtils.INTEGER_ONE);
assuming INTEGER_ONE is declared as an int.
At execution time, assuming INTEGER_ONE has the value 1, that will actually return a reference to the same object each time, guaranteed by the Java Language Specification, because it's in the range -128 to 127. Values outside that range can return references to the same object, but don't have to.
Many wrappers and utility classes in java have cached pools. Integer uses an internally cached static array of 'Integer' references to dish out when the valueOf() method is invoked. Strings also have a similar pool.
If however you do something like Integer i = 128, that will begin to impact performance since autoboxing will kick in for uncached integers (Not that it does not kick in for cached integers). Unlike the case where cached integers were returned, this statement creates a new object. Object creation is expensive and drags down performance.
[EDIT]
Clarified answer
In which case should you use primitive types(int) or reference types (Integer)?
This question sparked my curiosity.
In which case should you use primitive
types(int) or reference types
(Integer)?
As a rule of thumb, I will use a primitive (such as int) unless I have to use a class that wraps a primitive.
One of the cases were one must use a wrapper class such as Integer is in the case of using generics, as Java does not support the use of primitive types as type parameters:
List<int> intList = new ArrayList<int>(); // Not allowed.
List<Integer> integerList = new ArrayList<Integer>(); // Allowed.
And, in many cases, I will take advantage of autoboxing and unboxing, so I don't have to explicitly perform conversions from primitives to its wrapper class and vice versa:
// Autoboxing will turn "1", "2", "3" into Integers from ints.
List<Integer> numbers = Arrays.asList(1, 2, 3);
int sum = 0;
// Integers from the "numbers" List is unboxed into ints.
for (int number : numbers) {
sum += number;
}
Also, as an additional note, when converting from primitives to its wrapper class objects, and unique instances of objects are not necessary, use the valueOf method provided by the wrapper method, as it performs caching and return the same instance for a certain value, reducing the number of objects which are created:
Integer i1 = Integer.valueOf(1); // Prefer this.
Integer i2 = new Integer(1); // Avoid if not necessary.
For more information on the valueOf methods, the API specification for the Integer.valueOf method can serve as a reference for how those methods will behave in the wrapper classes for primitives.
That really depends on the context. First prefer the primitive, because it's more intuitive and has less overhead. If it is not possible for generics/autoboxing reasons, or if you want it to be nullable, then go for the wrapper type (complex type as you call it).
The general rules I follow when creating an API can be summarized as follows:
If the method must return an value, use a primitive type
If the method may not always apply (eg: getRadioId(...) on an object where such an ID may not exist), then return an Integer and specify in the JavaDocs that the method will return null in some cases.
On #2, look out for NPEs when autoboxing. If you have a method defined as:
public Integer getValue();
And then call it as follows:
int myValue = getValue();
In the case where getValue() returns null you'll get an NPE without an obvious cause.
Since Java does something called auto-boxing and auto-unboxing, you should use the primitive type int in most cases because of less overhead.
The only time you absolutely need to use Integer is in generics.
List<int> list; // won't compile
List<Integer> list; // correct
One case in which Integer might be prefered is when you are working with a database where numerical entries are allowed to be null, since you wouldn't be able to represent a null value with an int.
But of course if you're doing straight math, then int would be better as others have mentioned due to intuitiveness and less overhead.
My rule of thumb is: use boxed primitives only when it's necessary to get the code to compile. The only places in your code where the names of the primitive wrapper classes should appear is in generic type parameters and static method calls:
List<Integer> intList = new ArrayList<Integer>();
int n = Integer.parseInt("123");
That's the advice I would give to new Java programmers. As they learn more, they'll run into situations where they have to be more discerning, like when dealing with Maps or databases, but by then they should also have a better understanding of the difference between primitives and boxed primitives.
Autoboxing tempts us to believe int and Integer (for example) are interchangeable, but it's a trap. If you mix the two kinds of value indiscriminately, you can end up comparing two Integer values with == or trying to unbox a null without realizing it. The resulting bugs can be intermittent and difficult to track down.
It doesn't help that comparing boxed primitives with == sometimes works as if it were doing a value comparison. It's an illusion caused by the fact that values within a certain range are automatically cached in the process of autoboxing. It's the same problem we've always had with String values: comparing them with == sometimes "works" because you're actually comparing two references to the same, cached object.
When dealing with strings we can just tell the n00bs never to compare them with ==, as we've been doing all along. But comparing primitives with == is perfectly valid; the trick (thanks to autoboxing) is being sure the values really are primitives. The compiler will now let us declare a variable as an Integer and use it as if it were an int; that means we have to exercise a greater level of discipline and treat it as an error when someone does so without good reason.
Rather than calling them "complex types", you'd be best served thinking Integer, Double, etc. as "Classes", and int, double, etc. as "primitives".
If you're doing any type of sophisticated math, the Class-based numeric representation like Integer and Double will be cumbersome and slow you down - many math operations can only be done with primitives.
On the other hand, if you're trying to put your numbers into collections like Lists and Maps, those collections can only contain objects - and thus you must use (or convert to) classes like Integer and Double.
Personally, I use primitives whenever I can get away with it, and only convert to the Class representations like Integer when it's time to do input or output, and the transport requires those representations.
However, if you aren't doing any math at all, and instead are just passing the values straight through your code, you might save yourself some trouble by dealing with the Class-based forms (like Integer) exclusively.
I think this is a bit late but I wanted to add my opinion just in case.
in some scenarios, it's required to use the wrappers as the lack of a value is different from the default value.
example,
for one project I worked on, there was a field on screen where the user could enter a double value, the business requirement clearly mentioned that if the user enters a 0 the meaning is different from not entering a value and leaving the field blank and this difference will make an impact later on in a different module.
so in this scenario we had to use the Double object, since I cannot represent a lack of value using the primitive; since the primitive will default to 0 which was a valid input for the field.
I dont think there is any rule as such. I would choose the types over primitives (Integer over int) when I write method signatures, Maps, collections, Data Objects that get passed around. As such I would still like to use Integer instead of int even inside of methods etc. But if you think that is too much trouble (to type extra "eger") then it is okay to use ints for local variables.
If you want to setAttribute to session you have to use Object like Integer,Boolean,String in servlets. If you want to use value you can use primitive types. Objects may be null but primitives not. And if you want to compare types for primitives use == but objects use .equals because in object comparision == looks not values it looks if these are the same objects. And using primitives makes faster the code.
When we deal with Spring getRequest mapping methods, using boolean value does not work.
For instance :
#GetMapping("/goal")
public boolean isValidGoal() {
boolean isValid = true;
return isValid;
}
Always opt for Boolean in those cases.