Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

What's the difference between new integer and integer.valueof ( 123 )?


Asked by Julie Ali on Dec 05, 2021 FAQ



new Integer (123) will create a new Object instance for each call. According to the javadoc, Integer.valueOf (123) has the difference it caches Objects... so you may (or may not) end up with the same Object if you call it more than once. For instance, the following code:
One may also ask,
Since Integer is a wrapper class for int data type, it gives us more flexibility in storing, converting and manipulating an int data. Integer is a class and thus it can call various in-built methods defined in the class. Variables of type Integer store references to Integer objects, just as with any other reference (object) type.
Besides, Integers can be described as whole numbers meaning that they do not have any fractional parts. Integers also include negative numbers. It is important to mention that 0 is also included in the list of integers.
Likewise,
Integers also include negative numbers. It is important to mention that 0 is also included in the list of integers. Zero is considered to be neutral which means that it is neither negative nor positive.
In respect to this,
Integer.valueOf() returns an Integer object, while Integer.parseInt() returns an int primitive. parseInt() parses String to int while valueOf() additionally wraps this int into Integer. That's the only difference. If you want to have full control over parsing integers, check out NumberFormat with various locales.