


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!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software