二进制运算符何时在Java中执行? [英] When does the binary operators execution happen in Java?

查看:57
本文介绍了二进制运算符何时在Java中执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解Java字节码.我从一个简单的例子开始:

I'm trying to understand java byte code. I started with simple example:

public class Test
{
    public static void main(String args[])
    {
        System.out.println(2 + 1);
    }
}

我编译了此类:

javac Test.java

然后我尝试在.class上使用javap,如下所示:

And then I tried to a javap on the .class like this:

javap -c Test

这给了我:

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

  public static void main(java.lang.String[]);
    Code:
       0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
       3: iconst_1      
       4: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
       7: return        
}

除了这一行之外,我还可以理解这一点:

I could able to make sense out of it, apart from this line:

public static void main(java.lang.String[]);
. . . 
3: iconst_1    
. . .

查看我的源代码和此字节码,看起来javac已经为该语句完成了加法运算:

looking at my source and this byte code, looks like javac already done the operation of addition for this statement:

2+1

并要求jvm返回该常量.

and asking jvm to return that constant.

如果我的理解是错误的,有人可以纠正我吗? javac是否在+-*等的编译上执行操作,然后才能在jvm上实际运行?如果可以,怎么办?

Can some one correct me if my understanding is wrong? Does javac performs the operation on compilation for +,-,* etc before it actually runs on the jvm? If so how?

推荐答案

2 + 1是一个编译时常量表达式.编译器本身在字节码中将其替换为3.

2 + 1 is a compile-time constant expression. The compiler itself replaces it by 3 in the byte-code.

请参见 Java语言规范,其中说:

某些表达式的值可以在编译时确定.这些是常量表达式.

Some expressions have a value that can be determined at compile time. These are constant expressions.

有关构成的信息,请参见另一章一个常数表达式

See this other chapter for what constitutes a constant expression

常量表达式是表示原始类型或String的值的表达式,该值不会突然完成,并且仅使用以下内容组成:

A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

  • 原始类型的文字和字符串[...]类型的文字
  • 加法运算符+和- [...]
  • Literals of primitive type and literals of type String [...]
  • The additive operators + and - [...]

这篇关于二进制运算符何时在Java中执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆