Java arithmetic int vs. long

Also, is it safe to perform arithmetic with different primitives so long as you are assigning into a variable of the widest primitive type in your expression?

It depends what you mean by safe. It certainly won't avoid you needing to consider the possibility of overflow.


When mixing types the int is automatically widened to a long and then the two longs are added to produce the result. The Java Language Specification explains the process for operations containing different primative types.

Specifically, these are the types each primative will widen to without requiring a cast:

  • byte to short, int, long, float, or double
  • short to int, long, float, or double
  • char to int, long, float, or double
  • int to long, float, or double
  • long to float or double
  • float to double

See: Conversions and promotions

According to that, your int is promoted to long and then is evaluated.

Same happens with, for instance, int + double and the rest of the primitives. ie.

System.out( 1 + 2.0 );// prints 3.0 a double

As for the addition operator I'm pretty much it is the same, but I don't have any reference of it.

A quick view to the compiler's source reveals they are different.

Namely iadd for int addition and ladd for long addition:

See this sample code:

$cat Addition.java 
public class Addition {
    public static void main( String [] args ) {
        int  a  = Integer.parseInt(args[0]);
        long b = Long.parseLong(args[0]);
        // int addition 
        int  c  = a + a;
        // long addition 
        long d = a + b;
    }
}
$javac Addition.java 
$

When compiled the byte code generated is this:

$javap -c Addition 
Compiled from "Addition.java"
public class Addition extends java.lang.Object{
public Addition();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   aload_0
   1:   iconst_0
   2:   aaload
   3:   invokestatic    #2; //Method java/lang/Integer.parseInt:(Ljava/lang/String;)I
   6:   istore_1
   7:   aload_0
   8:   iconst_0
   9:   aaload
   10:  invokestatic    #3; //Method java/lang/Long.parseLong:(Ljava/lang/String;)J
   13:  lstore_2
   14:  iload_1
   15:  iload_1
   16:  iadd
   17:  istore  4
   19:  iload_1
   20:  i2l
   21:  lload_2
   22:  ladd
   23:  lstore  5
   25:  return

}

Look at line 16 it says: iadd ( for int addition ) while the line 22 says ladd ( for long addition )

Also, is it safe to perform arithmetic with different primitives so long as you are assigning into a variable of the widest primitive type in your expression?

Yes, and it's also "safe" to perform arithmetic with smaller sizes, in the sense, they don't break the program, you just lose information.

For instance, try adding Integer.MAX_VALUE to Integer.MAX_VALUE to see what happens, or int x = ( int ) ( Long.MAX_VALUE - 1 );

Tags:

Java

Math