I have this code here:
public class Main {
public static void main(String[] args) {
System.out.println(Math.round(12.5));
System.out.println(round(12.5));
}
public static double round(double integer) {
return Math.round(integer);
}
}
When I run the code it outputs:
13
13.0
Why is it that when I run Math.round()
normally inside the main method, it provides an integer value, while it provides a double value inside the "round" method? I know that my method is of type "double" but Java doesn't let me change it to "int." Any reason behind this? Thanks.
In the call to :
Math.round(12.5)
12.5 is evaluated as a double
and the method, Math#round
, with the following signature is called:
public static long round(double a)
because it returns a long
it will print without any decimal place (i.e., 13). In the second print statement, however, you use:
public static double round(double integer) {
return Math.round(integer);
}
which returns a double
, hence the decimal value 13.0.