-1

Since int is less precise than double I thought I needed to cast it when parsing it into a method. Yet the following code runs fine. Why?

public class MyClass {

    public static void main(String[] args) {
        System.out.println(met(3/2));
    }

    static String met(int i){
        return "This is what I get " + i;
    }

}
ocram
  • 1,384
  • 6
  • 20
  • 36
  • 1
    I don't see any `double`s here. – rgettman Apr 22 '16 at 18:42
  • 1
    I thought it's 3/2 – ocram Apr 22 '16 at 18:42
  • 9
    `3/2` is not a double. It is an `int` with the value of `1`. `3.0/2.0` is however a `double` with the value of `1.5`. – RaminS Apr 22 '16 at 18:42
  • 3
    I see your next question in SO will be: *why is this code printing zero ? System.out.println(met(3/4));* – ΦXocę 웃 Пepeúpa ツ Apr 22 '16 at 18:46
  • Related (not necessary duplicate since you are asking about compilation aspect and not runtime results but still you should probably read these questions): http://stackoverflow.com/questions/7220681/division-of-integers-in-java http://stackoverflow.com/questions/3144610/integer-division-how-do-you-produce-a-double – Pshemo Apr 22 '16 at 18:55

1 Answers1

1

When you do 3/2 that won't give you a double result. Integer division happens and result gets truncated to an integer. Hence there is no need of cast. In order to get double result, either needs to be cast to double so that get a compiler error to get it casted to double.

Try doing met(3d / 2), then you run into the compiler error which you are expecting.

Andreas
  • 154,647
  • 11
  • 152
  • 247
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • 2
    @Pillar I upvoted just based on that comment, as I think you've gone past the point of rudeness about how much to worry about finding duplicates. – Louis Wasserman Apr 22 '16 at 18:47
  • 3
    @Pillar I didn't find a duplicate and hopefully someone do it soon. Thanks that you explained your down vote at least unlike many others. One last thing, things you don't like are not garbage. – Suresh Atta Apr 22 '16 at 18:52