1

What is default variable type in modulo after the "%".

variable1 = variable2 % variable3;

It means, is it possible java will change type of variable3 from long to int?

Martin Plávek
  • 335
  • 1
  • 3
  • 17

1 Answers1

1

Short answer - No it won't - It will tell you that precision loss occurred! Because Java is a strongly-typed language (I am willing to be corrected on this if required) you need to explicitly maintain your types for lvalus and rvalues. Use like the following:

(These are not code lines - simply explanation)

int res = int var1 % int var2;  // res as modulo of var1 and var2 (all int, no loss)


long res = int var1 % int var2; /* res as modulo of var1 and var2 (res size is bigger, 
                                * no loss) */

long res = long var1 % int var2; /* res as module of var1 and var2 (the divider is 
                                 * smaller size than dividend and quotient, so no
                                 * problem */

Anything else is loosing precision. Also, lvalue rvlaue arrangement when using modulo % sign matters.

long is simply extending the range to 64-bit from 32-bit. This is why when you mix them without balancing the lvalue and rvalue (with respect to "=" operator and % operator) - the compiler complians. For your case, unless you are doing specific bitwise operation, don't use long unnecessarily. I would suggest use shorts wherever possible (and int if you need something as big as 32-bit).

ha9u63a7
  • 6,233
  • 16
  • 73
  • 108
  • @MartinPlávek Glad to help :). It might help you if you also read about this - http://stackoverflow.com/questions/1079785/whats-an-example-of-duck-typing-in-java – ha9u63a7 Nov 08 '14 at 16:47