in wrapper classes we have two types of methods parseXxx() and valueOf() in every wrapper class for interconversion between primitive and wrapper objects.recently java 1.5 introduced auto boxing and boxing.so why they didn't deprecate those methods.
Because Autoboxing and Auto Unboxing are just compile time features. Try writing something like this in your source file and then have a look at the decompiled code:
Integer i = 10;
Decompiled code:
Integer i = Integer.valueOf(10);
Similarly,
int i = new Integer(100);
will give you the below when decompiled:
int i = (new Integer(100)).intValue();
Thus, the JVM still heavily relies on these methods at runtime, though it's masked when you write the code.
Well, parseXxx() is entirely unlike boxing; it turns a String into a primitive object. valueOf(), on the other hand, is actually used in boxing -- it either constructs a new wrapper object, or it fetches an existing one from a cache, depending on the value. The Java compiler generates a call to valueOf(), and that's precisely what boxing means.
1. There can be value sometimes in explicitly stating some conversion (for the clarity of e.g. some unobvious/obscure case).
2. Wouldn't that deprecation result in old programs becoming excessively littered with deprecation warnings?
As the command line arguments are treated as String Array, but given the condition when you are expecting command line argument other than String datatype(that may be primitives) i.e. boolean, int, byte, short, long, float, double, char than you need to parse the argument into the one what your program expects and here you use parseXXX() methods, to be precise parseXXX method take String argument and return the appropriate data type which you are trying to parse into.
Related
This question already has answers here:
What is the difference between an int and an Integer in Java and C#?
(26 answers)
Closed 2 years ago.
I have seen many times in code that people use int or Integer to declare variable in beans. I know int is datatype and Integer is wrapper class.
My question is, in which condition int or Integer should be used and is there any advantage of either of them over another?
My question is, in which condition int or Integer should be used and is there any advantage of either of them over another?
Well, you should use the reference type Integer whenever you have to. Integer is nothing more than a boxed int. An Object with a single field containing the specified int value.
Consider this example
public class Ex {
int field1;
Integer field2;
public Ex(){}
}
In this case field1 will be initialized with the value 0 while field2 will be initialized with null. Depending on what the fields represent, both approaches might be advantageous. If field1 represents some kind of UUID, would you want it to be initialized with a zero value?
I wouldn't worry too much about the performance implications of Autoboxing. You can still optimize after you get your code running.
For more information take a look at the documentation
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Integer.html
You always use int, pretty much.
Integer should rarely be used; it is an intermediate type that the compiler takes care of for you. The one place where Integer is likely to appear is in generics, as int is simply not legal there. Here is an example:
List<Integer> indices = new ArrayList<Integer>();
int v = 10;
indices.add(v);
The above works: It compiles with no errors and does what you think it would (it adds '10' to a list of integer values).
Note that v is of type int, not Integer. That's the correct usage; you could write Integer here and the code works as well, but it wouldn't be particularly idiomatic java. Integer has no advantages over int, only disadvantages; the only time you'd use it, is if int is straight up illegal. Which is why I wrote List<Integer> and not List<int> as the latter is not legal java code (yet - give it a few versions and it may well be legal then, see Project Valhalla).
Note also that the compiler is silently converting your v here; if you look at the compiled code it is as if javac compiled indices.add(Integer.valueOf(v)) here. But that's fine, let the compiler do its thing. As a rule what the compiler emits and what hotspot optimizes are aligned; trust that what javac emits will be relatively efficient given the situation.
int is a primitive type, a value type for number literals.
it is used whenever and wherever you just want to do some basic arithmetical operation;
it is a value type, so it's stored in the Stack area of the memory, hence operations on it are much faster;
whenever it's needed, compiler implicitly and automatically casts back and forth (a.k.a Boxing and Unboxing) from int to Integer and vice versa;
Integer is a Class, which is a reference type and you instantiate an Object of that type.
you create an object of that class, which means, that you also have some methods and operations on that object;
any time you do some arithmetic operation on the instance of Integer, under the hood, it's still implemented by int primitives, and it's just wrapped into box/container;
it is a reference type / object, which is very important, as you can Serialize or Deserialize it;
it also has some very useful utility factory methods, like Integer.valueOf(..) for example, to parse the String as an integer;
it can be well used into declarations of the generic types and it, as a class, supports the hierarchy as well. For instance, it extends Number, and you can make use of this;
it is stored in the Heap area of the memory.
int is a primitive and Integer is an object .
From an memory footprint point of view , primitive consume less memory than object and also primitives are immutable (since they use pass by value ) .
Here is a good article on when to use what :
https://www.baeldung.com/java-primitives-vs-objects
int i = 10;
i++; // it ok primitive value can use ++.
Integer integer = 10;
integer++; // how it can use ++
MyClass myClass = new MyClass();
myClass++; // then why myclass can't use ++.
C++ has the ability to overload operators. The Java language considers this to be open to too much abuse (overloaded operators can be obfuscating) so it was never incorporated into Java.
Therefore, you can't write myClass++ as the syntax is not available to specify that operation.
But ++ does work on a selection of non-primitives. The mechanism exploited is called autoboxing. (Essentially the underlying plain-old-data type is extracted from the boxed type, incremented then re-boxed to the original reference type).
Somewhat related to this is the ability to apply += and + to java.lang.String instances. Simply put, this is a special case. Although fully aware of the risk of downvotes I regard this as one of the worst kludges in Java, particularly += which will create a new instance of a string (as strings themselves are immutable), and many Java programmers will be unaware of the effect this has on memory.
It is because of Java's autoboxing feature which is added in Java 1.5
The compiler will convert the statment as follow
Integer integer = 10;
integer.iniValue++;
You can try to add the compiler flag "javac -source 1.4" and it will return an error
From the Link provided in a comment by Konstantin V. Salikhov,
Integer has a defined method to return an int, which then has the ++ operator defined.
MyClass has no ++ operator, hence myClass++; is invalid
The method in question goes like:
Integer myInteger = 10;
myInteger.intValue++;
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.
Operator overloading in Java has a description (as to it being not allowed) at Operator overloading in Java
In some code I see this:
private void compute(Long a, Long b, Long c) {
long result = a-(b+c);
...
It seems a bit strange that the result is stored in a primitive long instead of a Long object corresponding to its operands.
Are there any reason that a result should be stored as a primitive?
It seems a bit strange that the result is stored in a primitive long instead of a Long object corresponding to its operands.
No, what is "strange" is that you can use the + and - operators on Long objects. Before Java 5, this would have been a syntax error. Then autoboxing/unboxing was introduced. What you're seeing in this code is autounboxing: the operators require primtives, so the compiler automatically inserts a call to longValue() on the objects. The arithmetic is then performed on primitive long values, and the result is also a long that can be stored without further conversion on the variable.
As for why the code does this, the real question is why someone would use the Long type instead of long. Possible reasons:
The values come from some library/API that delivers Long values.
The values are stored in collections (List, Map), which cannot hold primitives.
Sloppiness or cargo cult programming.
The ability to have null values is required, e.g. to signal unavailable or uninitialized data.
Note that the ability of Long to hold null values means that the calculation (or more specifically, the longValue() calls inserted by the compiler) can fail with a NullPointerException - a possibility the code should deal with somehow.
The reason is obvious: result is declared as primitive.
The arithmetic operators + and - are not defined for boxed types (e.g. Long) but for primitive types (e.g. long).
The result is also a long. See Autoboxing and Unboxing tutorial
Autoboxing this into a Long would result in a small performance cost. It is also unnecessary because
We know it will be non-null (if a, b or c were null, a NullPointerException would occur).
It would be autoboxed implicitly if we use it later where a Long is required.
Based on your needs.I mean the decelaration.
Autoboxing and unboxing can happen anywhere where an object is expected and primitive type is available
Usually you should prefer using primitives, especially if you are certain they cannot be null. If you insist on using the boxed types always think extra hard about what happens when it is null.
Java will do the boxing and unboxing automatically for you, but staring at an int and wondering why you got a NullPointerException can be fun.
From Java 1.5 onwards, autoboxing and unboxing occurs implicitly whenever needed.
The following line:
long result = a-(b+c);
...asks Java to take the result of the expression using 3 Longs, and then store it in a primitive long. Before Java 5, it would complain about the types not matching - but these days it just assumes you mean what you say and automatically does the conversion from object to primitive type for you.
In this example however, unless there's some other good reason not presented here, there's absolutely no point having the parameters as the boxed, object type in the first place.
As per the javadoc
Boxing conversion converts expressions of primitive
type to corresponding expressions of reference type.
Specifically, the following nine conversions are called the boxing conversions:
From type boolean to type Boolean
From type byte to type Byte
From type short to type Short
From type char to type Character
From type int to type Integer
From type long to type Long
From type float to type Float
From type double to type Double
From the null type to the null type
Ideally, boxing a given primitive value p, would always yield an identical reference.
In practice, this may not be feasible using existing implementation techniques. The
rules above are a pragmatic compromise. The final clause above requires that certain
common values always be boxed into indistinguishable objects. The implementation may
cache these, lazily or eagerly. For other values, this formulation disallows any
assumptions about the identity of the boxed values on the programmer's part. This would
allow (but not require) sharing of some or all of these references.
This ensures that in most common cases, the behavior will be the desired one, without
imposing an undue performance penalty, especially on small devices. Less memory-limited
implementations might, for example, cache all char and short values, as well as int and
long values in the range of -32K to +32K.`
Here is the Oracle Doc source
The answer for your doubt is
autoboxing and autounboxing in Java which converts from primitive to wrapper class objects and vice versa respectively.
autoboxing means internally compiler uses valueOf() method of primitive classes ans autounboxing means internally compiler uses xxxValue() method.
Suppose for
private void compute(Long a, Long b, Long c) {
long result = a-(b+c);
its makes this conversion a.longValue()-(b.longValue()+c.longValue())
Which means even before your statement performs addition the compiler provides the primitives of long type as input to your operands
Remember that this goes in hand as JAVA is statically and strongly typed language.
Hence you get long type output
I hope i cleared your doubt
Given that String s has been declared, the following 5 lines of code produce the same result:
int i = Integer.valueOf(s);
int y = Integer.parseInt(s);
int j = Integer.valueOf(s).intValue();
Integer x = Integer.valueOf(s);
Integer k = Integer.valueOf(s).intValue();
Are there circumstances where each one would be the preferred code? It appears that int and Integer are interchangeable and that .intValue() is not needed.
If you require an int, use parseInt(), if you require an Integer use valueOf(). Although they're (sort of) interchangeable now, it still makes more sense to use the one that directly returns the data type that you require. (Historically, they weren't interchangeable at all, this was introduced with auto-boxing and unboxing in Java 5.)
The intValue() method you're using is just converting the Integer class type to the int primitive, so using that and valueOf() is the worst possible combination, you never want to use that. (Nothing bad will happen, it's just longer to read, performs slightly worse and is generally more superfluous.)
If you don't care or don't know, then I'd use parseInt(). Especially as a beginner, it's more common that you want the primitive type rather than the class type.
int and Integer are made to look interchangeable by the magic of auto-boxing and auto-unboxing: In many cases where you need one but have the other, the compiler automagically inserts the necessary code to convert them.
This is useful, but if you know about it, you can avoid it in many places which results in slightly faster code (because there's less conversion to do).
Integer.parseInt() returns an int, so you should use it if you need an int
Integer.valueOf() returns an Integer, so you should use it if you need an Integer
Integer.valueOf().intValue() first creates an Integer and then extracts the int value from it. There's no good reason to use this instead of a simple Integer.parseInt().
The decision between int and Integer is easy to do as well:
generally you'd want to use the primitive type (int), if possible
if you need an Object (for example, if you want to put your number in a Collection), then you need to use the wrapper type (Integer), as the primitive type can't be used here.
int and Integer are not interchangeable.Because of Autoboxing feature fron java 5 onwards, int to Integer conversion is taken care by jvm itself.But we should not use Integer class unnecessarily.Primitive data types are always faster.Wrapper classes should be used only required.
In Java, I can do the following to succinctly guard against a NullPointerException:
if ("myString".equals(someOtherString))
But I cannot do the same with Integers, e.g.
if (5.equals(someOtherInteger))
I get a compile-time error. Any ideas on why this design decision was made? Or any resources that might explain it? Thanks in advance.
EDIT: someOtherInteger is an Integer, not an int.
String has always been an object in Java. There is no autoboxing for strings, and there can't be in principle. Autoboxing from the primitive int to the Integer object has been introduced fairly recently.
It is valid to ask why trying to access member variables of primitives doesn't invoke autoboxing (95.toString(radix) would actually be pretty convenient), but I imagine that the reason is that it wasn't considered a likely use-case, since since almost every wrappedPrimitive.method() has an equivalent WrapperClass.method( primitive ) version.
equals() is usually unnecessary for primitive types since == is already there. However, you do make a good case for it as a null-guard... 5 == integerInstance will try to unbox the instance, and throw a NullPointerException if the instance is null, unfortunately. (I didn't fully appreciate your point at first.)
That said, it would be really cool if we could hear from someone working on Java either currently or at the introduction of autoboxing about whether they considered this sort of functionality.
The JLS specifies that boxing conversions can only occur during assignment conversions, method invocation conversions, or casting conversions. Since you are neither assigning 5 to a variable, passing it as an argument to a method, nor explicitly casting it to Integer, it will not be autoboxed for you.
Assignment conversion (§5.2, §15.26) converts the type of an
expression to the type of a specified variable.
Assignment conversion may cause an OutOfMemoryError (as a result of
boxing conversion (§5.1.7)), a NullPointerException (as a result of
unboxing conversion (§5.1.8)), or a ClassCastException (as a result of
an unchecked conversion (§5.1.9)) to be thrown at run-time.
Method invocation conversion (§5.3, §15.9, §15.12) is applied to each
argument in a method or constructor invocation and, except in one
case, performs the same conversions that assignment conversion does.
Method invocation conversion may cause an OutOfMemoryError (as a
result of boxing conversion (§5.1.7)), a NullPointerException (as a
result of unboxing conversion (§5.1.8)), or a ClassCastException (as a
result of an unchecked conversion (§5.1.9)) to be thrown at run-time.
Casting contexts allow the use of one of:
...
a boxing conversion (§5.1.7) optionally followed by a widening
reference conversion (§5.1.5)
you can use
if (someOtherInteger!=null && someOtherInteger == 5)
I suspect that autoboxing is not implemented for the literal 5, whereas it is for a string myString, as a safety measure. It's safe to autobox a syntactic structure that is prepended and appended with double quotation marks "", because it's unlikely that the quotation marks are unintended, so the user's intention is clear and type-safety is not compromised.
However, the literal 5 could be a typo on the user's part - or it could be intended to be a string, rather than an integer. Therefore, to maintain the benefit that variables must be declared before use in object-oriented programming in order to prevent typos (among many other advantages) (even if it's implicit, as in the case of autoboxing), 5 is not autoboxed.
Here is a bit of reading on the different comparisons:
http://www.leepoint.net/notes-java/data/expressions/22compareobjects.html
Not sure if it was a built in design to reject int
If you do
Integer s=5;
Integer d=5;
if(d.equals(s)){
System.out.println("Fun");
}
It works just fine.
int is a primitive type it doesn't support any methods itself. To compare 2 ints you simply use the == convention as in:
if(a == b)
There is an Integer class that is a wrapper for an int that supports some other method calls
Edit:
Based on your edit you want to compare to Integer but the problem is the literal 5 isn't an Integer you have to create a new integer for it.
Integer myInt = 5;
if(myInt.equals(someOtherInteger)) ...
This design is inherent in the fact that primitives don't have any methods. As to whether primitives should support methods (or simply not exist) is integral to the debate as to whether Java is a Pure Object Oriented Language or not (many say no due to the fact that primitives exist).