


Detailed examples explain the two concepts of java execution, compilation and operation
This article provides a detailed explanation of Java program compile time and runtime through examples. Friends who need it can refer to
Java compile time and runtime are very important concepts, but they have not been made clear this time. Special blog to write about concepts.
Basic concepts
Compile time
Compile time, as the name suggests, is what is being compiled At that time. So what is compilation? It means that the compiler helps you translate the source code into code that the machine can recognize. (Of course, this is only said in a general sense. In fact, it may only be translated into some intermediate state Language. For example, Java only has bytecode recognized by the JVM. In addition, there are linkers and assemblers. For ease of understanding, we can collectively call it a compiler)
Then compiling is a simple operation Some translation work, such as checking whether you have accidentally written any wrong keywords. Is there any process such as lexical analysis and grammatical analysis? It is like a teacher checking whether there are typos and wrong sentences in a student's composition. If you find anything The compiler will tell you the error. So sometimes some people say that allocating memory during compilation is definitely a mistake.
Runtime
The so-called running When the code is running, it is loaded into the memory. (Your code is dead when it is saved on the disk and not loaded into the memory. It becomes alive only when it is run into the memory). And the runtime type check is It is different from the compile-time type checking (or static type checking) mentioned earlier. It is not a simple scan of the code. Instead, it does some operations in the memory and makes some judgments. (In this way, many things that cannot be discovered during compilation Errors can be found when running. It is best to avoid this logical error when writing)
cite examples
int arr[] = {1,2,3}; int result = arr[4]; System.out.println(result); Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 4
The above code When you look at it, you know that it is wrong code, array is out of bounds. But no error is reported when using the compiler, and an ArrayIndexOutOfBoundsException appears after running. It can be seen that the compiler is actually quite stupid, not as smart as your brain. Ah, so you think that although the compiler is a bit stupid, it is not too bad if you find errors when running.
Interview questions
理解这几个概念可以更好地帮助你去了解一些基本的原理。下面是初学者晋级中级水平需要知道的一些问题。 Q.下面的代码片段中,行A和行B所标识的代码有什么区别呢? public class ConstantFolding { static final int number1 = 5; static final int number2 = 6; static int number3 = 5; static int number4= 6; public static void main(String[ ] args) { int product1 = number1 * number2; //line A int product2 = number3 * number4; //line B } }
A. In the code of line A, the value of product is calculated at compile time, while the value of product in line B is calculated at runtime. If you use a Java decompiler (for example, jd-gui) to decompile the ConstantFolding.class file, then you will get the answer from the following results.
public class ConstantFolding { static final int number1 = 5; static final int number2 = 6; static int number3 = 5; static int number4 = 6; public static void main(String[ ] args) { int product1 = 30; int product2 = number3 * number4; } }
Constant Folding is an optimization technique used by the Java compiler. Since the values of finalvariables will not change, they can be optimized. The Java decompiler and javap command are both powerful tools for viewing compiled code (e.g., bytecode).
Method overloading: This happens at compile time. Method overloading is also called compile-time polymorphism because the compiler can choose which method to use based on the type of the argument.
public class { public static void evaluate(String param1); // method #1 public static void evaluate(int param1); // method #2 }
If the compiler wants to compile the following statement:
1evaluate(“My Test Argument passed to param1”);
It will generate the bytecode for calling the #1 method based on the incoming parameter being a string constant.
Method override: This happens at runtime. Method overloading is called runtime polymorphism because at compile time the compiler does not know and cannot know which method to call. The JVM makes decisions while the code is running.
public class A { public int compute(int input) { //method #3 return 3 * input; } } public class B extends A { @Override public int compute(int input) { //method #4 return 4 * input; } }
The compute(..) method in subclass B overrides the compute(..) method of the parent class. If the compiler encounters the following code:
public int evaluate(A reference, int arg2) { int result = reference.compute(arg2); }
The compiler has no way of knowing whether the type of the parameter reference passed in is A or B. Therefore, the decision to call method #3 or method # can only be made at runtime based on the type of the object assigned to the input variable "reference" (for example, an instance of A or B) 4
Generics (also known as type checking): This occurs during compilation. The compiler is responsible for checking the correctness of the types in the program, and then translating or rewriting the code that uses generics into non-generic code that can be executed on the current JVM. This technique is called "type erasure".
In other words, the compiler will erase all type information within angle brackets to ensure compatibility with JRE version 1.4.0 or earlier.
1List myList = new ArrayList(10);
After compilation, it becomes:
1List myList = new ArrayList( 10);
Exception: You can use runtime exceptions or compile-time exceptions.
RuntimeException (RuntimeException) is also called an unchecked exception (unchecked exception), which means that this exception does not require the compiler to detect.
RuntimeException is the parent class of all exceptions that can be thrown at runtime. In addition to catching exceptions, a method may throw
when it is executed.A subclass of RuntimeException, then it does not need to use the throw statement to declare the thrown exception.
For example: NullPointerException, ArrayIndexOutOfBoundsException, etc.
Checked exceptions (checked exceptions) are checked by the compiler at compile time, through the throws statement or try {}cathch{} statement block to handle detection exceptions. The compiler will analyze which exceptions will be thrown when executing a method or constructor.
【Related Recommendations】
2. Alibaba Java Development Manual
3. JAVA Elementary Introduction Video Tutorial
The above is the detailed content of Detailed examples explain the two concepts of java execution, compilation and operation. For more information, please follow other related articles on the PHP Chinese website!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.