运行时和编译时的区别是什么?


当前回答

您可以通过阅读实际代码来理解代码编译结构。运行时结构并不清楚,除非您了解所使用的模式。

其他回答

简单地说,b/w编译时间和运行时间的差异。

编译时:开发人员以.java格式编写程序,并将其转换为类文件字节码,在编译期间发生的任何错误都可以定义为编译时错误。

运行时:生成的.class文件被应用程序用于它的附加功能&逻辑是错误的,并抛出一个错误,这是一个运行时错误

下面是《JAVA编程入门》的作者Daniel Liang关于编译的一段话:

用高级语言编写的程序称为源程序或源代码。因为计算机不能执行源程序,所以必须将源程序转换成机器代码才能执行。翻译可以使用另一种被称为解释器或编译器的编程工具来完成。”(Daniel Liang,“JAVA编程入门”,p8)。

...他仍在继续……

编译器将整个源代码翻译成一个机器代码文件,然后执行机器代码文件。

当我们输入高级/人类可读的代码时,这在一开始是无用的!它必须被翻译成一个序列的“电子事件”在你的小CPU!实现这一目标的第一步是编译。

简单地说:编译时错误发生在这个阶段,而运行时错误稍后发生。

请记住:仅仅因为一个程序没有错误地编译,并不意味着它将没有错误地运行。

运行时错误将发生在程序生命周期的准备、运行或等待部分,而编译时错误将发生在生命周期的“新”阶段之前。

编译时错误的例子:

语法错误——如果你的代码有歧义,你怎么能把它们编译成机器级指令??你的代码需要100%符合语言的语法规则,否则它不能被编译成工作的机器代码。

运行时错误的例子:

内存不足——例如,在给定特定程度的变量时,调用递归函数可能会导致堆栈溢出!编译器怎么能预料到这一点!?它不能。

这就是编译时错误和运行时错误的区别

public class RuntimeVsCompileTime {

    public static void main(String[] args) {
        
        //test(new D()); COMPILETIME ERROR
        /**
         * Compiler knows that B is not an instance of A
         */
        test(new B());
    }
    
    /**
     * compiler has no hint whether the actual type is A, B or C
     * C c = (C)a; will be checked during runtime
     * @param a
     */
    public static void test(A a) {
        C c = (C)a;//RUNTIME ERROR
    }

}

    class A{
    
}

    class B extends A{
    
}

    class C extends A{
    
}

    class D{
    
}

我们可以将其分为两大类静态绑定和动态绑定。它取决于何时与相应值绑定。如果引用是在编译时解析的,那么它是静态绑定;如果引用是在运行时解析的,那么它是动态绑定。静态绑定和动态绑定又称早期绑定和后期绑定。有时也称为静态多态和动态多态。

约瑟夫Kulandai‏。

Imagine that you are a boss and you have an assistant and a maid, and you give them a list of tasks to do, the assistant (compile time) will grab this list and make a checkup to see if the tasks are understandable and that you didn't write in any awkward language or syntax, so he understands that you want to assign someone for a Job so he assign him for you and he understand that you want some coffee, so his role is over and the maid (run time)starts to run those tasks so she goes to make you some coffee but in sudden she doesn’t find any coffee to make so she stops making it or she acts differently and make you some tea (when the program acts differently because he found an error).