Using (int) in Java


Some time ago, I noticed that sometimes a type of data appears in the following way.


Which I do not understand so that it is done. Some of the cases in which I have seen it, are the following:

suma = (int) (math.random * (4+3));

The question is:

What is it used for, what is its function or purpose?

asked by José Miguel Sepulveda 21.04.2017 в 13:35

2 answers


(int) is a cast to a primitive. Since the JDK 1.5 is no longer necessary when casting Integer objects to primitives (int) by boxing and unboxing. In your case what you are doing is a casting of a double primitive that returns math.Random to an int primitive that has no decimal value. Casting is used to convert one object or primitive into another.

Documentation here

answered by 21.04.2017 / 13:39

If you look at the documentation of Math.random() you see that the function returns Double .

(int) serves to cast the Double to int and thus remove the decimal part of the number.

What you are saying in the comments on the difference between Parsear and Castear would be basically that:

  • Casting takes the representation of that variable and represents it with another type. In this case, Double to Int . Not all types can be casted to others, since their internal representation of the variable is not compatible. For this there is the parsimony.

  • Parsear would be something closer to the human and converts one type of variable to another, such as String to Int with parseInt . Ex: "7" -> 7

answered by 21.04.2017 в 13:38