Bald bald bald bald 2022-02-13 07:08:02 阅读数:59
JVM:
Java virtual machine (JVM) Is to run Java The virtual machine of bytecode .JVM There are specific implementations for different systems (Windows,Linux,macOS), The purpose is to use the same bytecode , They all give the same result .
JVM There is not only one ! As long as meet JVM standard , Every company 、 Organizations or individuals can develop their own exclusive JVM.
In addition to what we usually use most HotSpot VM
Outside , also J9 VM、Zing VM、JRockit VM etc. JVM .
JDK:
JDK yes Java Development Kit abbreviation , It's fully functional Java SDK.
It has a JRE Everything you have , And the compiler (javac
) And tools ( Such as javadoc
and jdb
). It can create and compile programs
.
JRE:
JRE yes Java Runtime environment .
It is Run compiled Java A collection of all the content required by a program
, Include Java virtual machine
(JVM),Java Class library
,java command
And some other basic components . however , It can't be used to create new programs .
function Java Program ——JRE
Java Programming ——JDK
stay Java in ,JVM Understandable code is called Bytecode
( The extension is .class
The file of ), It does not target any specific processor , Virtual machine only .
Java Language by bytecode , Up to a point It solves the problem of low execution efficiency of traditional interpretative language
The problem of , At the same time, it retains the explanatory language portable
Characteristics .
Because bytecode is not specific to a particular machine , therefore ,Java The program can run on computers of different operating systems without recompilation .
What we need to pay special attention to is .class-> Machine code
This step . In this step JVM Class loader first loads the bytecode file
, And then through The interpreter interprets and executes... Line by line
, In this way The execution speed will be relatively slow
. and , Some methods and code blocks are often called ( It's called Hot code
), So the introduction of JIT(just-in-time compilation) compiler
, and JIT Belong to Compile at run time
. When JIT After the compiler completes the first compilation , It will the byte code corresponding to Save the machine code
, You can use it directly next time
. And we know that , The operation efficiency of machine code must be higher than Java Of the interpreter . It also explains why we often say Java It's a language where compilation and interpretation coexist
.
JDK 9 A new compilation mode is introduced
AOT(Ahead of Time Compilation)
, It compiles bytecode directly into machine code , This avoids JIT Preheat and other expenses .JDK Support hierarchical compilation and AOT Collaborative use of . however ,AOT The compiler's compilation quality is certainly not comparable to JIT Compiler .
We can divide high-level programming languages into two types according to the execution mode of programs :
A compiled : Compiler language (opens new window) Through the compiler (opens new window) take The source code is translated into machine code that can be executed by the platform at one time
. In general , Compiler language The execution speed is relatively fast
, Development efficiency is relatively low
. Common compiled languages are C、C++、Go、Rust
wait .
interpreted : Explanatory language (opens new window) Through the interpreter (opens new window) Explain the code sentence by sentence (interpret) Code for the machine before executing
. Explanatory language Development efficiency is relatively fast
, The execution speed is slow
. Common explanatory languages are Python、JavaScript、PHP
wait .
Java Language has both Compiler language
Characteristics of , Also has the Explanatory language
Characteristics of . because Java The procedure has to go through To compile the first , Explain later
Two steps , from Java The written program needs to go through Compilation steps , Generated bytecode
(.class file ), This bytecode must be made by Java Interpreter to explain execution
.
object-oriented
Language , All support encapsulation
、 Inherit
and polymorphic
No pointers are provided to directly access memory
, Program memory is more secure Single inheritance
Of ,C++ Support for multiple inheritance ; although Java Can't inherit more , however Interfaces can inherit more
. Automatic memory management garbage collection mechanism (GC)
, There's no need for programmers to manually release useless memory . Only method overloading is supported
( Operator overloading adds complexity , This is related to Java The original design idea didn't match ). Single quotation marks
Caused by the A character
, The string constant is Double quotes
Caused by the 0 One or more characters
integer
( ASCII value ), Can participate Expression operation
; The string constant represents a Address values
( The string is stored in memory )2 Bytes
; String constant takes several bytes from Java5 Start ,Java Support the definition of variable length parameters , The so-called variable length parameter is a parameter that allows an indefinite length to be passed in when calling a method . Accept 0 One or more parameters
.
public static void method2(String arg1, String... args) {
//......
}
Simply speaking , An identifier is a name . But there are some identifiers ,Java Language has given it a special meaning , It can only be used in certain places , This special identifier is a keyword .
A keyword is an identifier given a special meaning .
【Java Common keywords in 】
The symbol is preceded by / reduce , The symbol is followed by / reduce
continue
: Jump out of the current cycle , So let's go to the next loop .break
: Jump out of the loop , Continue to execute the statement below the loop .return
: Used to jump out of the way , End the operation of the method .return;
: Use it directly return End method execution , For methods that have no return value functions return value;
:return A specific value , Methods for functions with return values This needs to be combined with JVM Knowledge about , The main reasons are as follows :
Static methods belong to classes
, Memory is allocated when the class is loaded , It can be accessed directly through the class name . and Non static members belong to instance objects
, Only after the object is instantiated , You need to access... Through the instance object of the class . Class name . Method name
The way , You can also use object . Method name
The way , And the instance method only has the latter way . in other words , You can call static methods without creating objects
. however , It should be noted that... Is generally not recommended object . Method name To call static methods . This approach is very confusing , Static methods do not belong to an object of a class, but to this class . therefore , It is generally recommended to use Class name . Method name
To call static methods . Static methods when accessing members of this class , Only static members are allowed
( Static member variables and static methods ), Access to instance members is not allowed ( Instance member variables and instance methods ), and Instance methods do not have this limitation
. heavy load It's the same method that can be used according to different input data , Make a different deal . Occurs in the same class ( Or between a parent class and a child class ), Method name must be the same , Different parameter types 、 The number is different. 、 Different order , Method return values and access modifiers can be different
. Sum up : Overloading means that multiple methods with the same name in the same class perform different logical processing according to different parameters .
rewrite That is, when the subclass inherits the same method from the parent class , The input data is the same , But to make a response different from the parent class , You're going to override the parent method . Rewriting occurs at run time , Is a subclass to the parent class to allow access to the method of the implementation process to be rewritten
. Sum up : Rewriting is a modification of the parent method by a subclass , The external appearance cannot be changed , Internal logic can change .
Java Generic (generics) yes JDK 5 A new feature introduced in , Generics provide Compile time type safety detection mechanism
, This mechanism allows programmers to detect illegal types at compile time . The essence of generics is parameterized type
, in other words The data type being manipulated is specified as a parameter
.
Java The generics of are Pseudo generics
, This is because Java During operation , All generic information is erased
, This is what is commonly said Type Erasure
.
List<Integer> list = new ArrayList<>();
list.add(12);
list.add("a"); // If you add it directly here, you will report an error
Class<? extends List> clazz = list.getClass();
Method add = clazz.getDeclaredMethod("add", Object.class);
// But it is possible to add through reflection
// This means that all generic information will be erased during runtime
add.invoke(list, "kl");
System.out.println(list);
Generics are generally used in three ways : Generic classes
、 Generic interface
、 Generic methods
.
// here T It can be written as any logo , The common ones are T、E、K、V Parameters of the same form are often used to represent generics
// When instantiating generic classes , Must specify T Specific types of
public class Generic<T> {
private T key;
public Generic(T key) {
this.key = key;
}
public T getKey() {
return key;
}
}
Instantiate generic classes :
Generic<Integer> genericInteger = new Generic<Integer>(123456);
public interface Generator<T> {
public T method();
}
Implement generic interface , Do not specify type :
class GeneratorImpl<T> implements Generator<T>{
@Override
public T method() {
return null;
}
}
Implement generic interface , Specify the type :
class GeneratorImpl implements Generator<String>{
@Override
public String method() {
return "hello";
}
}
public static <E> void printArray(E[] inputArray) {
for (E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}
Use :
// Create different types of arrays : Integer, Double and Character
Integer[] intArray = {
1, 2, 3 };
String[] stringArray = {
"Hello", "World" };
printArray(intArray);
printArray(stringArray);
Common wildcards :T 、E、K、V、?
CommonResult<T>
Through parameters T
The data type of the result can be specified dynamically according to the specific return type == For basic types and reference types, the effect is different :
because Java Only
Value passed
, therefore , about == Come on , Regardless of the basic data type , Or variables that reference data types ,The essence of comparison is value
, It's justThe value stored in the reference type variable is the address of the object
.
equals() Functions cannot be used to determine variables of basic data types , It can only be used to judge whether two objects are equal .
Object class equals() Method :
public boolean equals(Object obj) {
return (this == obj);
}
hashCode() Introduce
hashCode() To get hash code
(int Integers ), Also known as Hash code
. The function of this hash code is Determines the index position of the object in the hash table
.Object Of hashCode() Methods are local methods , This method is usually used to Convert the memory address of the object to an integer and return
.
Hash table stores key value pairs (key-value), It is characterized by : According to “ key ” Quickly retrieve the corresponding “ value ”. So hash code is used !
Why would there be hashCode?
With
HashSet
For example :
When you add objects HashSet when ,HashSet MeetingFirst calculate the value of the object hashcode Value to determine where the object is added
, At the same timeWith other objects that have been added hashcode Comparison of values
, If there is no match hashcode,HashSet It assumes that the object does not recur . But ifFound the same hashcode Value object , This will call equals() Methods to check hashcode Are equal objects really the same
. IfThe two are the same ,HashSet It won't make the join operation successful
. IfDifferent words , It will be re hashed to other locations
. In this way, we will greatly reduce equals The number of times , Accordingly, the execution speed is greatly improved .
Why rewrite equals() Must rewrite hashCode() Method ?
hashCode() The default behavior for is Generate unique values for objects on the heap
. If you don't rewrite it hashCode(), Then class The two objects of cannot be equal in any way
.
If equals Method to judge that two objects are equal , The of these two objects hashCode The values should also be equal .
Why do two objects have the same hashcode value , And they don't have to be equal ? because hashCode() What is used The hash algorithm may just make multiple objects return the same hash value
. The worse the hash algorithm, the easier it is to collide , But it also has to do with the characteristics of data range distribution ( Collision means that different objects get the same hashCode ).“ Two different key value pairs , Hash values are equal ”, This is hash conflict
.
I just mentioned HashSet, If HashSet In contrast , alike hashcode There are multiple objects , It will use equals() To see if it's really the same
. in other words hashcode Just to reduce the search cost .
because HashSet Whether the objects are the same is judged according to their hashCode() Value comparison , and equals() The default comparison is also hashCode(). When we don't rewrite anything , The object created by default corresponds to hashCode Values are inconsistent ; But when we rewrite equeals() when , That means we want to change the way we judge whether objects are equal , So we need to rewrite hashCode(), To ensure that the object judgment method is the effect we want .
Java There is 8 Basic data types , Respectively :
byte
、short
、int
、long
、float
、double
char
boolean
. Packaging
Respectively :Byte
、Short
、Integer
、Long
、Float
、Double
、Character
、Boolean
. Basic data type
Store directly in Java virtual machine Local variable table in stack
in , and Packaging type
Belongs to the object type , We know Object instances exist in the heap
. Compared to object types , Basic data types take up very little space . Local variable table :
The local variable table mainly stores the basic data types known at compile time (boolean、byte、char、short、int、float、long、double)、 Object reference (reference type , It's different from the object itself , May be a reference pointer to the starting address of the object , It can also be a handle to a representative object or other location related to the object ).
Java Most of the basic types of wrapper classes implement constant pool technology .
Byte,Short,Integer,Long this 4 The wrapper class creates a value by default [-128,127] The corresponding type of cached data ,Character Created values in [0,127] Range cache data ,Boolean Go straight back to True or False.
give an example Integer Cache source code :
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
private static class IntegerCache {
static final int low = -128;
static final int high;
static {
// high value may be configured by property
int h = 127;
}
}
Comparison of values between all integer wrapper class objects , All use equals Methods to compare .
What is an automatic box ?
Integer i = 10; // Packing
int n = i; // Unpacking
From bytecode , We found that Packing
It's actually called The wrapper class valueOf()
Method , Unpacking
It's actually called xxxValue()
Method .
Be careful : If the box is disassembled frequently , It will also seriously affect the performance of the system . We should try to avoid unnecessary disassembly and assembly of the box .
copyright:author[Bald bald bald bald],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130707591598.html