interview Java I will ask SE Some basic knowledge , I’ve been asked many times , This article records some frequently asked questions and answers .
One 、 understand JDK、JRE、JVM
-
JDK(Java Development Kit)Java Development kit , As a whole Java The core of development , Which includes JRE, namely Java Runtime environment , Have compilers and tools (javadoc、jdb) etc. . If it’s development Java The program only needs to be installed JDK that will do .
-
JRE(Java Runtime Environment):Java Runtime environment , Which includes JVM Standards implementation 、Java Class library and some basic components .JRE For operation Java Program , Instead of creating and developing Java Program , But if the running program contains the program to be compiled ( for example JSP Need to convert to Servlet) You need to install jdk.
-
JVM(Java Virtual Machine):Java virtual machine , It will be able to class The bytecode instruction in the file identifies the machine code and calls the API Complete the action .JVM Specific implementation for different operating systems , This is a Java The key to cross platform .
all Java Development and operation environments are not necessarily provided by the same manufacturer , For the most part Sun company ( Present quilt Oracle Acquisition ) Provided ,JDK、JRE、JVM And so on have different implementations . such as JDK Yes Oracle JDK、Open JDK And other companies JDK etc. ,JVM Yes Sun HotSpot VM、IBM J9 VM、Google Android Dalvik VM And other things VM etc. . In general, we use Oracle JDK + HotSpot VM.
Two 、 Overloading and rewriting
-
heavy load (Overload): Occurs in the same class , Method name must be the same , Parameter type 、 Number of parameters 、 Parameter sequence 、 Return value 、 Access modifier can be different .
-
rewrite (Override): Occurs in a parent-child class , Method name 、 Parameters must be the same , The return value must be the return value of the parent class or its subclass , Exception must be a parent exception or a child of it , Access modifier permission must be greater than or equal to parent class , except private, By private Decorated method cannot be overridden .
private (private) Methods and constructors cannot be overridden , But it can be overloaded , A class can have multiple overloaded construction methods .
3、 … and 、Java Three characteristics of
-
encapsulation : Provides access modifiers to control access visibility of properties and methods ,Java Four access modifiers in :private、default、protect、public. Special attention : External classes can access the private/protected Variable , At compile time , External and internal classes are no longer nested , Instead, it becomes two classes in a package , And then to private Access to variables , The compiler generates one accessor function .
- private: Same class accessible
- default: The same class and package are accessible
- protect: Same class 、 Same package 、 Subclasses can access
- public: Same class 、 Same package 、 Subclass 、 Other packages are accessible
-
Inherit : Subclass inherits parent , The child class has all the properties and methods of the parent class , But only non private Properties and methods of , The properties and methods of a subclass are not visible to the parent , Subclass can override the non private He Fei final Methods . Using inheritance properly in development can reuse code easily , Inheritance provides great convenience in refactoring .
-
polymorphic : The specific type of the reference variable defined in the program and the method call issued by the reference variable are not determined during programming , It’s determined during program operation , That is, which class of instance object does a reference variable point to when it bottoms down , The method call issued by the reference variable is the method implemented in which class , Must be determined during run by program . There are three forms of polymorphism :
- Inherit : There must be subclass and superclass with inheritance relationship in polymorphism
- rewrite / Implementation interface : Subclass redefining some methods in the parent class , When these methods are called, the subclass’s methods are called
- Upward transformation : In polymorphism, you need to assign a reference of a subclass to a parent object , Only in this way can the reference have the skills to call the methods of the parent class and the subclass
Four 、 Interface (interface) And abstract classes (abstract) The difference between
- Abstract classes can have constructors , Cannot have constructor in interface .
- The default for abstract methods in an interface is public, But it can only be public, Abstract methods cannot be implemented concretely ,jdk8 You can have default Method realization , Abstract classes can have both abstract and non abstract methods . In a sense, interface is a special abstract class .
- Static methods can be included in abstract classes , stay JDK1.8 Static methods cannot be excluded from the previous interface ,JDK1.8 Later, it can include .
- The default instance variable of the interface is final type , Do not modify the , Abstract classes are not necessarily .
- A class can implement multiple interfaces , But you can only inherit from one abstract class , Interface can’t implement interface , But you can inherit interfaces , And can inherit multiple interfaces .
- The interface doesn’t work new Instantiation , But variables can be declared , Its variable must refer to an object instantiated by the interface .
5、 … and 、== and equals difference
==: If you are comparing basic data types , Judge whether its value is equal ; If you are comparing reference types , Determine whether the addresses of two objects are equal .
equals:equals Is in Object Methods defined in class , stay Object Class to compare only two objects with the same address .
public boolean equals (Object x){
return this == x;
}
Everyone knows that all classes are Object Subclasses of , So you can choose whether to override equals Method , With String Class equals Methods as an example ,equals Method to determine whether the value of a string is the same .
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
In rewriting equals Several rules need to be satisfied in method :
- reflexivity . For any non null Reference value x,x.equals(x) Should return true.
- symmetry . For any non null Reference value x And y, If and only if :y.equals(x) return true when ,x.equals(y) To return to true.
- Transitivity . For any non null Reference value x、y And z, If y.equals(x) return true,y.equals(z) return true, that x.equals(z) Should also return to true.
- Uniformity . For any non null Reference value x And y, Suppose the object is equals The information in the comparison has not been modified , Call… Multiple times x.equals(y) Always return true Or always return false.
- For any non null reference value x,x.equal(null) Should return false.
equals Method is used to judge whether two objects are the same in the practical sense , For example, there are two photos to judge whether the person is the same , Although the clothes in the two photos 、 The environment is different , But it’s actually the same person .equals Methods often and hashCode() Use it together .
6、 … and 、hashCode and equals
equals The method is described above ,hashCode() Defined in Object Class , This method is used to get hash code , It returns a int Type value , Hash hash code is used to determine the index position of the object in the hash table , The purpose is to support Map Interface . stay Object Class hashCode It’s a native Method , It is uniquely determined by the location in the virtual machine heap , In general, when rewriting this method, you need to define its own algorithm .
rewrite equals Must rewrite hashCode Method ?
Not necessarily , Many articles on the Internet say that they must be rewritten at the same time , This is based on reasonable design . If a class does not involve HashSet、Hashtable、HashMap Wait for classes that use the data structure of the hash table internally , Can be overridden hashCode Method , Because if the hash table is not involved hashCode It doesn’t make sense . But in the actual coding, it requires rewriting at the same time , Because you can’t predict whether this class will be applied to a class with a hash table , So there are usually “ rewrite equals Must rewrite hashCode Method ” That’s what I’m saying .
- Two objects are equal , be hashCode It must be the same ;
- Two objects are equal , Call each other equals Methods also return true;
- Two objects have the same hashCode value , They call each other equals Not necessarily back true( It could happen Hash Collision ).
7、 … and 、String、StringBuilder、StringBuffer difference
variability
String Class immutable , It applies for a fixed length of char A character array final char value[]
, And not modifiable , Usually used + String concatenation actually opens up multiple memory spaces , Heap memory available for final result string , The rest of the space is rubbish , Readers can read an article I once wrote to understand :Java in String Knowledge that is most easily ignored by objects .
StringBuffer and StringBuilder Are all variable string classes , They all inherit from AbstractStringBuilder
class , The character array definition is variable char[] value
, In which each string concatenation changes in the current heap memory if the capacity is sufficient , Open up new space if not enough , Each expansion is the original capacity 2 times +2, This is how it is implemented in the source code :(value.length << 1) + 2
, The maximum capacity is Integer.MAX_VALUE - 8
, Why subtract 8 Well ? Because the object head needs to occupy a certain space , Actual occupancy depends on the number of virtual machines .
Multithreading security
String and StringBuffer Is multithreaded safe ,String The character array of is final Of , So it’s thread safe without modification , and StringBuffer The thread security is realized by synchronous lock , All of its methods are used synchronized Decorate to ensure thread safety . and StringBuilder Non thread safe .
Applicable conditions
Suitable when string splicing is rare String class . When string splicing is frequent , If you operate on variables only in a single thread , fit StringBuilder; In the case of multithreading , Use StringBuffer Can better ensure its safety . In the case of a single thread ,StringBuilder Compared with StringBuffer Yes 15% Left right performance improvement .
8、 … and 、”abc” And new String(“abc”)
There are usually two ways to create a string , One is to directly use double quotation marks to create "abc"
, One is new One String class . Both methods can create strings , But the process is different , Please read this article for details :Java in String Knowledge that is most easily ignored by objects .
These two methods involve String Of intern Method realization , stay jdk6 and jdk6 There will be some differences in specific implementation in the future , It’s just about jdk6 Future implementation .
- Double quotation mark creation checks whether the string exists in the constant pool , If the constant pool has one, the reference of the constant pool will be returned directly , If not, check if the string exists in the heap , Add references to this object in the heap to the constant pool if they exist , And return the reference , If it doesn’t exist in the heap , Just create a string in the pool and return its reference .
- new One String Class is to create a new object directly in heap memory , But the string passed in by the constructor is another String object , If there is no such string in the object pool, there will be more garbage in the heap memory , Therefore, the first double quotation mark is recommended for normal use .
Nine 、 Constructors 、 Building blocks of code 、 Static code block
Let’s take a look at these three in the code
public class Test1 {
Test1() {
System.out.println(" Constructors ");
}
{
System.out.println(" Building blocks of code ");
}
static {
System.out.println(" Static code block ");
}
public static void main(String[] args) {
System.out.println("main Function execution ");
new Test1();
}
}
The result of the above code is :
Static code block
main Function execution
Building blocks of code
Constructors
-
Constructors
- Object 1 Establishment , The corresponding constructor will be called , Do not instance objects , Constructor will not run .
- Constructor is used to initialize objects .
- An object is created , Constructor runs only once , The general method can be called multiple times by the object .
-
Building blocks of code
- The purpose of building blocks is to initialize objects .
- Building blocks run as soon as objects are created , and Takes precedence over constructor execution . With object instantiation , To run the building block , Class cannot call a building block .
- Construction of code blocks and constructors difference yes : The construction code block is the unified initialization of all objects , The constructor initializes the corresponding object , Because constructors can be multiple , What kind of object will be created by running which constructor , But no matter which object is created , Will execute the same building block first . in other words , The initialization contents of different objects are defined in the construction code block .
-
Static code block
- It is executed as the class is loaded , Only once , And takes precedence over the main function . This happens during the class load life cycle Initialization phase Readers can read this article I wrote before On a Java The life cycle of a class .
- Static code blocks are used to initialize classes , Building blocks is initializing objects .
- Variables in static code blocks are local variables , There is no difference between the properties of local variables and ordinary functions .
- There can be multiple static code blocks in a class
Ten 、final、finally、finalize difference
- final:Java keyword , It can be used to modify a class 、 Method 、 Variable , They have different meanings ,final Embellished class Represents that extension cannot be inherited ,final We can’t modify the variables of , and final The method of can’t be rewritten (override).
- finally: Java A mechanism to ensure that key code must be executed . We can use
try-finally
perhapstry-catch-finally
To make a similar shutdown JDBC Connect 、 Guarantee unlock Lock and so on . - finalize: Foundation class Object One way , It is designed to ensure that objects are recycled before being garbage collected .finalize The mechanism is now not recommended , And in JDK9 The beginning is marked as deprecated.
11、 … and 、Java Value passing and reference passing in
Because this part of knowledge is easy to forgive , So I will combine the code description .
Value passed
Method passing object is the basic data type , Method gets a copy of the parameter value , No matter what changes the method makes to its transfer variables , Its original value will not change , Because the method body operates on the copied data .
public static void main(String[] args) {
int a = 1, b = 2;
change(a, b);
System.out.println("a = " + a + ",b = " + b);
// The result of the operation is : a = 1,b = 2
}
static void change(int a, int b) {
a = 3;
b = 4;
}
reference
The object passed by reference is a reference data type or an array type , Method gets the heap memory address of the object , Method to change the contents of objects in heap memory , But it’s a little confusing with value passing , I’m sure the following code won’t be confused .
static class User{
String name;
User(String name){
this.name = name;
}
}
public static void main(String[] args) {
User user1 = new User(" north wind ");
User user2 = new User("tz");
swap(user1,user2);
// This method is exchange user1 and user2 Heap memory for , It turns out to be a failure ,
// Because the stack memory of both of them has not changed , Still pointing to the original heap memory
System.out.println("user1:"+user1.name+"; user2:"+user2.name);
// The result of the operation is : user1: north wind ; user2:tz
change(user1,user2);
// The approach is to change user1 and user2 Of name attribute , You will be successful ,
// Because reference passing can modify the contents of heap memory
System.out.println("user1:"+user1.name+"; user2:"+user2.name);
// The result of the operation is : user1:AAAAAAA; user2:BBBBBBB
}
// In exchange for user1 and user2 Address
static void swap(User user1,User user2) {
User temp = user1;
user1 = user2;
user2 = temp;
}
// modify user1 and user2 The content of
static void change(User user1,User user2) {
user1.name = "AAAAAAA";
user2.name = "BBBBBBB";
}
Twelve 、 How to get an instance of a class
- new object , Use keywords new Create an object instance directly in heap memory .
- clone(),clone() Method defined in Object class , Used to clone as like as two peas from a heap memory to a new heap memory. , Cloned objects must be implemented Cloneable Interface , There is no actual definition of this interface , For identification only .
- Reflection , Instantiate any class in the running state , And all its properties and methods can be called , You can even break the rules of access control permission , namely private Definitions can also be accessed . Worry about dynamic loading class , Can improve code flexibility . The disadvantage is that it is easy to cause performance bottleneck , Class interpretation process JVM To do , increase JVM burden .
- Deserialization ObjectInputStream,, Converting binary streams to class objects , Binary streams must be created by Java Serialized . The specific implementation can read the article I wrote before Serialization and deserialization