Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beginner Java Question about Integer.parseInt() and casting

so when casting like in the statement below :-

int randomNumber=(int) (Math.random()*5)

it causes the random no. generated to get converted into an int..

Also there's this method I just came across Integer.parseInt() which does the same !

i.e return an integer

Why two different ways to make a value an int ?

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 ?

What about this casting then (int) ?? Can we use this to convert a string to an int too ?

sorry if it sounds like a dumb question..I am just confused and trying to understand

Help ?

like image 644
Serenity Avatar asked May 20 '10 15:05

Serenity


1 Answers

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.

like image 155
Mike Deck Avatar answered Sep 20 '22 00:09

Mike Deck