Search code examples
javacastingintdoubletypecast-operator

At last lines why he is using typecasting in double?


I'm new learner in java This is just a part of the code just i need to know why he is using typecasting here and why int specially?

double anynumber =(int) 32/8.5;


Solution

  • This:.

    (int) 32/8.5;
    

    casts 32 to an integer and not the result of the division to integer,
    because casting has higher precedence than division.
    But it is totally unnecessary since 32 is already an integer.
    So this:

    double anynumber =(int) 32/8.5;
    System.out.println(anynumber);
    

    will print:

    3.764705882352941
    

    just like if the casting was not there.
    But this:

    double anynumber =(int) (32/8.5);
    System.out.println(anynumber);
    

    will print:

    3.0
    

    because it applies the casting to the result of the division by truncating the decimal digits to create an integer.
    So to answer your question, if you found this line of code in a book or online,
    it does not do anything different than a simple:

    double anynumber = 32/8.5;