
I'd favour using for generating random integers. 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. You'll always get 0 because casting has higher precedence than multiplication. you type int notSoRandomNumber=(int) Math.random()*5

You see, if you forget a parenthesis, i.e. Yes, this does indeed give a random integer between 0 and 4, but this is very much not the proper way of doing this. int randomNumber=(int) (Math.random()*5) No, casting to int will only work for primitive values, and in Java a String is not a primitive. What about this casting then (int) ? Can we use this to convert a string to an int too ? You cannot pass any other type to the parseInt method or you will get a compiler error. So does this mean that parseInt() is ONLY to convert String into integer ?Ĭorrect. 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.Īlso I made a search and it says parseInt() takes string as an argument. You have to take into account what the type of the value you are converting is. Why two different ways to make a value an int ? Instead, you use a method to parse the String and return the value. Because of this there is no first order language feature for converting a String to an int. "5", "042", and "1,000" all have integer representations, but something like "Hello, World!" does not. 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. The string "5" is not immediately convertible to an integer. Now take a look at the conversion of a String to an int: int value = Integer.parseInt("5") 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."

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. What you're trying to do is assign that value to a variable of type int. Thus the expression Math.random()*5 has a type of double. Math.random returns a double, and when you multiply a double by an int Java considers the result to be a double. Let's take a look at your first example: int randomNumber=(int) (Math.random()*5)

Integer.parseInt does not do the same thing as a cast.
