2

the below code result "39 44" as output. I read somewhere that casting used modulo here. I know basic how to calculate modulo like 10%3 = 1 but I still didn't get how it calculated here.

class conversion {
    public static void main(String args[]) 
    {    
         double a = 295.04;
         int  b = 300;
         byte c = (byte) a;
         byte d = (byte) b;
         System.out.println(c + " "  + d);
    } 
}
Raj Bhatia
  • 889
  • 4
  • 12
  • 27
  • Duplicate ? http://stackoverflow.com/questions/26465633/type-casting-into-byte-in-java – Mateo Barahona Apr 15 '17 at 09:08
  • You haven't asked for anything using the remainder operator. Rather than relying on something you "read somewhere" but presumably can't provide the details of, I suggest you use the [JLS](http://docs.oracle.com/javase/specs/jls/se8/html/index.html) to explain the behaviour. – Jon Skeet Apr 15 '17 at 09:08
  • 2
    How that works is precisely defined in the Java Language Specification: https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.3. And there is no modulo involved. – JB Nizet Apr 15 '17 at 09:08
  • @JBNizet there isn't a modulus? This [answer](http://stackoverflow.com/questions/26465633/type-casting-into-byte-in-java) says there is. – dumbPotato21 Apr 15 '17 at 09:13
  • 3
    Well, it's wrong. – JB Nizet Apr 15 '17 at 09:15
  • 1
    @Shashwat: The answers says the result is the same *as if* `%` were used. That's not the same thing. "How does multiplication work" could say that the result of multiplying `x * y` is the same as starting a sum of 0 and adding `x` to it `y` times... but that's not how multiplication happens in the CPU. – Jon Skeet Apr 15 '17 at 09:16
  • 1
    Also, try it with 500, for example, and you'll see that the result of a modulo 128 and the result of the cast are different. – JB Nizet Apr 15 '17 at 09:43

1 Answers1

1

Range of byte is -128 to 127. so byte(128) will be -128. byte(129) will be -127. byte(256) will be 0. byte(257)=1 byte(295)=39. byte(295.04)=byte(295)=39.

Maulik Doshi
  • 315
  • 1
  • 11