表达式赋值 - 编译或运行时现象
我有一个疑问,
任何表达式赋值操作都是 编译时或运行时现象?
例如 Foo f=new Bar();
谢谢。
I had a doubt,
Any expression assignment operation is
a compile time or runtime phenomenon ?e.g Foo f=new Bar();
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果编译以下内容:
那么您分配的表达式将在编译时计算,因为它仅涉及常量基本类型。在大多数其他情况下,包括您的示例,表达式将在运行时计算。
If you compile the following:
then the expression that you are assigning will be evaluated at compile time because it involves only constant basic types. In most other cases, including your example, the expression will be evaluated at runtime.
我不知道你到底有什么疑问,但我认为在编译过程中,程序的文本表示会被翻译成机器可理解的形式(在Java情况下,它是Java字节码)。同样的情况也发生在诸如赋值之类的操作上。在运行时,执行此类操作。因此,为了准确回答您的问题,赋值操作既是编译现象,也是运行时现象(在这两种情况下都会采取某些操作 - 在编译情况下,它们由 Java 编译器完成,在运行时由 JVM 完成)。
例如,
此代码将被编译器拒绝。它会对你大喊大叫,说你正在尝试分配不兼容的类型。
I don't know what exactly is your doubt, but I think that during compilation textual representation of a program is translated into machine-understandable form (in Java case it'd be Java byte code). The same happens with operations like assignments. In runtime, such operations are executed. So to precisely answer your question, the assignment operation is both compile and runtime phenomenon (certain actions are taken in both cases - in a case of compilation they're done by Java compiler and in runtime the're done by JVM).
For instance,
This code will be rejected by compiler. It will yell at you that you are trying to assign incompatible types.
它的运行时
Foo f
将引用在运行时为Bar
创建的Object
运行时。有编译时检查。
Bar
必须是Foo
才能成功编译Its runtime
Foo f
would be referring toObject
created runtime ofBar
at runtime.There are compile time check for it.
Bar
must be aFoo
for this to compile successfully两者皆有。
编译时 - 在编译时分析赋值的类型兼容性、注入代码以进行转换/装箱/拆箱等。甚至某些流分析也会影响赋值,例如变量及其赋值可以被优化掉编译
运行时 - 值的实际分配,即更改变量内存位置中的位,当然发生在运行时。
Its both.
Compile time - an assignment is analyzed at compile time for type compatibility, for the injection of code to do conversion/boxing/unboxing, etc. Even some flow analysis can affect an assignment, e.g. variable and its assignment can be optimized away completely.
Run time - the actual assignment of a value, i.e. changing the bits in the variable's memory location, of course, happens at run-time.