-2

Why can't I use the parseDouble method to convert int to double in Java?

I tried to convert int to double with the parseDouble method in java, but I got an error. Instead of parseDouble, I use newDouble method, I get output. Why didn't the parseDouble method work?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 7
    "Why i can't use parseDouble method to convert int to double in java?" - because that's not what it's there for. It's there to parse a *text* representation. To convert an `int` to `double` in Java you don't need a method at all - there's an implicit conversion: `int x = 5; double y = x;` – Jon Skeet Feb 25 '23 at 06:52
  • 2
    from the [documentation](https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/lang/Double.html#parseDouble(java.lang.String)) you can see that this method accepts a `String` argument and not an `int`, so it cannot be used to convert an `int` (it will be able to convert a `String` with an `int` value, e.g. `Double.parseDouble("123")`, but only because it also is a valid `double` representation) – user16320675 Feb 25 '23 at 08:00

1 Answers1

4

Note that the declaration of the Double.parseDouble() method in Java is as follows.

public static double parseDouble(String s)

Since the parseDouble method accepts a String argument, you cannot pass an int value as an argument. If you pass an int value for the parseDouble method, you will get the error: incompatible types: double cannot be converted to String exception.

Furthermore, you can refer to this answer to find out the proper way of converting an int to a double.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Kavindu Nilshan
  • 569
  • 6
  • 17