Are arithmetic operations on literals calculated at compile time or run time?

前端 未结 3 1864
挽巷
挽巷 2020-12-06 09:14

I have the following:

double timeInMinutes = (double) timeInMilliseconds / (1000 * 60);

Is the operation (1000 * 60) done at c

3条回答
  •  渐次进展
    2020-12-06 09:47

    Just create class Test

    public class Test {
        public static void main(String [] args) {
            long timeInMilliseconds = System.currentTimeMillis();
            double timeInMinutes = (double) timeInMilliseconds / (1000 * 60);
            System.out.println(timeInMinutes);
        }
    }
    

    and decompile it using command: javap -v Test

    You can see output of decompiled class:

      public static void main(java.lang.String[]);
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=4, locals=5, args_size=1
         0: invokestatic  #2                  // Method java/lang/System.currentTimeMillis:()J
         3: lstore_1
         4: lload_1
         5: l2d
         6: ldc2_w        #3                  // double 60000.0d
         9: ddiv
        10: dstore_3
        11: getstatic     #5                  // Field java/lang/System.out:Ljava/io/PrintStream;
        14: dload_3
        15: invokevirtual #6                  // Method java/io/PrintStream.println:(D)V
        18: return
      LineNumberTable:
        line 3: 0
        line 4: 4
        line 5: 11
        line 6: 18
    

    Take a look on the line 6: ldc2_w #3 // double 60000.0d

提交回复
热议问题