Use parseInt to create wrapper objects - java

I’m reading the book Beginning Java 9 fundamentals and in relation to creating wrapper objects the author says:
“All wrapper classes are immutable. They provide three ways to create
their objects:
1-Using constructors.
2-Using the valueOf() factory methods.
3-Using parseXxx() method, where Xxx is the name of the wrapper class. It is not available in the Character class.
The first and the second point I have clear, but the third I do not finish to understand it completely.
But the API says that Integer.parseXxx returns a primitive.
Does it make any sense?

The only way I see using parseXxx to create a wrapper object is to actually have the target type be a wrapper type itself. i.e:
Integer number = Integer.parseInt("123");
Yet, parseInt is not really creating a wrapper object but rather the value returned by parseInt is being autoboxed to its corresponding wrapper type.

Yes, the static method Integer.parseInt(String) attempts to parse the given string into a primitive integer. Failing to do that, it will throw an exception.
So basically, there is no need to wrap it, as it guaranteed either succeeding, or "letting you know" it couldn't by throwing.

A look at the source code of Integer class confirms that Integer.parseInt returns int primitive. Below is how the method signature,
public static int parseInt(String s, int radix)
The api basically Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, for api to work.
And it can be used as below, in java program, to get the int primitive from String
int newInt = Integer.parseInt("99");

Related

int or Integer in java [duplicate]

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

how to read appropriately on java document in terms of using methods

when I look at the java documents to see how to use methods.
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString()
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toString()
I find two methods that confuse me, first one is
static String valueOf(char[] data)
Returns the string representation of the char array argument.
that's the information I find on java docs, but I cannot find any information on how to use it, and how do I know I need to use String.valueOf() instead of something.valueof() based on java docs?
second method is
String toString()
This object (which is already a string!) is itself returned.
How do I know when it is to use Integer.toString() or something.toString() based on the information provided by java docs.
Could anyone tell me how to extract those information? This issue has bothered me for a long time. Happy holidays^_^
You need to have a method in a class before you can call it whether by using an instance of that class or using the class itself if it is static.
In the case here, valueOf() is only found in the String class and it is static so you can only call it using String.valueOf().
But that is not the case of toString() because it is not static and can be called through an instance like something.toString().
Basically they seem to perform the same function but valueOf() is treated special a bit. Such that it can take null values but toString() will throw a NullPointerException if variable of null value is used.
I cannot find any information on how to use String valueOf(char[] data), and how do I know I need to use "String.valueOf()" instead of something.valueof() based on java docs?
It's very straightforward. If you have a char array, and you want a String, you use this method. If you have something other than a char array, or you want something other than a String, you use a different method.
How do I know when it is to use Integer.toString() or something.toString() based on the information provided by java docs?
If you have an int or an Integer, and you want a String, then you use this method. If you have something that is not an int or an Integer, or you want something other than a String, you use a different method.
For instance, Double.toString() converts a double or a Double to a String.
Generally, you look at the class you want to convert to, and find a method that does the conversion. Sometimes, like the toString() method, the method is in the class you want to convert from.

Conversions of strings to Integer and to int

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.

Implicit cast to string - toString and int + ""

Why when i use this:
int a = 1;
methodWithParamString(a + "");
a is cast to String, bu i can't use toString() on integer?
int a = 1;
methodWithParamString(a.toString());
Doesn't this: a+"" works like: a.toString() + "" ?
No, it works like String.valueOf( a ) + "", which in turn behaves like new StringBuilder( String.valueOf( a ) ).append( "" ).toString().
The important thing to know is that it's all just done by the compiler, in other words it's syntactic sugar. This is why adding strings together in a loop isn't a good idea for example. (Although modern VMs might have some mechanism to reduce the performance overhead.)
a is cast to String
No. It is converted to a String. (You can't cast a primitive type to a String, either implicitly or explicitly.)
The details of this conversion are specified in the JLS - 15.18.1.1. The specification states that for a primitive type, the conversion is done "as if" you created an instance of appropriate wrapper type and then called toString() on it. This leaves the Java compiler the option of using other approaches provided that the end result is the same. (For reference types, the conversion turns null into "null" and other non-String types into String by calling toString().)
The JLS states that the concatenation is then performed "as if" by a call to String.concat(...), noting that the JLS explicitly permits optimization of sequences of concatenations. (JLS 15.18.1.2)
Doesn't this: a+"" works like: a.toString() + "" ?
True. it doesn't.
+ is overloaded internally. and Java doesn't support method calls on primitives.
The way this is accomplished in Java is actually a bit simpler than the other answers seem to suggest.
Using the string concatenation operator with a String and an object results in a call to that object's toString() method, then performs string concatenation.
Remember that whenever a primitive is passed to a context where an Object would be valid, Java performs "autoboxing", converting an int to an Integer, a double to a Double, etc.
So you can think of it as autoboxing followed by toString() followed by string concatenation.
At the same time, you should realize that the JLS string concatenation spec allows JVM implementations to optimize away the autoboxing, provided the result is the same, so your JVM may instead use a StringBuilder, or use any other valid JVM bytecode to create the resulting string, so the performance of the string concatenation operator is often better than performing boxing yourself would be.
Because int a - is not an object, it is primitive type.
So it doesn't have any methods.
You should use boxing:
Integer objectA = new Integer(a);
objectA.toString();
toString() is a method in Object class, any class that inherits from it will have that method, like Integer or String. But int is a primitive type not an Object, so the method does not exist.
No.int is a primitive type so it's not an object and can't have any methods.
Read this I think it will be helpful. There are wrapper classes for primitives for example Integer for int. You can call toString() method for them.
Actually String is a special class in java. And you can use + (and not only) operator for Strings and primitives. I think you'll find full answer to your question here.

auto boxing and boxing of wrapper classes

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.

Categories

Resources