The summary of Java interview summarizes the basic knowledge of Java, collection container, concurrent programming, JVM, common open source frameworks Spring, MyBatis, database, middleware, etc., including most of the knowledge that a java engineer needs or may use in the interview. Welcome to read. I have limited experience. It is inevitable that there are mistakes or omissions in my blog. I hope you can give me some advice. I would like to express my gratitude here. The article is constantly updated
Serial number | content | Link address |
---|---|---|
1 | Interview questions on Java Basics (2020 latest edition) | https://thinkwon.blog.csdn.net/article/details/104390612 |
2 | Java collection container interview questions (2020 latest version) | https://thinkwon.blog.csdn.net/article/details/104588551 |
3 | Java exception interview questions (2020 latest edition) | https://thinkwon.blog.csdn.net/article/details/104390689 |
4 | Concurrent programming interview questions (2020 latest edition) | https://thinkwon.blog.csdn.net/article/details/104863992 |
5 | JVM interview questions (2020 latest edition) | https://thinkwon.blog.csdn.net/article/details/104390752 |
6 | Spring interview questions (2020 latest edition) | https://thinkwon.blog.csdn.net/article/details/104397516 |
7 | Spring MVC interview questions (2020 latest edition) | https://thinkwon.blog.csdn.net/article/details/104397427 |
8 | Spring Boot interview questions (2020 latest edition) | https://thinkwon.blog.csdn.net/article/details/104397299 |
9 | Spring Cloud interview questions (2020 latest edition) | https://thinkwon.blog.csdn.net/article/details/104397367 |
10 | MyBatis interview questions (2020 latest edition) | https://thinkwon.blog.csdn.net/article/details/101292950 |
11 | Redis interview questions (2020 latest edition) | https://thinkwon.blog.csdn.net/article/details/103522351 |
12 | MySQL database interview questions (2020 latest version) | https://thinkwon.blog.csdn.net/article/details/104778621 |
13 | Message oriented middleware MQ and RabbitMQ interview questions (2020 latest version) | https://thinkwon.blog.csdn.net/article/details/104588612 |
14 | Dubbo interview questions (2020 latest edition) | https://thinkwon.blog.csdn.net/article/details/104390006 |
15 | Linux interview questions (2020 latest version) | https://thinkwon.blog.csdn.net/article/details/104588679 |
16 | Tomcat interview questions (2020 latest edition) | https://thinkwon.blog.csdn.net/article/details/104397665 |
17 | ZooKeeper interview questions (2020 latest edition) | https://thinkwon.blog.csdn.net/article/details/104397719 |
18 | Netty interview questions (2020 latest edition) | https://thinkwon.blog.csdn.net/article/details/104391081 |
19 | Architecture Design & distributed data structure and algorithm interview questions (2020 latest edition) | https://thinkwon.blog.csdn.net/article/details/105870730 |
Java overview
What is programming
Programming is a process in which a computer uses a programming language to write program code to solve a problem and finally get the result.
In order to make the computer understand people's intention, human beings must tell the computer the ideas, methods and means of the problems to be solved in the form that the computer can understand, so that the computer can work step by step according to people's instructions and complete a specific task. This process of communication between people and computers is programming.
What is Java
Java is an object-oriented programming language, which not only absorbs various advantages of C + + language, but also discards the concepts of multi inheritance and pointer which are difficult to understand in C + +. Therefore, Java language has two characteristics: powerful function and easy to use. As the representative of static object-oriented programming language, Java language perfectly realizes the object-oriented theory and allows programmers to program complex programs in an elegant way of thinking.
jdk1. Three versions after 5
- Java SE (J2SE, Java 2 Platform Standard Edition, Standard Edition)
Java SE was formerly known as J2SE. It allows the development and deployment of Java applications for use on desktops, servers, embedded environments, and real-time environments. Java SE contains classes that support Java Web service development and provides the basis for Java EE and Java ME. - Java EE (J2EE, Java 2 platform, enterprise edition, Enterprise Edition)
Java EE was formerly known as J2EE. Enterprise Edition helps develop and deploy portable, robust, scalable, and secure server-side java applications. Java EE is built on the basis of Java SE. It provides Web services, component model, management and communication API s, which can be used to implement enterprise service-oriented architecture (SOA) and web2 0 application. In February 2018, Eclipse announced that it officially renamed Java EE as Jakarta EE - Java ME (J2ME, Java 2 Platform Micro Edition, Micro Edition)
Java me was formerly known as J2ME. Java me provides a robust and flexible environment for applications running on mobile and embedded devices, such as mobile phones, PDA s, TV set-top boxes and printers. Java ME includes a flexible user interface, a robust security model, many built-in network protocols, and rich support for networked and offline applications that can be downloaded dynamically. Applications based on the Java ME specification need only be written once, can be used for many devices, and can take advantage of the native functions of each device.
Relationship between JVM, JRE and JDK
JVM
Java Virtual Machine is a Java Virtual Machine. Java programs need to run on the virtual machine. Different platforms have their own virtual machines. Therefore, Java language can realize cross platform.
JRE
The Java Runtime Environment includes the Java virtual machine and the core class libraries required by Java programs. The core class library is mainly Java Lang package: contains the necessary system classes for running Java programs, such as basic data types, basic mathematical functions, string processing, threads, exception handling classes, etc. the system loads this package by default
If you want to run a developed Java program, you only need to install JRE in your computer.
JDK
The Java Development Kit is provided to Java developers, including java development tools and JRE. Therefore, with JDK installed, there is no need to install JRE separately. The development tools include compiling tool (javac.exe), packaging tool (jar.exe), etc
JVM & JRE & JDK diagram
What is cross platform? What is the principle
The so-called cross platform refers to the program written in java language, which can run on multiple system platforms after one compilation.
Implementation principle: Java programs run on the system platform through Java virtual machine. As long as the system can install the corresponding Java virtual machine, the system can run Java programs.
What are the characteristics of Java language
Easy to learn (the syntax of Java language is very close to C language and C + + language)
Object oriented (encapsulation, inheritance, polymorphism)
Platform independence (Java virtual machine implements platform independence)
It supports network programming and is very convenient (the birth of Java language itself is designed to simplify network programming)
Support multithreading (multithreading mechanism enables applications to execute multiple tasks in parallel at the same time)
Robustness (strong typing mechanism of Java language, exception handling, automatic garbage collection, etc.)
Security
What is bytecode? What are the biggest benefits of bytecode
Bytecode: a file generated after Java source code is compiled by the virtual machine compiler (i.e. a file extended to. class). It does not face any specific processor, but only the virtual machine.
Benefits of bytecode:
By means of bytecode, Java language solves the problem of low execution efficiency of traditional interpretative language to a certain extent, and retains the portability of interpretative language. Therefore, the Java program runs more efficiently. Moreover, because the bytecode is not specific to a specific machine, the Java program can run on a variety of different computers without recompiling.
Let's first look at the compiler and interpreter in java:
The concept of virtual machine is introduced into Java, that is, a layer of abstract virtual machine is added between the machine and the compiler. This virtual machine provides a common interface to the compiler on any platform. The compiler only needs to face the virtual machine, generate the code that the virtual machine can understand, and then the interpreter will convert the virtual machine code into the machine code of a specific system for execution. In Java, this code for virtual machines to understand is called bytecode (i.e. a file extended to. class). It does not face any specific processor, but only virtual machines. The interpreter of each platform is different, but the virtual machine implemented is the same. The Java source program is compiled into bytecode by the compiler, and the bytecode is interpreted and executed by the virtual machine. The virtual machine sends each bytecode to be executed to the interpreter, which translates it into the machine code on a specific machine, and then runs on a specific machine. This is the explanation of the coexistence of compilation and interpretation of the characteristics of Java mentioned above.
Java source code---->compiler---->jvm Executable Java Bytecode(Virtual instruction)---->jvm---->jvm Middle interpreter----->Machine executable binary machine code---->The program runs.
- 1
What is the main class of a Java program? How are the main classes of applications and applets different?
A program can have multiple classes, but only one class is the main class. In Java applications, this main class refers to the class containing the main() method. In Java applets, this main class is a subclass that inherits from the system class Applet or Applet. The main class of an application does not necessarily require a public class, but the main class of an Applet must be a public class. The main class is the entry point for Java program execution.
What are the differences between Java applications and applets?
Simply put, the application starts from the main thread (that is, the main() method). The applet has no main method. It is mainly embedded on the browser page (call init() thread or run() to start). Embedding the browser is similar to flash games.
The difference between Java and C + +
I know many people haven't studied C + +, but the interviewer just likes to compare us with Java and C + +! no way out!!! Even if you haven't learned C + +, write it down!
- They are object-oriented languages and support encapsulation, inheritance and polymorphism
- Java does not provide pointers to directly access memory, so program memory is more secure
- Java classes are single inheritance, and C + + supports multiple inheritance; Although Java classes cannot inherit more, interfaces can inherit more.
- Java has an automatic memory management mechanism, which does not require programmers to manually release useless memory
Comparison between Oracle JDK and OpenJDK
-
Oracle JDK version will be released every three years, while OpenJDK version will be released every three months;
-
OpenJDK is a reference model and is completely open source, while Oracle JDK is an implementation of OpenJDK, not completely open source;
-
Oracle JDK is more stable than OpenJDK. The code of OpenJDK and Oracle JDK are almost the same, but Oracle JDK has more classes and some bug fixes. Therefore, if you want to develop enterprise / business software, I suggest you choose Oracle JDK because it has been thoroughly tested and stable. In some cases, some people mentioned that many applications may crash when using OpenJDK, but the problem can be solved by switching to Oracle JDK;
-
In terms of responsiveness and JVM performance, Oracle JDK provides better performance than OpenJDK;
-
Oracle JDK will not provide long-term support for the upcoming version. Users must update to the latest version to obtain the latest version every time;
-
Oracle JDK is licensed under the binary license agreement, while OpenJDK is licensed under the GPL v2 license.
Basic grammar
data type
What data types does Java have
Definition: Java language is a strongly typed language. It defines specific data types for each kind of data, and allocates different sizes of memory space in memory.
classification
- Basic data type
- Numerical type
- Integer type (byte,short,int,long)
- Floating point type (float,double)
- Character type (char)
- Boolean
- Numerical type
- Reference data type
- Class
- Interface
- Array ([])
Java basic data type diagram
Whether switch can act on byte, long and String
Before Java 5, in switch(expr), expr can only be byte, short, char and int. Since Java 5, enumeration type has been introduced into Java. Expr can also be enum type. Since Java 7, expr can also be String, but long is not allowed in all current versions.
Calculate 2 times 8 in the most efficient way
2 < < 3 (shifting 3 bits left is equivalent to multiplying 2 to the power of 3, and shifting 3 bits right is equivalent to dividing 2 to the power of 3).
Math. What is round (11.5) equal to? Math. What is round (- 11.5) equal to
Math. The return value of round (11.5) is 12, math The return value of round (- 11.5) is - 11. The principle of rounding is to add 0.5 to the parameter and then round it down.
float f=3.4; Is it correct
incorrect. 3.4 is a double precision number. Assigning a double to a float is a down casting (also known as narrowing), which will cause precision loss. Therefore, it is necessary to force the type conversion float f =(float)3.4; Or write as float f =3.4F;.
short s1 = 1; s1 = s1 + 1; Is there anything wrong? short s1 = 1; s1 += 1; Is there anything wrong
For short, S1 = 1; s1 = s1+1; Since 1 is of type int, the result of s1+1 operation is also of type int. the type needs to be cast before it can be assigned to type short.
While short S1 = 1; s1+= 1; It can be compiled correctly because s1+= 1; Equivalent to s1 = (short(s1 + 1); There is an implicit cast.
code
What coding scheme does the Java language adopt? What are the characteristics?
The Java language adopts the Unicode coding standard, Unicode (Standard Code), which sets a unique value for each character, so it can be used safely in any language, platform and program.
notes
What Java annotations
Definition: text used to explain the program
classification
- Single-Line Comments
Format: / / annotation text - multiline comment
Format: / * note text*/ - Documentation Comments
Format: / * * note text*/
effect
In the program, especially in the complex program, adding notes appropriately can increase the readability of the program and is conducive to program modification, debugging and communication. The content of comments will be ignored during program compilation and will not produce object code. The part of comments will not have any impact on the execution results of the program.
Note: multiline and document comments cannot be nested.
Access modifier
Access modifiers public,private,protected, and the difference when not writing (default)
Definition: in Java, access modifiers can be used to protect access to classes, variables, methods, and constructor methods. Java supports four different access rights.
classification
private: visible in the same class. Using objects: variables, methods. Note: you cannot decorate classes (external classes)
Default (i.e. default, write nothing and use no keywords): it is visible in the same package without any modifiers. Use objects: classes, interfaces, variables, methods.
protected: visible to classes and all subclasses in the same package. Using objects: variables, methods. Note: you cannot decorate classes (external classes).
public: visible to all classes. Using objects: classes, interfaces, variables, methods
Access modifier graph
operator
&And & &
&Operator has two uses: (1) bitwise AND; (2) Logic and.
&&The operator is a short circuit and operation. The difference between logic and short circuit and is very great, although both require the Boolean values at the left and right ends of the operator to be true, and the value of the whole expression is true&& It is called short circuit operation because if && the value of the expression on the left is false, the expression on the right will be directly short circuited and will not be operated.
Note: the same is true for the difference between logical or operator (|) and short circuit or operator (|).
keyword
Does Java have goto
goto is a reserved word in Java, which is not used in the current version of Java.
What's the use of final?
Used to modify classes, properties and methods;
- A class modified by final cannot be inherited
- Methods modified by final cannot be overridden
- The variable modified by final cannot be changed. The variable modified by final cannot be changed is the reference of the variable, not the content pointed to by the reference. The content pointed to by the reference can be changed
final finally finalize differences
- final can modify classes, variables and methods. A modified class means that the class cannot be inherited, and a modified method means that the method cannot be overridden and modify the variable table
Indicates that the variable is a constant and cannot be re assigned. - Finally is generally used in the try catch code block. When handling exceptions, we usually need to execute the code method finally code block
Indicates that the code block will be executed regardless of whether an exception occurs. It is generally used to store some code for closing resources. - finalize is a method belonging to the Object class, and the Object class is the parent class of all classes. This method is generally called by the garbage collector
When we call system When using the GC () method, the garbage collector calls finalize() to collect garbage and whether an object is recyclable
Final judgment.
Usage of this keyword
this is an object of itself, representing the object itself. It can be understood as a pointer to the object itself.
The usage of this can be roughly divided into three types in java:
1. Ordinary direct reference, this is equivalent to pointing to the current object itself.
2. The formal parameter has the same name as the member name, which is distinguished by this:
public Person(String name, int age) { this.name = name; this.age = age; }
- 1
- 2
- 3
- 4
3. Reference the constructor of this class
class Person{ private String name; private int age;<span class="token keyword">public</span> <span class="token function">Person</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> <span class="token punctuation">}</span> <span class="token keyword">public</span> <span class="token function">Person</span><span class="token punctuation">(</span>String name<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> <span class="token keyword">this</span><span class="token punctuation">.</span>name <span class="token operator">=</span> name<span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token keyword">public</span> <span class="token function">Person</span><span class="token punctuation">(</span>String name<span class="token punctuation">,</span> <span class="token keyword">int</span> age<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> <span class="token keyword">this</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>age <span class="token operator">=</span> age<span class="token punctuation">;</span> <span class="token punctuation">}</span>
}
Usage of super keyword
Super can be understood as a pointer to its own super (parent) class object, and this super class refers to the nearest parent class.
super can also be used in three ways:
1. Common direct reference
Similar to this, super is equivalent to a reference to the parent class of the current object, so you can use super XXX to reference members of the parent class.
2. When the member variable or method in the subclass has the same name as the member variable or method in the parent class, use super to distinguish
class Person{ protected String name;<span class="token keyword">public</span> <span class="token function">Person</span><span class="token punctuation">(</span>String name<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> <span class="token keyword">this</span><span class="token punctuation">.</span>name <span class="token operator">=</span> name<span class="token punctuation">;</span> <span class="token punctuation">}</span>
}
class Student extends Person{
private String name;
<span class="token keyword">public</span> <span class="token function">Student</span><span class="token punctuation">(</span>String name<span class="token punctuation">,</span> String name1<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> <span class="token keyword">super</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token keyword">this</span><span class="token punctuation">.</span>name <span class="token operator">=</span> name1<span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">getInfo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//Child</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token keyword">super</span><span class="token punctuation">.</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//Father</span> <span class="token punctuation">}</span>
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student("Father","Child");
s1.getInfo();
<span class="token punctuation">}</span>
}
3. Reference parent class constructor
3. Reference parent class constructor
- super (parameter): call a constructor in the parent class (should be the first statement in the constructor).
- This (parameter): call another form of constructor in this class (should be the first statement in the constructor).
The difference between this and super
- Super: it refers to the member in the direct parent class of the current object (used to access the member data or function in the hidden parent class in the direct parent class. When the base class and the derived class have the same member definition, such as: super. Variable name super. Member function data name (argument)
- This: it represents the current object name (where ambiguity is easy to occur in the program, this should be used to indicate the current object; if the formal parameter of the function has the same name as the member data in the class, this should be used to indicate the member variable name)
- super() is similar to this(). The difference is that super() calls the construction method of the parent class in the subclass. this() calls other construction methods of this class in this class.
- Both super() and this() need to be placed in the first line of the constructor.
- Although you can call one constructor with this, you cannot call two.
- This and super cannot appear in one constructor at the same time, because this must call other constructors, and other constructors must also have super statements. Therefore, if there are the same statements in the same constructor, the meaning of the statements will be lost, and the compiler will not pass.
- Both this() and super() refer to objects, so they can't be used in static environment. Including: static variable, static method and static statement block.
- In essence, this is a pointer to this object, while super is a Java keyword.
The main meaning of static
The main meaning of static is to create domain variables or methods independent of specific objects. So that you can use properties and call methods even if you don't create an object!
Static keyword also plays a key role in forming static code blocks to optimize program performance. Static blocks can be placed anywhere in the class, and there can be multiple static blocks in the class. When the class is first loaded, each static block is executed in the order of static blocks, and only once.
The reason why static block can be used to optimize program performance is that it is only executed once when the class is loaded. Therefore, many times, some initialization operations that only need to be performed once are placed in the static code block.
The uniqueness of static
1. Variables or methods modified by static are any object independent of the class, that is, these variables and methods do not belong to any instance object, but are shared by the instance object of the class.
How to understand the sentence "shared by class instance objects"? That is, the static member of a class belongs to everyone [everyone refers to multiple object instances of this class. We all know that a class can create multiple instances!], All class objects are shared, unlike member variables that are self-contained [self-contained refers to a single instance object of this class]... I think what I have said is very popular, do you understand?
2. When the class is loaded for the first time, it will load the static modified part, and it will only be loaded and initialized when the class is used for the first time. Note that it needs to be initialized for the first time, and it can be assigned again as needed.
3. The static variable value allocates space when the class is loaded, and will not be reallocated when creating class objects in the future. If you assign values, you can assign values arbitrarily!
4. Variables or methods modified by static take precedence over objects, that is, after a class is loaded, it can be accessed even if no object is created.
static application scenario
Because static is shared by the instance objects of the class, if a member variable is shared by all objects, the member variable should be defined as a static variable.
Therefore, common static application scenarios include:
1. Modify member variable 2. Modify member method 3. Static code block 4. Modify class [only modify internal class, that is, static internal class] 5. Static package Guide
static considerations
1. Static can only access static. 2. Non static can access both non static and static.
Process control statement
Differences and functions of break, continue and return
break jumps out of the loop of the previous level and no longer executes the loop (ends the current loop body)
Continue jump out of this cycle and continue to execute the next cycle (end the executing cycle and enter the next cycle condition)
Return the program returns. The following code will no longer be executed (end the current method and return directly)
In Java, how to jump out of the current multi nested loop
In Java, if you want to jump out of multiple loops, you can define a label in front of the outer loop statement, and then use the labeled break statement in the code of the inner loop body to jump out of the outer loop. For example:
public static void main(String[] args) { ok: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { System.out.println("i=" + i + ",j=" + j); if (j == 5) { break ok; }<span class="token punctuation">}</span> <span class="token punctuation">}</span>
}
object-oriented
Object oriented overview
The difference between object oriented and process oriented
Process oriented:
Advantages: the performance is higher than that of object-oriented, because class calls need to be instantiated, which costs a lot and consumes resources; For example, single chip microcomputer, embedded development and Linux/Unix generally adopt process oriented development, and performance is the most important factor.
Disadvantages: no object-oriented, easy to maintain, easy to reuse and easy to expand
object-oriented:
Advantages: easy to maintain, reuse and expand. Due to the characteristics of object-oriented encapsulation, inheritance and polymorphism, a low coupling system can be designed to make the system more flexible and easier to maintain
Disadvantages: lower performance than process oriented
Process oriented is concrete and process oriented. To solve a problem, you need to analyze it step by step and realize it step by step.
Object oriented is modeled. You only need to abstract a class, which is a closed box where you have data and methods to solve problems. What functions you need can be used directly. There is no need to implement them step by step. As for how to implement this function, it doesn't matter what we do? We can use it.
In fact, the bottom layer of object-oriented is process-oriented. We abstract the process-oriented into classes and then encapsulate them. What is convenient for us to use is object-oriented.
Three characteristics of object oriented
What are the characteristics of object-oriented
Object oriented features mainly include the following aspects:
Abstraction: abstraction is the process of summarizing the common characteristics of a class of objects to construct a class, including data abstraction and behavior abstraction. Abstraction only focuses on the attributes and behaviors of objects, not the details of these behaviors.
encapsulation
Encapsulation privatizes the properties of an object and provides methods for properties that can be accessed by the outside world. If the properties do not want to be accessed by the outside world, we do not need to provide methods for external access. However, if a class does not provide methods for external access, the class is meaningless.
inherit
Inheritance is a technology that uses the definition of an existing class as a basis to establish a new class. The definition of a new class can add new data or new functions, or use the functions of the parent class, but cannot selectively inherit the parent class. By using inheritance, we can easily reuse previous code.
Remember the following three points about inheritance:
-
Subclasses have non private properties and methods of the parent class.
-
Subclasses can have their own properties and methods, that is, subclasses can extend the parent class.
-
Subclasses can implement the methods of their parent classes in their own way. (introduced later).
polymorphic
The so-called polymorphism refers to the specific type pointed to by the reference variable defined in the program and the method call issued through the reference variable. It is not determined during programming, but only during the running of the program, that is, the instance object of which class a reference variable will point to, and the method call issued by the reference variable is the method implemented in which class, It can only be determined during the running of the program.
There are two forms of polymorphism in Java: inheritance (multiple subclasses rewrite the same method) and interface (implement the interface and overwrite the same method in the interface).
Among them, Java object-oriented programming has three characteristics: encapsulation, inheritance and polymorphism
Encapsulation: hide the attributes and implementation details of the object, only provide public access, isolate changes, facilitate use, and improve reusability and security.
Inheritance: inheritance is the technology of using the existing class definition as the basis to create a new class. The new class definition can add new data or new functions, or use the functions of the parent class, but cannot selectively inherit the parent class. Code reusability can be improved by using inheritance. Inheritance is the premise of polymorphism.
Remember the following three points about inheritance:
-
Subclasses have non private properties and methods of the parent class.
-
Subclasses can have their own properties and methods, that is, subclasses can extend the parent class.
-
Subclasses can implement the methods of their parent classes in their own way.
Polymorphism: a reference variable defined by a parent class or interface can point to an instance object of a child class or a concrete implementation class. It improves the expansibility of the program.
There are two forms of polymorphism in Java: inheritance (multiple subclasses rewrite the same method) and interface (implement the interface and overwrite the same method in the interface).
Method overload implements compile time polymorphism (also known as pre binding), while method override implements runtime polymorphism (also known as post binding).
Which class instance object a reference variable will point to, and which class implements the method call issued by the reference variable, must be determined during program operation. Runtime polymorphism is the quintessence of object-oriented. Two things need to be done to realize polymorphism:
- Method override (the subclass inherits the parent class and overrides the existing or abstract methods in the parent class);
- Object modeling (using the parent type to refer to the subtype object, so that the same reference calls the same method, it will show different behavior according to the different subclass objects).
What is polymorphism? How does the Java language implement polymorphism?
The so-called polymorphism refers to the specific type pointed to by the reference variable defined in the program and the method call issued through the reference variable. It is not determined during programming, but only during the running of the program, that is, a reference variable will point to the instance object of which class, and the method call issued by the reference variable is the method implemented in which class, It can only be determined during the running of the program. Because the specific class is determined only when the program is running, the reference variable can be bound to various class implementations without modifying the source program code, resulting in the change of the specific method called by the reference, that is, the specific code bound when the program is running can be changed without modifying the program code, so that the program can select multiple running states, This is polymorphism.
Polymorphism can be divided into compile time polymorphism and run-time polymorphism. Polymorphism during editing is static, which mainly refers to method overloading. It distinguishes different functions according to different parameter lists. After editing, it will become two different functions, so it can't be polymorphic at run time. The runtime polymorphism is dynamic, which is realized by dynamic binding, that is, what we call polymorphism.
Implementation of polymorphism
There are three necessary conditions for Java polymorphism: inheritance, rewriting and upward transformation.
Inheritance: there must be subclasses and parent classes with inheritance relationship in polymorphism.
Override: a subclass redefines some methods in the parent class. When these methods are called, the subclass's methods will be called.
Upward Transformation: in polymorphism, you need to assign the reference of the subclass to the parent object. Only in this way can the reference have the skills to call the methods of the parent class and the subclass.
Only when the above three conditions are met can we use unified logic implementation code to deal with different objects in the same inheritance structure, so as to execute different behaviors.
For Java, its polymorphic implementation mechanism follows a principle: when a superclass object references a subclass object with a reference variable, the type of the referenced object rather than the type of the reference variable determines whose member method to call, but the called method must be defined in the superclass, that is, the method covered by the subclass.
What are the five basic principles of object orientation (optional)
- Single responsibility principle (SRP)
The function of class should be single, not all inclusive, just like a grocery store. - Open close principle (OCP)
A module is open for expansion and closed for modification. If you want to add functions, you are warmly welcome. If you want to modify, hum, 10000 are unwilling. - The Liskov Substitution Principle (LSP)
A subclass can replace the parent class wherever the parent class can appear. For example, you can work at your grandmother's house on behalf of your father. Ha ha~~ - The dependency inversion principle (DIP)
High level modules should not rely on low-level modules, they should all rely on abstraction. Abstraction should not depend on concrete implementation, but concrete implementation should depend on abstraction. If you go abroad, you should say you are Chinese, not which village you are from. For example, the Chinese are abstract. There are specific xx provinces, xx cities and xx counties. The abstraction you have to rely on is the Chinese, not that you are from xx village. - The interface aggregation principle (ISP)
It is better to design with multiple interfaces related to specific customer classes than with a common interface. For example, a mobile phone has functions such as making phone calls, watching videos and playing games. It is much better to split these functions into different interfaces than in one interface.
Classes and interfaces
Comparison of abstract classes and interfaces
Abstract classes are used to capture the general characteristics of subclasses. An interface is a collection of abstract methods.
From the design level, an abstract class is an abstraction of a class, a template design, and an interface is an abstraction of behavior and a specification of behavior.
Same point
- Neither interfaces nor abstract classes can be instantiated
- Are at the top of inheritance and are used by other implementations or inheritance
- All contain abstract methods, and their subclasses must override these abstract methods
difference
parameter | abstract class | Interface |
---|---|---|
statement | Abstract classes are declared using the abstract keyword | Interfaces are declared using the interface keyword |
realization | Subclasses use the extends keyword to inherit abstract classes. If the subclass is not an abstract class, it needs to provide the implementation of all declared methods in the abstract class | Subclasses use the implements keyword to implement interfaces. It needs to provide the implementation of all declared methods in the interface |
constructor | Abstract classes can have constructors | An interface cannot have a constructor |
Access modifier | Methods in abstract classes can be arbitrary access modifiers | The default modifier of interface method is public. It is not allowed to be defined as private or protected |
Multiple inheritance | A class can inherit at most one abstract class | A class can implement multiple interfaces |
Field declaration | The field declaration of an abstract class can be arbitrary | The fields of the interface are static and final by default |
Note: default methods and static methods are introduced into interfaces in Java 8 to reduce the differences between abstract classes and interfaces.
Now we can provide the default implementation method for the interface without forcing subclasses to implement it.
Interfaces and abstract classes have their own advantages and disadvantages. In the selection of interfaces and abstract classes, such a principle must be observed:
- Behavior models should always be defined through interfaces rather than abstract classes, so interfaces are usually preferred and abstract classes are used as little as possible.
- When selecting an abstract class, you usually need to define the behavior of subclasses and provide common functions for subclasses.
What are the differences between ordinary classes and abstract classes?
- Ordinary classes cannot contain abstract methods, and abstract classes can contain abstract methods.
- Abstract classes cannot be instantiated directly. Ordinary classes can be instantiated directly.
Can abstract classes be decorated with final?
No, defining an abstract class is to let other classes inherit. If it is defined as final, the class cannot be inherited, which will conflict with each other. Therefore, final cannot modify an abstract class
What keywords are used to create an object? How are object instances different from object references?
New keyword, new creates an object instance (the object instance is in heap memory), and the object reference points to the object instance (the object reference is stored in stack memory). An object reference can point to 0 or 1 objects (a rope can be tied without a balloon or a balloon); An object can have n references to it (you can tie a balloon with n ropes)
Variables and methods
What are the differences between member variables and local variables
Variable: the amount whose value can change within a certain range during program execution. Essentially, a variable is a small area of memory
Member variables: variables defined outside the method and inside the class
Local variables: variables in the methods of a class.
Differences between member variables and local variables
Scope
Member variable: valid for the entire class.
Local variable: valid only in a certain range. (generally refers to the method, in the statement body)
Storage location
Member variable: exists with the creation of the object, disappears with the disappearance of the object, and is stored in heap memory.
Local variable: it exists when a method is called or a statement is executed and is stored in stack memory. When the method is called or the statement ends, it is automatically released.
life cycle
Member variable: exists with the creation of the object and disappears with the disappearance of the object
Local variable: automatically released when the method is called or the statement ends.
Initial value
Member variables: have default initial values.
Local variable: it has no default initial value and must be assigned before use.
Use principle
The principles to be followed when using variables are: proximity principle
First, find in the local scope and use it if necessary; Then look at the member location.
The function of defining a constructor that does nothing and has no parameters in Java
Before executing the constructor of a subclass, if a java program does not use super() to call the constructor specific to the parent class, it will call the constructor without parameters in the parent class. Therefore, if only the constructor with parameters is defined in the parent class, and the constructor of the child class does not use super() to call the specific constructor in the parent class, an error will occur during compilation, because the Java program cannot find a constructor without parameters in the parent class for execution. The solution is to add a constructor that does nothing and has no parameters to the parent class.
Before calling the subclass constructor, the constructor without parameters of the parent class will be called first. The purpose is to?
Help subclasses do initialization.
What is the function of a class constructor? If a class does not declare a constructor, can the modifier execute correctly? Why?
The main function is to complete the initialization of class objects. Can be executed. Because even if a class does not declare a constructor, it will have a default constructor without parameters.
What are the characteristics of construction methods?
The name is the same as the class name;
There is no return value, but the constructor cannot be declared with void;
It is automatically executed when generating the object of the class without calling.
Differences between static variables and instance variables
Static variable: because static variables do not belong to any instance object and belong to a class, there will only be one copy in memory. During class loading, the JVM will allocate memory space for static variables only once.
Instance variable: each time an object is created, the memory space of member variables will be allocated for each object. Instance variables belong to instance objects. In memory, when an object is created several times, there are several member variables.
Differences between static variables and ordinary variables
Static variables are also called static variables. The difference between static variables and non static variables is that static variables are shared by all objects and have only one copy in memory. It will be initialized when and only when the class is first loaded. Non static variables are owned by objects. They are initialized when creating objects. There are multiple copies, and the copies owned by each object do not affect each other.
Another point is that static member variables are initialized in the defined order.
How are static methods different from instance methods?
The difference between static method and instance method is mainly reflected in two aspects:
- When calling static methods externally, you can use "class name. Method name" or "object name. Method name". The instance method has only the latter method. That is, calling a static method eliminates the need to create an object.
- When accessing members of this class, static methods only allow access to static members (i.e. static member variables and static methods), but not instance member variables and instance methods; Instance methods do not have this restriction
Why is it illegal to call a non static member within a static method?
Because static methods can not be called through objects, other non static variables and non static variable members cannot be called in static methods.
What is the return value of a method? What is the function of the return value?
The return value of a method refers to the result obtained after the code in a method body is executed! (provided that the method may produce results). Function of return value: receive the result so that it can be used for other operations!
Inner class
What is an inner class?
In Java, you can put the definition of one class inside the definition of another class, which is the inner class. The internal class itself is an attribute of the class, which is consistent with the definition of other attributes.
What are the classifications of internal classes
Internal classes can be divided into four types: member internal classes, local internal classes, anonymous internal classes and static internal classes.
Static inner class
A static class defined inside a class is a static inner class.
public class Outer {<span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">int</span> radius <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> <span class="token keyword">static</span> <span class="token keyword">class</span> <span class="token class-name">StaticInner</span> <span class="token punctuation">{<!-- --></span> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">visit</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"visit outer static variable:"</span> <span class="token operator">+</span> radius<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span>
}
Static internal classes can access all static variables of external classes, but not non static variables of external classes; Static internal class creation method, new external class Static inner class (), as follows:
Outer.StaticInner inner = new Outer.StaticInner(); inner.visit();
- 1
- 2
Member inner class
A non static class defined within a class and at a member location is a member inner class.
public class Outer {<span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">int</span> radius <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> <span class="token keyword">private</span> <span class="token keyword">int</span> count <span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">;</span> <span class="token keyword">class</span> <span class="token class-name">Inner</span> <span class="token punctuation">{<!-- --></span> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">visit</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"visit outer static variable:"</span> <span class="token operator">+</span> radius<span class="token punctuation">)</span><span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"visit outer variable:"</span> <span class="token operator">+</span> count<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span>
}
Member inner classes can access all variables and methods of outer classes, including static and non-static, private and public. The inner class of the member depends on the instance of the outer class, and its creation method is the instance of the outer class new inner class (), as follows:
Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); inner.visit();
- 1
- 2
- 3
Local inner class
The internal class defined in the method is the local internal class.
public class Outer {<span class="token keyword">private</span> <span class="token keyword">int</span> out_a <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span> <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">int</span> STATIC_b <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">;</span> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testFunctionClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span> <span class="token keyword">int</span> inner_c <span class="token operator">=</span><span class="token number">3</span><span class="token punctuation">;</span> <span class="token keyword">class</span> <span class="token class-name">Inner</span> <span class="token punctuation">{<!-- --></span> <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">fun</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>out_a<span class="token punctuation">)</span><span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>STATIC_b<span class="token punctuation">)</span><span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>inner_c<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> Inner inner <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Inner</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> inner<span class="token punctuation">.</span><span class="token function">fun</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">testStaticFunctionClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span> <span class="token keyword">int</span> d <span class="token operator">=</span><span class="token number">3</span><span class="token punctuation">;</span> <span class="token keyword">class</span> <span class="token class-name">Inner</span> <span class="token punctuation">{<!-- --></span> <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">fun</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span> <span class="token comment">// System.out.println(out_a); Compilation error. Local classes defined in static methods cannot access instance variables of external classes</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>STATIC_b<span class="token punctuation">)</span><span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>d<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> Inner inner <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Inner</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> inner<span class="token punctuation">.</span><span class="token function">fun</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span>
}
The local class defined in the instance method can access all variables and methods of the external class, and the local class defined in the static method can only access the static variables and methods of the external class. The creation method of the local internal class, in the corresponding method, new internal class (), is as follows:
public static void testStaticFunctionClass(){ class Inner { } Inner inner = new Inner(); }
- 1
- 2
- 3
- 4
- 5
Anonymous Inner Class
Anonymous internal classes are internal classes without names, which are often used in daily development.
public class Outer {<span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">test</span><span class="token punctuation">(</span><span class="token keyword">final</span> <span class="token keyword">int</span> i<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> <span class="token keyword">new</span> <span class="token class-name">Service</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">method</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> j <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> j <span class="token operator"><</span> i<span class="token punctuation">;</span> j<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"Anonymous Inner Class "</span> <span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span><span class="token punctuation">.</span><span class="token function">method</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span>
}
//Anonymous inner classes must inherit or implement an existing interface
interface Service{
void method();
}
In addition to having no name, anonymous inner classes have the following characteristics:
- Anonymous inner classes must inherit an abstract class or implement an interface.
- Anonymous inner classes cannot define any static members and static methods.
- When the formal parameter of the method needs to be used by the anonymous inner class, it must be declared as final.
- Anonymous inner classes cannot be abstract. They must implement all abstract methods of inherited classes or implemented interfaces.
Anonymous inner class creation method:
new class/Interface{ //Anonymous inner class implementation part }
- 1
- 2
- 3
Advantages of inner classes
Why should we use inner classes? Because it has the following advantages:
- An internal class object can access the contents of the external class object that created it, including private data!
- The inner class is not seen by other classes in the same package and has good encapsulation;
- The internal class effectively implements "multiple inheritance" and optimizes the defect of java single inheritance.
- Anonymous inner classes can easily define callbacks.
What are the application scenarios of internal classes
- Some multi algorithm occasions
- Solve some non object-oriented statement blocks.
- Proper use of internal classes makes the code more flexible and extensible.
- When a class is no longer used by other classes except its external class.
When local inner classes and anonymous inner classes access local variables, why must final be added to the variables?
When local inner classes and anonymous inner classes access local variables, why must final be added to the variables? What is its internal principle?
Look at this code first:
public class Outer {<span class="token keyword">void</span> <span class="token function">outMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span> <span class="token keyword">final</span> <span class="token keyword">int</span> a <span class="token operator">=</span><span class="token number">10</span><span class="token punctuation">;</span> <span class="token keyword">class</span> <span class="token class-name">Inner</span> <span class="token punctuation">{<!-- --></span> <span class="token keyword">void</span> <span class="token function">innerMethod</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{<!-- --></span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span>
}
In the above example, why add final? Because the life cycle is inconsistent, local variables are directly stored in the stack. When the method execution ends, non final local variables are destroyed. The reference of the local internal class to the local variable still exists. If the local internal class wants to call the local variable, an error will occur. The addition of final can ensure that the variables used by the local internal class are distinguished from the external local variables, which solves this problem.
Internal class related, see the program say the running results
public class Outer { private int age = 12;<span class="token keyword">class</span> <span class="token class-name">Inner</span> <span class="token punctuation">{<!-- --></span> <span class="token keyword">private</span> <span class="token keyword">int</span> age <span class="token operator">=</span> <span class="token number">13</span><span class="token punctuation">;</span> <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">print</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> <span class="token keyword">int</span> age <span class="token operator">=</span> <span class="token number">14</span><span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"Local variables:"</span> <span class="token operator">+</span> age<span class="token punctuation">)</span><span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"Internal class variables:"</span> <span class="token operator">+</span> <span class="token keyword">this</span><span class="token punctuation">.</span>age<span class="token punctuation">)</span><span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"External class variables:"</span> <span class="token operator">+</span> Outer<span class="token punctuation">.</span><span class="token keyword">this</span><span class="token punctuation">.</span>age<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> Outer<span class="token punctuation">.</span>Inner in <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Outer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token keyword">new</span> <span class="token class-name">Inner</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> in<span class="token punctuation">.</span><span class="token function">print</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span>
}
Operation results:
Local variables: 14 Internal class variables: 13 External class variables: 12
- 1
- 2
- 3
Rewriting and overloading
Can the constructor be overridden
Constructors cannot be inherited, so they cannot be overridden, but they can be overloaded.
The difference between Overload and Override. Can overloaded methods be distinguished according to the return type?
Method overloading and rewriting are ways to realize polymorphism. The difference is that the former realizes compile time polymorphism, while the latter realizes run-time polymorphism.
Overload: occurs in the same class, with the same method name and different parameter lists (different parameter types, different numbers and different orders), which has nothing to do with the method return value and access modifier, that is, overloaded methods cannot be distinguished according to the return type
Rewriting: occurs in parent-child classes. The method name and parameter list must be the same. The return value must be less than or equal to the parent class, the thrown exception must be less than or equal to the parent class, and the access modifier must be greater than or equal to the parent class (Richter substitution principle); If the method access modifier of the parent class is private, it is not overridden in the child class.
Object equality judgment
==What is the difference between and equals
==: it is used to judge whether the addresses of two objects are equal. That is, judge whether two objects are the same object. (basic data type = = compares values, reference data type = = compares memory addresses)
equals(): it is also used to judge whether two objects are equal. However, it is generally used in two cases:
Case 1: the class does not override the equals () method. When comparing two objects of this class through equals(), it is equivalent to comparing the two objects through "= =".
Case 2: the class overrides the equals() method. Generally, we override the equals() method to make the contents of two objects equal; Returns true if their contents are equal (that is, the two objects are considered equal).
for instance:
public class test1 { public static void main(String[] args) { String a = new String("ab"); // A is a reference String b = new String("ab"); // b is another reference, and the content of the object is the same String aa = "ab"; // Put in constant pool String bb = "ab"; // Find from constant pool if (aa == bb) // true System.out.println("aa==bb"); if (a == b) // false, not the same object System.out.println("a==b"); if (a.equals(b)) // true System.out.println("aEQb"); if (42 == 42.0) { // true System.out.println("true"); } } }explain:
- String Medium equals Method is rewritten because object of equals The method is to compare the memory address of the object, and String of equals Method compares the value of the object.
- When created String When an object of type, the virtual opportunity looks for an object with the same value as the one to be created in the constant pool. If so, it will be assigned to the current reference. If not, recreate one in the constant pool String Object.
hashCode And equals (important)
HashSet How to check for duplicates
Of two objects hashCode() Same, then equals() It must be true,Am I right?
hashCode and equals Relationship between methods
The interviewer may ask you, "have you rewritten it hashcode and equals Well, why rewrite equals Must be overridden when hashCode Method? "
hashCode()introduce
hashCode() The function of is to obtain hash code, also known as hash code; It actually returns a int Integer. This hash code is used to determine the index position of the object in the hash table. hashCode() Defined in JDK of Object.java In, this means Java Any class in contains hashCode()Function.
Hash tables store key value pairs(key-value),Its characteristic is that it can quickly retrieve the corresponding "value" according to the "key". This makes use of hash code! (you can quickly find the required object)
Why hashCode
We take“ HashSet How to check for duplication "is an example to illustrate why hashCode:
When you add objects HashSet When, HashSet The of the object will be calculated first hashcode Value to determine the location of the object to be added, and it will also be compared with other added objects hashcode Values are compared if there is no match hashcode,HashSet It is assumed that the object does not reappear. But if you find the same hashcode Value, which is called equals()Method to check hashcode Whether equal objects are really the same. If the two are the same, HashSet It will not make the join operation successful. If it is different, it will be hashed to another location. (from my Java Enlightenment book< Head first java>Second Edition). In this way, we greatly reduce equals Accordingly, the execution speed is greatly improved.
hashCode()And equals()Relevant provisions of
If two objects are equal, then hashcode It must be the same
Two objects are equal, and two objects are called separately equals Methods return true
Two objects have the same hashcode Values, they are not necessarily equal
So, equals Method is overridden, then hashCode Methods must also be overridden
hashCode() The default behavior of is to produce unique values for objects on the heap. If not rewritten hashCode(),Then class The two objects of will not be equal in any case (even if they point to the same data)
What is the difference between the equality of objects and the equality of references to them?
The equality ratio of objects is whether the contents stored in memory are equal, while the equality of references is whether the memory addresses they point to are equal.
pass by value
When an object is passed as a parameter to a method, the method can change the properties of the object and return the changed results. Is this value transfer or reference transfer
Is value passing. Java Language method calls only support parameter value passing. When an object instance is passed to a method as a parameter, the value of the parameter is a reference to the object. The properties of the object can be changed during the call, but the change of the object reference will not affect the caller
Why? Java Only values are passed in
First, let's review some technical terms in programming language about passing parameters to methods (or functions).Call by value(call by value)The representation method receives the value provided by the caller and is called by reference( call by reference)The representation method receives the variable address provided by the caller. A method can modify the variable value corresponding to the passed reference, but cannot modify the variable value corresponding to the passed value call. It is used to describe various programming languages (not just Java)Method parameter transfer method in.
Java Programming languages always use call by value. That is, the method gets a copy of all parameter values, that is, the method cannot modify the contents of any parameter variables passed to it.
Here are three examples to illustrate
example 1
public static void main(String[] args) { int num1 = 10; int num2 = 20;<span class="token function">swap</span><span class="token punctuation">(</span>num1<span class="token punctuation">,</span> num2<span class="token punctuation">)</span><span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"num1 = "</span> <span class="token operator">+</span> num1<span class="token punctuation">)</span><span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"num2 = "</span> <span class="token operator">+</span> num2<span class="token punctuation">)</span><span class="token punctuation">;</span>
}
public static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"a = "</span> <span class="token operator">+</span> a<span class="token punctuation">)</span><span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"b = "</span> <span class="token operator">+</span> b<span class="token punctuation">)</span><span class="token punctuation">;</span>
}
result:
a = 20 b = 10 num1 = 10 num2 = 20
- 1
- 2
- 3
- 4
Resolution:
In the swap method, the values of a and b are exchanged without affecting num1 and num2. Because the values in a and b are only copied from num1 and num2. In other words, a and b are equivalent to the copies of num1 and num2. No matter how the contents of the copies are modified, they will not affect the original itself.
Through the above example, we have learned that a method cannot modify parameters of a basic data type, but object references are different as parameters. See example 2
example 2
public static void main(String[] args) { int[] arr = { 1, 2, 3, 4, 5 }; System.out.println(arr[0]); change(arr); System.out.println(arr[0]); }<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">change</span><span class="token punctuation">(</span><span class="token keyword">int</span><span class="token punctuation">[</span><span class="token punctuation">]</span> array<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> <span class="token comment">// Change the first element of the array to 0</span> array<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> <span class="token punctuation">}</span>
result:
1 0
- 1
- 2
Resolution:
Array is initialized. The copy of arr is a reference to an object, that is, array and arr point to the same array object. Therefore, external changes to the reference object will be reflected on the corresponding object.
As we have seen from example 2, it is not difficult to implement a method to change the state of object parameters. The reason is very simple. The method gets a copy of the object reference. The object reference and other copies reference the same object at the same time.
Many programming languages (especially C + + and Pascal) provide two ways to pass parameters: value call and reference call. Some programmers (even the authors of this book) think that the Java programming language uses reference calls to objects. In fact, this understanding is wrong. Because this misunderstanding is universal, a counterexample is given below to illustrate this problem in detail.
example 3
public class Test {<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> <span class="token comment">// TODO Auto-generated method stub</span> Student s1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Student</span><span class="token punctuation">(</span><span class="token string">"Xiao Zhang"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> Student s2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Student</span><span class="token punctuation">(</span><span class="token string">"petty thief"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> Test<span class="token punctuation">.</span><span class="token function">swap</span><span class="token punctuation">(</span>s1<span class="token punctuation">,</span> s2<span class="token punctuation">)</span><span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"s1:"</span> <span class="token operator">+</span> s1<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"s2:"</span> <span class="token operator">+</span> s2<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">swap</span><span class="token punctuation">(</span>Student x<span class="token punctuation">,</span> Student y<span class="token punctuation">)</span> <span class="token punctuation">{<!-- --></span> Student temp <span class="token operator">=</span> x<span class="token punctuation">;</span> x <span class="token operator">=</span> y<span class="token punctuation">;</span> y <span class="token operator">=</span> temp<span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"x:"</span> <span class="token operator">+</span> x<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"y:"</span> <span class="token operator">+</span> y<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span>
}
result:
x:petty thief y:Xiao Zhang s1:Xiao Zhang s2:petty thief
- 1
- 2
- 3
- 4
Resolution:
Before exchange:
After exchange:
It can be clearly seen from the above two figures that the method does not change the object reference stored in variables s1 and s2. The parameters x and y of the swap method are initialized to copies of two object references, which are exchanged by this method
summary
The Java programming language does not use reference calls on objects. In fact, object references are passed by value.
The following is a summary of the use of method parameters in Java:
- A method cannot modify a parameter of a basic data type (that is, numeric or Boolean)
- A method can change the state of an object parameter.
- A method cannot have an object parameter reference a new object.
What is the difference between value passing and reference passing
Value Passing: when a method is called, the parameters passed are passed according to the copy of the value, which means that they are not related to each other after passing.
Reference passing: when a method is called, the parameters passed are passed by reference. In fact, the address of the reference passed is the address of the memory space corresponding to the variable. What is passed is a reference to a value, that is, both before and after passing point to the same reference (that is, the same memory space).
Java package
What packages are commonly used in JDK
- java.lang: This is the basic class of the system;
- java.io: there are all classes related to input and output, such as file operation;
- java.nio: a new package written to improve the functions in the io package and improve the performance in the io package;
- java.net: there are classes related to network;
- java.util: This is the system auxiliary class, especially the collection class;
- java.sql: This is the class of database operation.
What is the difference between import java and javax
At the beginning, the package necessary for Java API was the package beginning with Java, and javax was only used for extending API package at that time. However, over time, javax has gradually expanded into a part of the Java API. However, moving extensions from the javax package to the java package will be too cumbersome and will eventually destroy a pile of existing code. Therefore, it was ultimately decided that the javax package would become part of the standard API.
So, in fact, there is no difference between java and javax. It's all a name.
IO stream
How many types of IO streams are there in java?
- According to the flow direction, the flow can be divided into input flow and output flow;
- According to the division of operation units, it can be divided into byte stream and character stream;
- According to the role of flow, it is divided into node flow and processing flow.
The Java Io stream involves more than 40 classes. These classes look very messy, but they are actually very regular, and they are closely related to each other. More than 40 classes of the Java I0 stream are derived from the following four abstract classes and base classes.
- InputStream/Reader: the base class of all input streams. The former is byte input stream and the latter is character input stream.
- OutputStream/Writer: the base class of all output streams. The former is byte output stream and the latter is character output stream.
Structure diagram classified by operation mode:
Classification structure chart by operation object:
What's the difference between bio, NiO and AIO?
Brief answer
- BIO: Block IO synchronous blocking IO is the traditional IO we usually use. It is characterized by simple mode, convenient use and low concurrent processing capacity.
- NIO: Non IO synchronous non blocking IO is an upgrade of traditional io. The client and server communicate through Channel to realize multiplexing.
- AIO: Asynchronous IO is an upgrade of NIO, also known as NIO2. It realizes asynchronous non blocking io. The operation of Asynchronous IO is based on event and callback mechanism.
Detailed answer
- BIO (Blocking I/O): synchronous blocking I/O mode. Data reading and writing must be blocked in a thread and wait for it to complete. When the number of active connections is not particularly high (less than 1000 for a single machine), this model is relatively good. Each connection can focus on its own I/O, and the programming model is simple, without too much consideration of system overload, current limit and other problems. Thread pool itself is a natural funnel, which can buffer some connections or requests that the system can't handle. However, when faced with 100000 or even millions of connections, the traditional BIO model is powerless. Therefore, we need a more efficient I/O processing model to deal with higher concurrency.
- NIO (New I/O): NIO is a synchronous non blocking I/O model. NIO framework is introduced in Java 1.4, corresponding to Java NIO package provides abstractions such as channel, selector and Buffer. N in NIO can be understood as non blocking, not just New. It supports Buffer oriented, channel based I/O operations. NIO provides two different Socket channel implementations of SocketChannel and ServerSocketChannel corresponding to Socket and ServerSocket in the traditional BIO model. Both channels support blocking and non blocking modes. The use of blocking mode is as simple as the traditional support, but the performance and reliability are not good; Non blocking mode is the opposite. For low load and low concurrency applications, synchronous blocking I/O can be used to improve development speed and better maintainability; For high load and high concurrency (Network) applications, NIO's non blocking mode should be used for development
- AIO (Asynchronous I/O): AIO is NIO 2. NIO 2, an improved version of NIO, is introduced into Java 7. It is an asynchronous non blocking IO model. Asynchronous IO is implemented based on event and callback mechanism, that is, it will return directly after application operation and will not be blocked there. When the background processing is completed, the operating system will notify the corresponding thread for subsequent operation. AIO is the abbreviation of asynchronous io. Although NIO provides a non blocking method in network operation, NIO's IO behavior is synchronous. For NIO, our business thread is notified when the IO operation is ready, and then the thread performs the IO operation itself. The IO operation itself is synchronous. Looking up relevant information on the Internet, I found that at present, AIO is not widely used. Netty has tried to use AIO before, but gave up.
What are the common methods of Files?
- Files. exists(): check whether the file path exists.
- Files. createFile(): creates a file.
- Files. createDirectory(): creates a folder.
- Files. delete(): deletes a file or directory.
- Files. copy(): copy files.
- Files. move(): move files.
- Files. size(): view the number of files.
- Files. read(): read the file.
- Files. write(): write to a file.
reflex
What is the reflection mechanism?
Java reflection mechanism is to know all the properties and methods of any class in the running state; For any object, you can call any of its methods and properties; This kind of dynamically acquired information and the function of dynamically calling object methods are called the reflection mechanism of Java language.
Static compilation and dynamic compilation
- **Static compilation: * * determine the type and bind the object during compilation
- **Dynamic compilation: * * runtime determines the type and binds the object
Advantages and disadvantages of reflection mechanism
- Advantages: judgment of runtime type, dynamic loading of classes, and improvement of code flexibility.
- Disadvantages: performance bottleneck: reflection is equivalent to a series of interpretation operations to inform the JVM of what to do. The performance is much slower than that of direct java code.
What are the application scenarios of reflection mechanism?
Reflection is the soul of frame design.
In our usual project development process, reflection mechanism is rarely used directly, but this does not mean that reflection mechanism is useless. In fact, many designs and development are related to reflection mechanism, such as modular development, which calls the corresponding bytecode through reflection; The dynamic proxy design pattern also adopts the reflection mechanism, and the Spring / Hibernate and other frameworks we use daily also use the reflection mechanism.
For example: ① when using JDBC to connect to the database, we use Class Forname() loads the driver of the database through reflection; ② The Spring framework also uses many reflection mechanisms, the most classic of which is the XML configuration pattern. The process of Spring loading beans through XML configuration pattern: 1) load all XML or properties configuration files in the program into memory; 2) The Java Class parses the contents in XML or properties to obtain the bytecode string and related attribute information of the corresponding entity Class; 3) Use the reflection mechanism to obtain the Class instance of a Class according to this string; 4) Dynamically configure the properties of an instance
Three ways to get reflection in Java
1. Implement reflection mechanism through new object 2 Implement reflection mechanism through path 3 Implement reflection mechanism through class name
public class Student { private int id; String name; protected boolean sex; public float score; }
- 1
- 2
- 3
- 4
- 5
- 6
public class Get { //There are three ways to obtain reflection mechanism public static void main(String[] args) throws ClassNotFoundException { //Method 1 (by creating objects) Student stu = new Student(); Class classobj1 = stu.getClass(); System.out.println(classobj1.getName()); //Mode 2 (passing path - relative path) Class classobj2 = Class.forName("fanshe.Student"); System.out.println(classobj2.getName()); //Method 3 (by class name) Class classobj3 = Student.class; System.out.println(classobj3.getName()); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
Network programming
Network programming interview questions can see my article Learn TCP/IP protocol again, shake hands three times and wave hands four times The content includes not only the knowledge of TCP/IP protocol and three handshakes and four waves, but also the computer network architecture, HTTP protocol, the difference between get request and post request, and the difference between session and cookie. Welcome to read.
Common API
String correlation
The difference between character constant and string constant
- Formally: the character constant is a character string caused by single quotation marks, and the constant is several characters caused by double quotation marks
- Meaning: the character constant is equivalent to an integer value (ASCII value), which can participate in expression operation. The string constant represents an address value (where the string is stored in memory)
- Memory size character constant only takes two bytes, string constant takes several bytes (at least one character end flag)
What is a string constant pool?
The string constant pool is located in heap memory and is specially used to store string constants, which can improve memory utilization and avoid opening up multiple blocks of space to store the same string. When creating a string, the JVM will first check the string constant pool. If the string already exists in the pool, it will return its reference. If it does not exist, it will instantiate a string and put it in the pool, And returns its reference.
Is String the most basic data type
no There are only 8 basic data types in Java: byte, short, int, long, float, double, char, boolean; In addition to the primitive type, the rest are reference types. The enumeration type introduced after Java 5 is also a special reference type.
This is a very basic thing, but it is easy for many beginners to ignore. String is not included in the eight basic data types of Java. Char is used to describe text data, but it can only represent a single character, such as' a 'and' good '. If you want to describe a piece of text, you need to use multiple variables of char type, That is, an array of char type. For example, "hello" is an array of length 2. char[] chars = {you ',' good '};
However, using arrays is too cumbersome, so there is String. The bottom layer of String is an array of char type. Only when using, developers do not need to directly operate the bottom array, and can use strings in a simpler way.
What are the characteristics of String
-
Invariance: String is a read-only String. It is a typical immutable object. Any operation on it is actually to create a new object and point the reference to the object. The main function of invariant pattern is to ensure the consistency of data when an object needs to be shared and accessed frequently by multiple threads.
-
Constant pool Optimization: after the String object is created, it will be cached in the String constant pool. If the same object is created next time, the cached reference will be returned directly.
-
Final: use final to define the String class, which means that the String class cannot be inherited, which improves the security of the system.
Why is String immutable?
Simply put, the String class uses the char type array modified by final to store characters. The source code is shown in the figure below, so:
/** The value is used for character storage. */ private final char value[];
- 1
- 2
Is String really immutable?
I think if someone asks this question, the answer is invariable. Here are just two representative examples:
1) String is immutable, but does not mean that the reference cannot be changed
String str = "Hello"; str = str + " World"; System.out.println("str=" + str);
- 1
- 2
- 3
result:
str=Hello World
- 1
Resolution:
In fact, the content of the original String is unchanged, but str changes from the memory address pointing to "hello" to the memory address pointing to "Hello World", that is, an additional memory area is opened up for the "Hello World" String.
2) Through reflection, you can modify the so-called "immutable" object
// Create the string "Hello World" and assign it to the reference s String s = "Hello World";
System.out.println("s = " + s); // Hello World
//Gets the value field in the String class
Field valueFieldOfString = String.class.getDeclaredField("value");
//Change access to the value attribute
valueFieldOfString.setAccessible(true);
//Gets the value of the value attribute on the s object
char[] value = (char[]) valueFieldOfString.get(s);
//Change the fifth character in the array referenced by value
value[5] = '_';
System.out.println("s = " + s); // Hello_World
result:
s = Hello World s = Hello_World
- 1
- 2
Resolution:
Reflection can access private members, then reflect the value attribute in the String object, and then change the structure of the array through the obtained value reference. But generally we don't do that. Here's just a brief mention of this thing.
Can I inherit String class
String class is final and cannot be inherited.
Is String str="i" the same as String str=new String("i")?
Different, because the memory is allocated differently. String str="i", the java virtual opportunity allocates it to the constant pool; String str=new String("i") is divided into heap memory.
String s = new String(“xyz”); Several string objects were created
Two objects, one is the "xyz" of the static area, and the other is the object created on the heap with new.
String str1 = "hello"; //str1 points to the static area String str2 = new String("hello"); //str2 points to an object on the heap String str3 = "hello"; String str4 = new String("hello"); System.out.println(str1.equals(str2)); //true System.out.println(str2.equals(str4)); //true System.out.println(str1 == str3); //true System.out.println(str1 == str2); //false System.out.println(str2 == str4); //false System.out.println(str2 == "hello"); //false str2 = str1; System.out.println(str2 == "hello"); //true
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
How do I reverse a string?
Use the reverse() method of StringBuilder or stringBuffer.
Example code:
// StringBuffer reverse StringBuffer stringBuffer = new StringBuffer(); stringBuffer. append("abcdefg"); System. out. println(stringBuffer. reverse()); // gfedcba // StringBuilder reverse StringBuilder stringBuilder = new StringBuilder(); stringBuilder. append("abcdefg"); System. out. println(stringBuilder. reverse()); // gfedcba
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
Does the array have a length() method? Does String have a length() method
The array has no length() method and has a length attribute. String has a length() method. In JavaScript, the length of the string is obtained through the length attribute, which is easy to be confused with Java.
What are the common methods of the String class?
- indexOf(): returns the index of the specified character.
- charAt(): returns the character at the specified index.
- replace(): string replacement.
- trim(): remove whitespace at both ends of the string.
- split(): splits a string and returns an array of split strings.
- getBytes(): returns an array of byte types of strings.
- length(): returns the length of the string.
- toLowerCase(): converts a string to lowercase letters.
- toUpperCase(): converts a string to uppercase characters.
- substring(): intercepts the string.
- equals(): string comparison.
When using HashMap, what are the advantages of using String as key?
The internal implementation of HashMap determines the storage location of value through the hashcode of the key. Because the string is immutable, when creating a string, its hashcode is cached and does not need to be calculated again, so it is faster than other objects.
What is the difference between String, StringBuffer and StringBuilder? Why is String immutable
variability
String class uses character array to save string, private final char value [], so string object is immutable. Both StringBuilder and StringBuffer inherit from AbstractStringBuilder class. In AbstractStringBuilder, character array is also used to save strings, char[] value. Both objects are variable.
Thread safety
The object in String is immutable, which can be understood as a constant and thread safe. AbstractStringBuilder is the public parent class of StringBuilder and StringBuffer. It defines some basic String operations, such as expandCapacity, append, insert, indexOf and other public methods. StringBuffer adds a synchronization lock to the method or adds a synchronization lock to the called method, so it is thread safe. StringBuilder does not apply synchronization locks to methods, so it is non thread safe.
performance
Each time the String type is changed, a new String object will be generated, and then the pointer will point to the new String object. StringBuffer will operate on the StringBuffer object itself every time, instead of generating a new object and changing the object reference. In the same case, using StirngBuilder can only improve the performance by about 10% ~ 15% compared with using StringBuffer, but it takes the risk of unsafe multithreading.
Summary of the use of the three
If you want to manipulate a small amount of data, use = String
Single thread operation large amount of data in string buffer = StringBuilder
Multithreaded operation: operate a large amount of data in the string buffer = StringBuffer
Date related
Packaging related
Autoboxing and unboxing
Boxing: wrap basic types with their corresponding reference types;
Unpacking: convert the package type to the basic data type;
What's the difference between int and Integer
Java is an almost pure object-oriented programming language, but basic data types are introduced for programming convenience. However, in order to operate these basic data types as objects, Java introduces the corresponding wrapper class for each basic data type. The wrapper class of int is Integer, Since Java 5, the automatic packing / unpacking mechanism has been introduced, so that they can be converted to each other.
Java provides wrapper types for each primitive type:
Primitive types: boolean, char, byte, short, int, long, float, double
Packing type: Boolean, Character, Byte, Short, Integer, Long, Float, Double
Is Integer a= 127 equal to Integer b = 127
For object reference type: = = compares the memory address of the object.
For basic data types: = = values are compared.
If the value of the Integer literal is between - 128 and 127, the new Integer object will not be created during auto boxing, but the Integer object in the constant pool will be directly referenced. If the range a1==b1 is exceeded, the result is false
public static void main(String[] args) { Integer a = new Integer(3); Integer b = 3; // Automatically boxing 3 to Integer type int c = 3; System.out.println(a == b); // false two references do not refer to the same object System.out.println(a == c); // true a is automatically unpacked into int type, and then compared with c System.out.println(b == c); // trueInteger a1 <span class="token operator">=</span> <span class="token number">128</span><span class="token punctuation">;</span> Integer b1 <span class="token operator">=</span> <span class="token number">128</span><span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>a1 <span class="token operator">==</span> b1<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// false</span> Integer a2 <span class="token operator">=</span> <span class="token number">127</span><span class="token punctuation">;</span> Integer b2 <span class="token operator">=</span> <span class="token number">127</span><span class="token punctuation">;</span> System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>a2 <span class="token operator">==</span> b2<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// true</span>
}