简体   繁体   中英

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 !

ie 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 ?

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.

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.

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

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, ie 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. qv 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 (ie int, Integer, long, Long, &c.) you can always cast between them with the caveat that some conversions lose information. eg 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.

Following code convert String to int without any methods

public class MyStringToNumber {

    public static int convert_String_To_Number(String numStr){

        char ch[] = numStr.toCharArray();
        int sum = 0;
        //get ascii value for zero
        int zeroAscii = (int)'0'; // '0'=48 zeroAscii=48
        for(int i=0;i<ch.length;i++){
            int tmpAscii = (int)ch[i]; // for 0  ch[i]=3,3=51, tempAscii=51
                                       //         (0*10)+(51-48)
                                       //         0     +3
                                       //         3
                                       //      sum=3
                                       // for 1  ch[i]=2,2=50, tempAscii=50            
            sum = (sum*10)+(tmpAscii-zeroAscii);  // 0 +(51-48)=3 sum=3
                                                  // (3*10)=30+(50-48)
                                                  //           30  +  2
                                                  //   sum=32
                                       // for 2  ch[i]=5, 5=53 tempAscii=53
                                       //         (32*10)+(53-48)
                                       //          320   + 5
                                       //          325     
                                       //  sum=325
                                      // for 3   ch[i]=6,6=54, tempAscii=54
                                      //         (325*10)+(54-48)
                                      //         3250 +6
                                     //         3256
                                     //    sum=3256
        }
        return sum;
    }

    public static void main(String a[]){

        System.out.println("\"3256\" == "+convert_String_To_Number("3256"));
    }
}

Output "3256" --> 3256

  1. Parse() method is available is many formats, Integer class having the method ParseInt() which is a static method, we to call this method by Integer.ParseInt()

  2. Similarly Double class having ParseDouble()and we call it as Double.ParseDouble().

  3. The more Generic way is XXXX.ParseXXXX()

  4. The main use of this Method is to convert any Object into a Primitive.

  5. And here you can raise a question why we need to convert into Primitives? The answer is, we know that primitives are stored in stack area and objects are stored in Heap area, and you doesn't want to waste the Heap Memory and you can convert an Object into a Primitive.

  6. And the other thing, while accessing any Object there may be Overhead. It is better to use as a Primitive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM