views:

351

answers:

5

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 ?

+4  A: 

In your example, you are casting a floating-point number to an int. Integer.parseInt(), however, reads an integer value from a String.

Carl Manaster
oh doesn't Math.random() generate a double ?
Serenity
double and float are floating-point types:)
Petar Minchev
oh right.I misread it as only float
Serenity
+1  A: 

Casting can only convert from one numeric type to another. Interpreting a string (aka parsing) needs to be done with a method call.

Paul Tomblin
+3  A: 

You can only cast between compatible types (I'd link to the JLS but that might be too much for a beginner question).

Casting is basically just taking a value and saying, "Hey, this thing that was a double? Now it's an int. So there."

You can't do that with a string because it isn't anything like an int. You have to instead parse an int out of it, which is actually a lot harder than it sounds. Fortunately, it's already implemented for you so you don't have to worry about how it works.

Michael Myers
ah ok..I get it now..thanksbut hey I was actually thinking about having a look at these method's codes ie those of parseInt() and random() ... I just wanted to see how they are actually working(I know I won't understand it all but will get an idea atleast)..where do I find Integer and Math classes ? Where are they stored on my PC ?
Serenity
oh and what is JLS ?
Serenity
@happysoul: Depending on how you installed the JDK, you might have a zip file called src.zip in C:\Program Files\Java\(your JDK folder). Open it and look in java\lang to find Integer and Math. Alternatively, if you have an IDE properly set up, you might be able to just ctrl+click on the method name to jump right to it.
Michael Myers
JLS = [Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html).
Michael Myers
cool..thanks :)No I am not using any IDE as of now
Serenity
@happysoul: install one. It may slow you down in the first day or so, but the rest of your learning experience will be so much smoother.
polygenelubricants
+3  A: 

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.

Mike Deck
wow..thanks to all ! things make sense now..I just tried passing a word to parseInt() ..it displayed an error saying some exception in thread
Serenity
@happysoul Exactly! Take a look at the javadoc for that method: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String), notice that it says it will throw a NumberFormatException if the string you pass in is not a parsable int.
Mike Deck
I just did..thanks for the link
Serenity
+1  A: 

Let's start from the top.

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

Yes, this does indeed give a random integer between 0 and 4, but this is very much not the proper way of doing this. You see, if you forget a parenthesis, i.e. you type

int notSoRandomNumber=(int) Math.random()*5;

you'll always get 0 because casting has higher precedence than multiplication. That is to say the result of Math.random() is first coerced into an integer, which will always be 0 and then it's multiplied by 5, which is still 0.

I'd favour using java.util.Random for generating random integers. q.v. http://java.sun.com/javase/6/docs/api/java/util/Random.html#nextInt(int).

Casting can only be done between "compatible types". For primitive types and their wrappers (i.e. int, Integer, long, Long, &c.) you can always cast between them with the caveat that some conversions lose information. e.g. when casting a long to an int, the long may contain a number larger than Integer.MAX_VALUE]. This kind of casting Java basically got from C++ which it in turn got from C.

As for casting objects, it's actually simpler. Simply ask "is this object, o, an X?" If so then (X) o makes sense and has static type X. If o is not an X and you try to cast anyway, you'll get a ClassCastException signifying that o's dynamic (runtime) type is not compatible with X. This will probably make a lot more sense later when you get the difference between the static and the dynamic (runtime) type of objects.

kahen