Search code examples
javaprimitiveprimitive-types

Why is it that I can declare a numerical variable as a double but still use .nextInt()?


Okay, I'm new to coding so I am unfamiliar with everything. Here's my question:

Why is it that .nextInt(); will process a double even though the name is .nextInt();?

double max = scan.nextInt();

This works, but why?


Solution

  • If you peek into the java-doc you'll actually see that nextInt() returns int as the method name suggests.

    In your specific example, the value returned from nextInt() is widened to a double as every int can fit into a double type.