-1

if I have two integer value int fiona = 13 int charming = 5

expression fiona/charming = 2.6

In java, does it becomes to a real number or integer?

BeyelerStudios
  • 4,243
  • 19
  • 38
Ivy
  • 23
  • 4

3 Answers3

1

In Java, like in many other typed languages, when you divide two integers you'll get an integer result:

int fiona = 13;
int charming = 5;
if(fiona / charming == 2)
    System.out.println("int");

will print int.

If you want a double, you need a division where the terms get promoted to double:

int fiona = 13;
int charming = 5;
if((double)fiona / charming == 2)
    System.out.println("int");
else
    System.out.println("value: " + ((double)fiona / charming));

will print value: 2.6. Here a cast to double of one term of the devision produces a double result: double result = (double)fiona / charming;.

Note that there are precedence rules for promotion in an expression e.g.:

double result = (double)1 / 2 + 1 / 3;

results in 0.5 as the (integer) division of 1 / 3 is evaluated before the addition (and any promotion) take place.

user207421
  • 305,947
  • 44
  • 307
  • 483
BeyelerStudios
  • 4,243
  • 19
  • 38
0

By default, it truncates the result. So in your case, fiona/charming would truncate to 2.

But hope is not lost! There are a couple of ways you can do this. You can cast either the numerator or denominator to a double and then the result will be a double. So either of these will work:

double fionasPerCharming = fiona/(double)charming;
double fionasPerCharming2 = (double)fiona/charming;

Or you can do both, if for some reason you wanted to, though there's not much of a point.

double fionasPerCharming3 = (double)fiona/(double)charming;

But one thing you can't do is cast after dividing:

double fionasPerCharmingFail = (double)(fiona/charming);

This doesn't work because it's already divided fiona by charming and gotten an integer result before you try to cast it. Sure your datatype will be double but the value will still be 2. If you printed it showing one decimal place, it will say 2.0.

Devsman
  • 434
  • 4
  • 17
0

The result of any operation between two integers is another integer. If you want a floating-point result, you need to cast one of the operands to float or double as required.

user207421
  • 305,947
  • 44
  • 307
  • 483