Integer.parseInt does not do the same thing as a cast.
Let's take a look at your first example:
int randomNumber=(int) (Math.random()*5)
Math.random returns a double, and when you multiply a double by an int Java considers the result to be a double. Thus the expression Math.random()*5 has a type of double. What you're trying to do is assign that value to a variable of type int. By default Java will not allow you to assign a double value to a variable of type int without your explicitly telling the compiler that it's ok to do so. Basically you can think of casting a double to an int as telling the compiler, "I know this int variable can't hold the decimal part of this double value, but that's ok, just truncate it."
Now take a look at the conversion of a String to an int:
int value = Integer.parseInt("5");
The string "5" is not immediately convertible to an integer. Unlike doubles, which by definition can be converted to an integer by dropping the decimal part, Strings can't be easily or consistently converted to an int. "5", "042", and "1,000" all have integer representations, but something like "Hello, World!" does not. Because of this there is no first order language feature for converting a String to an int. Instead, you use a method to parse the String and return the value.
So to answer all your questions:
Why two different ways to make a value an int ?
You have to take into account what the type of the value you are converting is. If you're converting a primitive to an int you can use a cast, if you're converting an Object you'll need to use some sort of conversion method specific to that type.
Also I made a search and it says parseInt() takes string as an argument.. So does this mean that parseInt() is ONLY to convert String into integer ?
Correct. You cannot pass any other type to the parseInt method or you will get a compiler error.
What about this casting then (int) ?? Can we use this to convert a string to an int too ?
No, casting to int will only work for primitive values, and in Java a String is not a primitive.
Answer from Mike Deck on Stack Overflowjava - Integer.valueOf() vs. Integer.parseInt() - Stack Overflow
java - Difference between Integer.parseint vs new Integer - Stack Overflow
Integer.valueOf() and parseint()
Integer.parseInt is best way to convert String to Int in Java? - Stack Overflow
Integer.parseInt does not do the same thing as a cast.
Let's take a look at your first example:
int randomNumber=(int) (Math.random()*5)
Math.random returns a double, and when you multiply a double by an int Java considers the result to be a double. Thus the expression Math.random()*5 has a type of double. What you're trying to do is assign that value to a variable of type int. By default Java will not allow you to assign a double value to a variable of type int without your explicitly telling the compiler that it's ok to do so. Basically you can think of casting a double to an int as telling the compiler, "I know this int variable can't hold the decimal part of this double value, but that's ok, just truncate it."
Now take a look at the conversion of a String to an int:
int value = Integer.parseInt("5");
The string "5" is not immediately convertible to an integer. Unlike doubles, which by definition can be converted to an integer by dropping the decimal part, Strings can't be easily or consistently converted to an int. "5", "042", and "1,000" all have integer representations, but something like "Hello, World!" does not. Because of this there is no first order language feature for converting a String to an int. Instead, you use a method to parse the String and return the value.
So to answer all your questions:
Why two different ways to make a value an int ?
You have to take into account what the type of the value you are converting is. If you're converting a primitive to an int you can use a cast, if you're converting an Object you'll need to use some sort of conversion method specific to that type.
Also I made a search and it says parseInt() takes string as an argument.. So does this mean that parseInt() is ONLY to convert String into integer ?
Correct. You cannot pass any other type to the parseInt method or you will get a compiler error.
What about this casting then (int) ?? Can we use this to convert a string to an int too ?
No, casting to int will only work for primitive values, and in Java a String is not a primitive.
In your example, you are casting a floating-point number to an int. Integer.parseInt(), however, reads an integer value from a String.
Actually, valueOf uses parseInt internally. The difference is parseInt returns an int primitive while valueOf returns an Integer object. Consider from the Integer.class source:
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s, 10);
}
public static Integer valueOf(String s, int radix) throws NumberFormatException {
return Integer.valueOf(parseInt(s, radix));
}
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
As for parsing with a comma, I'm not familiar with one. I would sanitize them.
int million = Integer.parseInt("1,000,000".replace(",", ""));
First Question: Difference between parseInt and valueOf in java?
Second Question:
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();
Third Question:
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(',');
df.setDecimalFormatSymbols(symbols);
df.parse(p);
They use the same implementation :
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
The main difference is that parseInt returns a primitive (int) while the Integer constructor returns (not surprisingly) an Integer instance.
If you need an int, use parseInt. If you need an Integer instance, either call parseInt and assign it to an Integer variable (which will auto-box it) or call Integer.valueOf(String), which is better than calling the Integer(String) constructor, since the Integer constructor doesn't take advantage of the IntegerCache (since you always get a new instance when you write new Integer(..)).
I don't see a reason to ever use new Integer("5"). Integer.valueOf("5") is better if you need an Integer instance, since it will return a cached instance for small integers.
The Java documentation for Integer states :
The string is converted to an int value in exactly the manner used by the parseInt method for radix 10.
So I guess its the same.
Hello, i have started learning java recently by mooc. But during this course, it uses Integer.valueOf while taking integer inputs, I use same way but whenever i do it intellij suggests me parseint(). And I wonder if it is better to use parseint?
parseInt is the way to go. The Integer documentation says
Use parseInt(String) to convert a string to a int primitive, or use valueOf(String) to convert a string to an Integer object.
parseInt is likely to cover a lot of edge cases that you haven't considered with your own code. It has been well tested in production by a lot of users.
I invite you to look at the source code of the parseInt function. Your naïve function is faster, but it also does way less. Edge cases, such as the number being to large to fit into an int or not even being a number at all, will produce undetectable bogus results with your simple function.
It is better to just trust that the language designers have done their job and have produced a reasonably fast implementation of parsing integers. Real optimization is probably elsewhere.
I tried both of them in my program and both of them appear to do the same thing, but I want to know which one is better if there is even a difference.
I dont fully understand the difference between the two. They do exaxtly the same thing. Im assuming with Integer.parseInt(x.nextLine()) it can detect both a string and an Int and nextInt only can detect an Int. Is this right? Or are they bothe the same. Which one do real programmers in the real world use most? Thank you guys!