0

I am trying to learn interesting behaviour of java. Please explain

    double z  = 1/3;
    System.out.println(z);

This program return 0.0 where as

    double z  = 1/3d;
    System.out.println(z);

This program prints 0.333333. What is the difference.

user2864740
  • 60,010
  • 15
  • 145
  • 220
Alex
  • 1,406
  • 2
  • 18
  • 33

3 Answers3

2

The first one is an integer division really. It divides an integer by another integer (the result of which is again an integer) and assigns the result to a double variable.

Only the second one yields a double as result.

integer / integer => result is integer, even though assigned to a double variable
integer or double / double => result is double
Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
2

first example will divide integers and assign them to your double "z", second divides doubles in the first place

riddy
  • 501
  • 1
  • 4
  • 17
1

Integer/Integer is an Integer even if you assign it to a holder variable of type double.To get a double precision value,you need to do your arithmetic operations using double variables

Kumar Abhinav
  • 6,565
  • 2
  • 24
  • 35