表达式赋值 - 编译或运行时现象

发布于 2024-10-15 13:58:31 字数 127 浏览 6 评论 0原文

我有一个疑问,

任何表达式赋值操作都是 编译时或运行时现象?
例如 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

冷夜 2024-10-22 13:58:31

如果编译以下内容:

int x = 34 + 45;

那么您分配的表达式将在编译时计算,因为它仅涉及常量基本类型。在大多数其他情况下,包括您的示例,表达式将在运行时计算。

If you compile the following:

int x = 34 + 45;

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.

不必了 2024-10-22 13:58:31

我不知道你到底有什么疑问,但我认为在编译过程中,程序的文本表示会被翻译成机器可理解的形式(在Java情况下,它是Java字节码)。同样的情况也发生在诸如赋值之类的操作上。在运行时,执行此类操作。因此,为了准确回答您的问题,赋值操作既是编译现象,也是运行时现象(在这两种情况下都会采取某些操作 - 在编译情况下,它们由 Java 编译器完成,在运行时由 JVM 完成)。

例如,

class Foo { }
class Bar { }
Foo f = new Bar();

此代码将被编译器拒绝。它会对你大喊大叫,说你正在尝试分配不兼容的类型。

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,

class Foo { }
class Bar { }
Foo f = new Bar();

This code will be rejected by compiler. It will yell at you that you are trying to assign incompatible types.

魔法少女 2024-10-22 13:58:31

它的运行时

Foo f 将引用在运行时为 Bar 创建的 Object 运行时。

有编译时检查。 Bar 必须是 Foo 才能成功编译

Its runtime

Foo f would be referring to Object created runtime of Bar at runtime.

There are compile time check for it. Bar must be a Foo for this to compile successfully

南冥有猫 2024-10-22 13:58:31

两者皆有。

  1. 编译时 - 在编译时分析赋值的类型兼容性、注入代码以进行转换/装箱/拆箱等。甚至某些流分析也会影响赋值,例如变量及其赋值可以被优化掉编译

  2. 运行时 - 值的实际分配,即更改变量内存位置中的位,当然发生在运行时。

Its both.

  1. 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.

  2. 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文