-3

When I assign some value (< 1) to float or double without any suffix 'f' or 'd' respectively, then why the output shows 0.0? My program is

  public class Example {

    double a = 1/2d;
    float b = 1/2f;
    double c = 1/2;
    float d = 1/2;

    public static void main(String[] args) {
        Example e = new Example();
        System.out.println("a: "+e.a);
        System.out.println("b: "+e.b);
        System.out.println("c: "+e.c);
        System.out.println("d: "+e.d);
    }
}

The output is

  a: 0.5
  b: 0.5
  c: 0.0
  d: 0.0

Abhishek Kumar
  • 283
  • 3
  • 12
  • 4
    `1/2` is **not** a value less than `1`, it is: `1`, the divide operator, `2`. Integer division is truncating and the result is `0`. – Boris the Spider Apr 02 '18 at 15:05

1 Answers1

1

d stands for double, and f stands for float

According to the actual calculation, 1/2d will give you 0.5

but if you do not specify type then compiler will convert this into integer literal then it shows 0.0

you can read up on the basic primitive types of java here

http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

casillas
  • 14,727
  • 15
  • 94
  • 183
  • 2
    I think the confusion is that the OP has written `1/2` and thinks that this is a numeric literal. But it's obviosuly not. – Boris the Spider Apr 02 '18 at 15:06
  • Please review your answer - it seems contradicting and ambiguous. You seem to suggest that the double `a = 1/2d` would still print a as `0.0` instead of `0.5`? – YoYo Apr 02 '18 at 15:13