Java basics for Android interview

Bald bald bald bald 2022-02-13 07:08:02 阅读数:59

java basics android interview

Basic concepts and common sense

1. Java What are the characteristics of language ?

  • object-oriented ( encapsulation , Inherit , polymorphic )
  • Platform independence ( Java Platform independence of virtual machine )
  • Multithreading support
  • It supports network programming and is very convenient
  • Compilation and interpretation coexist
  • “Write Once, Run Anywhere( Write once , Run anywhere )”
  • Strong Ecology

2. JVM vs JDK vs JRE

JVM:
Java virtual machine (JVM) Is to run Java The virtual machine of bytecode .JVM There are specific implementations for different systems (Windows,Linux,macOS), The purpose is to use the same bytecode , They all give the same result .
JVM There is not only one ! As long as meet JVM standard , Every company 、 Organizations or individuals can develop their own exclusive JVM.
In addition to what we usually use most HotSpot VM Outside , also J9 VM、Zing VM、JRockit VM etc. JVM .
JDK:
JDK yes Java Development Kit abbreviation , It's fully functional Java SDK.
It has a JRE Everything you have , And the compiler (javac) And tools ( Such as javadoc and jdb). It can create and compile programs .
JRE:
JRE yes Java Runtime environment .
It is Run compiled Java A collection of all the content required by a program , Include Java virtual machine (JVM),Java Class library ,java command And some other basic components . however , It can't be used to create new programs .

function Java Program ——JRE
Java Programming ——JDK

 Insert picture description here

3. Bytecode

stay Java in ,JVM Understandable code is called Bytecode ( The extension is .class The file of ), It does not target any specific processor , Virtual machine only .
Java Language by bytecode , Up to a point It solves the problem of low execution efficiency of traditional interpretative language The problem of , At the same time, it retains the explanatory language portable Characteristics .
Because bytecode is not specific to a particular machine , therefore ,Java The program can run on computers of different operating systems without recompilation .
 Insert picture description here
What we need to pay special attention to is .class-> Machine code This step . In this step JVM Class loader first loads the bytecode file , And then through The interpreter interprets and executes... Line by line , In this way The execution speed will be relatively slow . and , Some methods and code blocks are often called ( It's called Hot code ), So the introduction of JIT(just-in-time compilation) compiler , and JIT Belong to Compile at run time . When JIT After the compiler completes the first compilation , It will the byte code corresponding to Save the machine code , You can use it directly next time . And we know that , The operation efficiency of machine code must be higher than Java Of the interpreter . It also explains why we often say Java It's a language where compilation and interpretation coexist .

JDK 9 A new compilation mode is introduced AOT(Ahead of Time Compilation), It compiles bytecode directly into machine code , This avoids JIT Preheat and other expenses .JDK Support hierarchical compilation and AOT Collaborative use of . however ,AOT The compiler's compilation quality is certainly not comparable to JIT Compiler .

4. Why do you say Java Language " Compilation and interpretation coexist "?

We can divide high-level programming languages into two types according to the execution mode of programs :
A compiled : Compiler language (opens new window) Through the compiler (opens new window) take The source code is translated into machine code that can be executed by the platform at one time . In general , Compiler language The execution speed is relatively fast , Development efficiency is relatively low . Common compiled languages are C、C++、Go、Rust wait .
interpreted : Explanatory language (opens new window) Through the interpreter (opens new window) Explain the code sentence by sentence (interpret) Code for the machine before executing . Explanatory language Development efficiency is relatively fast , The execution speed is slow . Common explanatory languages are Python、JavaScript、PHP wait .
 Insert picture description here
Java Language has both Compiler language Characteristics of , Also has the Explanatory language Characteristics of . because Java The procedure has to go through To compile the first , Explain later Two steps , from Java The written program needs to go through Compilation steps , Generated bytecode (.class file ), This bytecode must be made by Java Interpreter to explain execution .

5. Java and C++ The difference between ?

  • All are object-oriented Language , All support encapsulation Inherit and polymorphic
  • Java No pointers are provided to directly access memory , Program memory is more secure
  • Java The class is Single inheritance Of ,C++ Support for multiple inheritance ; although Java Can't inherit more , however Interfaces can inherit more .
  • Java Yes Automatic memory management garbage collection mechanism (GC), There's no need for programmers to manually release useless memory .
  • C ++ It supports both method overloading and operator overloading , however Java Only method overloading is supported ( Operator overloading adds complexity , This is related to Java The original design idea didn't match ).

Basic grammar

1. The difference between character type constant and string constant ?

  • Character constant is Single quotation marks Caused by the A character , The string constant is Double quotes Caused by the 0 One or more characters
  • The character constant is equivalent to a integer ( ASCII value ), Can participate Expression operation ; The string constant represents a Address values ( The string is stored in memory )
  • Character constants only take up 2 Bytes ; String constant takes several bytes
     Insert picture description here

2. Variable length parameters

from Java5 Start ,Java Support the definition of variable length parameters , The so-called variable length parameter is a parameter that allows an indefinite length to be passed in when calling a method . Accept 0 One or more parameters .

public static void method2(String arg1, String... args) {

//......
}

3. notes

  • Single-line comments
  • Multiline comment
  • Documentation Comments

4. What's the difference between an identifier and a keyword ?

Simply speaking , An identifier is a name . But there are some identifiers ,Java Language has given it a special meaning , It can only be used in certain places , This special identifier is a keyword .
A keyword is an identifier given a special meaning .
【Java Common keywords in 】
 Insert picture description here

5. Auto increment and auto decrement operator

The symbol is preceded by / reduce , The symbol is followed by / reduce

6. continue、break and return What's the difference ?

  • continue : Jump out of the current cycle , So let's go to the next loop .
  • break : Jump out of the loop , Continue to execute the statement below the loop .
  • return : Used to jump out of the way , End the operation of the method .
    return; : Use it directly return End method execution , For methods that have no return value functions
    return value; :return A specific value , Methods for functions with return values

Method

1. Why static methods cannot call non static members

This needs to be combined with JVM Knowledge about , The main reasons are as follows :

  • Static methods belong to classes , Memory is allocated when the class is loaded , It can be accessed directly through the class name . and Non static members belong to instance objects , Only after the object is instantiated , You need to access... Through the instance object of the class .
  • Static members exist when non static members of a class do not exist , Call a non static member that does not exist in memory , It's illegal .

2. How is the static method different from the instance method ?

  • Call mode : When a static method is called externally , have access to Class name . Method name The way , You can also use object . Method name The way , And the instance method only has the latter way . in other words , You can call static methods without creating objects . however , It should be noted that... Is generally not recommended object . Method name To call static methods . This approach is very confusing , Static methods do not belong to an object of a class, but to this class . therefore , It is generally recommended to use Class name . Method name To call static methods .
  • Whether there are restrictions on accessing class members Static methods when accessing members of this class , Only static members are allowed ( Static member variables and static methods ), Access to instance members is not allowed ( Instance member variables and instance methods ), and Instance methods do not have this limitation .

3. The difference between overloading and rewriting

heavy load It's the same method that can be used according to different input data , Make a different deal . Occurs in the same class ( Or between a parent class and a child class ), Method name must be the same , Different parameter types 、 The number is different. 、 Different order , Method return values and access modifiers can be different . Sum up : Overloading means that multiple methods with the same name in the same class perform different logical processing according to different parameters .
rewrite That is, when the subclass inherits the same method from the parent class , The input data is the same , But to make a response different from the parent class , You're going to override the parent method . Rewriting occurs at run time , Is a subclass to the parent class to allow access to the method of the implementation process to be rewritten . Sum up : Rewriting is a modification of the parent method by a subclass , The external appearance cannot be changed , Internal logic can change .
 Insert picture description here

Generic

1. Java Do you understand generics ? What is type erasure ? Introduce the commonly used wildcards ?

Java Generic (generics) yes JDK 5 A new feature introduced in , Generics provide Compile time type safety detection mechanism , This mechanism allows programmers to detect illegal types at compile time . The essence of generics is parameterized type , in other words The data type being manipulated is specified as a parameter .
Java The generics of are Pseudo generics , This is because Java During operation , All generic information is erased , This is what is commonly said Type Erasure .

List<Integer> list = new ArrayList<>();
list.add(12);
list.add("a"); // If you add it directly here, you will report an error 
Class<? extends List> clazz = list.getClass();
Method add = clazz.getDeclaredMethod("add", Object.class);
// But it is possible to add through reflection 
// This means that all generic information will be erased during runtime 
add.invoke(list, "kl");
System.out.println(list);

Generics are generally used in three ways : Generic classes Generic interface Generic methods .

  • Generic classes
// here T It can be written as any logo , The common ones are T、E、K、V Parameters of the same form are often used to represent generics 
// When instantiating generic classes , Must specify T Specific types of 
public class Generic<T> {

private T key;
public Generic(T key) {

this.key = key;
}
public T getKey() {

return key;
}
}

Instantiate generic classes :

Generic<Integer> genericInteger = new Generic<Integer>(123456);
  • Generic interface
public interface Generator<T> {

public T method();
}

Implement generic interface , Do not specify type :

class GeneratorImpl<T> implements Generator<T>{

@Override
public T method() {

return null;
}
}

Implement generic interface , Specify the type :

class GeneratorImpl implements Generator<String>{

@Override
public String method() {

return "hello";
}
}
  • Generic methods
public static <E> void printArray(E[] inputArray) {

for (E element : inputArray) {

System.out.printf("%s ", element);
}
System.out.println();
}

Use :

// Create different types of arrays : Integer, Double and Character
Integer[] intArray = {
 1, 2, 3 };
String[] stringArray = {
 "Hello", "World" };
printArray(intArray);
printArray(stringArray);

Common wildcards :T 、E、K、V、?

  • ? To express uncertainty Java type
  • T(type) To represent a specific Java type
  • K V(key value) The sub table represents Java Of key values Key Value
  • E(element) representative Element

2. Where do you use generics in your project ?

  • Can be used to define common return results CommonResult<T> Through parameters T The data type of the result can be specified dynamically according to the specific return type
  • Used to build collection tool classes . Reference resources Collections Medium sort, binarySearch Method

== and equals() The difference between

== For basic types and reference types, the effect is different :

  • For basic data types ,== Compare values .
  • For reference data types ,== Compare the memory address of the object .

because Java Only Value passed , therefore , about == Come on , Regardless of the basic data type , Or variables that reference data types , The essence of comparison is value , It's just The value stored in the reference type variable is the address of the object .

equals() Functions cannot be used to determine variables of basic data types , It can only be used to judge whether two objects are equal .
Object class equals() Method :

public boolean equals(Object obj) {

return (this == obj);
}

hashCode() And equals()

hashCode() Introduce
hashCode() To get hash code (int Integers ), Also known as Hash code . The function of this hash code is Determines the index position of the object in the hash table .Object Of hashCode() Methods are local methods , This method is usually used to Convert the memory address of the object to an integer and return .
Hash table stores key value pairs (key-value), It is characterized by : According to “ key ” Quickly retrieve the corresponding “ value ”. So hash code is used !

Why would there be hashCode?

With HashSet For example :
When you add objects HashSet when ,HashSet Meeting First calculate the value of the object hashcode Value to determine where the object is added , At the same time With other objects that have been added hashcode Comparison of values , If there is no match hashcode,HashSet It assumes that the object does not recur . But if Found the same hashcode Value object , This will call equals() Methods to check hashcode Are equal objects really the same . If The two are the same ,HashSet It won't make the join operation successful . If Different words , It will be re hashed to other locations . In this way, we will greatly reduce equals The number of times , Accordingly, the execution speed is greatly improved .

Why rewrite equals() Must rewrite hashCode() Method ?
hashCode() The default behavior for is Generate unique values for objects on the heap . If you don't rewrite it hashCode(), Then class The two objects of cannot be equal in any way .
If equals Method to judge that two objects are equal , The of these two objects hashCode The values should also be equal .
Why do two objects have the same hashcode value , And they don't have to be equal ? because hashCode() What is used The hash algorithm may just make multiple objects return the same hash value . The worse the hash algorithm, the easier it is to collide , But it also has to do with the characteristics of data range distribution ( Collision means that different objects get the same hashCode ).“ Two different key value pairs , Hash values are equal ”, This is hash conflict .
I just mentioned HashSet, If HashSet In contrast , alike hashcode There are multiple objects , It will use equals() To see if it's really the same . in other words hashcode Just to reduce the search cost .

because HashSet Whether the objects are the same is judged according to their hashCode() Value comparison , and equals() The default comparison is also hashCode(). When we don't rewrite anything , The object created by default corresponds to hashCode Values are inconsistent ; But when we rewrite equeals() when , That means we want to change the way we judge whether objects are equal , So we need to rewrite hashCode(), To ensure that the object judgment method is the effect we want .

Basic data type

1. Java What are the basic data types in ? How many bytes do they occupy ? What is the corresponding packaging type ?

Java There is 8 Basic data types , Respectively :

  • 6 Number types :byteshortintlongfloatdouble
  • 1 Types of characters :char
  • 1 Species Boolean :boolean.
     Insert picture description here
    These eight basic types have corresponding Packaging Respectively :ByteShortIntegerLongFloatDoubleCharacterBoolean .
    If the packing type is not assigned, it means Null , The base type has a default value and is not Null.
    Basic data type Store directly in Java virtual machine Local variable table in stack in , and Packaging type Belongs to the object type , We know Object instances exist in the heap . Compared to object types , Basic data types take up very little space .

Local variable table :
The local variable table mainly stores the basic data types known at compile time (boolean、byte、char、short、int、float、long、double)、 Object reference (reference type , It's different from the object itself , May be a reference pointer to the starting address of the object , It can also be a handle to a representative object or other location related to the object ).

2. Do you know the constant pool technology of packaging type ?

Java Most of the basic types of wrapper classes implement constant pool technology .
Byte,Short,Integer,Long this 4 The wrapper class creates a value by default [-128,127] The corresponding type of cached data ,Character Created values in [0,127] Range cache data ,Boolean Go straight back to True or False.
give an example Integer Cache source code :

public static Integer valueOf(int i) {

if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
private static class IntegerCache {

static final int low = -128;
static final int high;
static {

// high value may be configured by property
int h = 127;
}
}

 Insert picture description here
Comparison of values between all integer wrapper class objects , All use equals Methods to compare .
 Insert picture description here

3. Automatic packing and unpacking understand ? What is the principle ?

What is an automatic box ?

  • Packing : Wrap basic types with their corresponding reference types ;
  • Unpacking : Convert wrapper type to base data type ;
Integer i = 10; // Packing 
int n = i; // Unpacking 

From bytecode , We found that Packing It's actually called The wrapper class valueOf() Method , Unpacking It's actually called xxxValue() Method .
 Insert picture description here
Be careful : If the box is disassembled frequently , It will also seriously affect the performance of the system . We should try to avoid unnecessary disassembly and assembly of the box .

copyright:author[Bald bald bald bald],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130707591598.html