-2

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?

CelineDion
  • 906
  • 5
  • 21

3 Answers3

0

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.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

The things after the period (.nextInt()) are called methods or functions.

Now to your actual question:

The method .nextInt() will return an integer, which will then be converted internally to a double, since every int is also a double if you ask for it explicitly (by saying double max=)

Also see: Why does Java implicitly (without cast) convert a `long` to a `float`?

cercle
  • 1
  • 3
-1

As others have indicated, this is an example of an implicit cast - you can assign an int to a double and it'll automatically be typecast (have the type changed) for you.

The basic idea here is that there's not really any serious harm in assigning an int to a double (other than consuming marginally more memory).

Note that the converse is not true - there could be serous harm in casting a double to int, so there is no implicit cast from double to int.