[Interview] Java Basics (1)

0. Question outline

One, Java basics

1.1 Java Concept Principle

1、谈谈你对Java平台的理解?【第1讲】
 - 追问1:面向过程和面向对象有什么区别?
 - 追问2:Java中为什么要写None Static Method(非静态方法/实例化方法)?
 - 追问3:Java和Python的区别
 - 追问4:Java 高级特性?
 - 追问5:“Java 是解释执行”,这个说法正确吗?

2、动态代理是基于什么原理?【第6讲】(运行时自省,获取类声明属性和方法)

3、Java为什么不能多继承?
 - 追问1:如何实现多继承?

4、谈谈接口和抽象类有什么区别?【第13讲】(*35、什么是内部类,什么是匿名内部类?

6、重写和重载的区别。(*2- 追问1:多态含义?

7、Exception和Error有什么区别?【第2讲】:Throwable类;可预料VS不可恢复;可检查+不可检查
 - 追问1:你了解哪些 Error、Exception 或者 RuntimeException?
 - 追问2:NoClassDefFoundError 和 ClassNotFoundException 有什么区别?
 - 追问3:异常处理有哪些原则?

8、谈谈finalfinally、 finalize有什么不同?【第3讲】(*2- 追问1final与immutable相同吗?

9、String、StringBuffer、StringBuilder有什么区别?【第5讲】(*3)不可变,中间对象;线程安全;非线程安全
 - 追问1:String是基本数据类型吗?

10int和Integer有什么区别?【第7讲】(*2):包,自动装箱拆箱、值缓存,较小数值范围

11、谈谈你知道的设计模式(*2)?【第14讲】
 - 追问1:最常用哪种设计模式?
 - 追问2:单例模式是什么,请手动实现(*3- 追问3:Spring 等框架中使用了哪些模式?动态代理实现原理?

One, Java basics

1.1 Java Concept Principle

1. Talk about your understanding of the Java platform? [Lecture 1]

answer:

  • 1. Compared with C language, Java is object-oriented and has GC (garbage collection), so you don't need to care about memory allocation and recovery;
  • 2. JVM (cross-platform), JRE (Java Basic Operating Environment), JDK (Java Development Kit)
    1)JVM + 【Java类库、某些模块等】= JRE
    2)JRE + 【编译器、诊断等工具】 = JDK

1

  • 3. Expand
    1
    ...
Follow-up 1: What is the difference between process-oriented and object-oriented?
angle Process-oriented Object-oriented
Features Solve the problem step by step, organize the code in a method Solve problems with categories and organize codes with categories.
advantage Good performance Engineering is more modular, achieving lower coupling and high cohesion
Disadvantage Poor adaptability, poor scalability and maintainability Class calls need to be instantiated, which is expensive
feature step Encapsulation, inheritance, polymorphism

Relationship: The details are solved by process-oriented, and the overall object-oriented control is complementary to each other.

Follow-up 2: Why write None Static Method in Java?

A: The static method permanent memory, defined too resource-intensive, may cause an overflow, and non-static methods as instance of an object disappear after being recovered, while the code will not be shared, thread-safe .

  • supplement:
angle Static Method Non Static Method
life cycle Like static class members, loaded into memory will stay resident until the JVM is closed Memory is allocated after instantiation and must be referenced by class instance. When the instance object is reclaimed by the JVM, it disappears.
Memory location The static method and the static variable use the same block of memory after creation, continuous There are multiple places in the memory, discrete
effectiveness high low
Thread safe Static methods (variables) share code (data) segments, which have concurrency problems For certain objects, no problem
Follow-up 3: The difference between Java and Python
angle Java Python
Types of Static type, flexible to achieve runtime modification Full dynamic
grammar Object-oriented Combining functional programming and object-oriented
Development cycle slow Rich library, fast
effectiveness Stable performance and good scalability Poor
field Server, Web, Android Script processing, AI, graphics and images
Follow-up 4: Java advanced features?
  • 1) Generic: Parameterized type, that is, the data type becomes a variable parameter.

  • 2) reflector: The obtained object (class, properties, methods) the name of the technique.
    Such as:可通过类名-->生成类实例;方法名-->调用方法;属性名-->访问属性值。

  • 3) Annotation: Tag the Java code to explain its function.
    Such as: read the code, check the format, reduce configuration, and reduce duplication. It can be detected at compile time, or it can be reflected at runtime

Follow-up question 5: "Java is interpretation and execution", is this statement correct?

Answer: Not very accurate. Java source code is first compiled into bytecode by Javac. At runtime, the interpreter embedded in the JVM converts the bytecode into the final machine code.

However, common JVMs (such as Hotspot JVM) provide a JIT (Just-In-Time) compiler, that is, a dynamic compiler, which can compile hot code into machine code at runtime . In this case, part of the hot code is compiled and executed. , Instead of explaining the execution.

2. What is the principle of dynamic agency? [Lecture 6] (Run-time introspection, access to class declaration properties and methods)

Answer: Reflection gives the program the ability to introspect at runtime. It can directly manipulate classes or objects, for example 获取类定义、属性和方法, you can even modify class definitions at runtime.

Dynamic proxy is a mechanism for dynamically constructing proxy and processing proxy method calls at runtime. Scenarios using similar mechanisms include RPC calls and AOP.

In terms of implementation, the JDK itself uses the reflection mechanism, and other bytecode manipulation mechanisms with higher performance, similar to ASM, cglib (based on ASM), Javassist, etc.

3. Why can't Java have multiple inheritance?

Answer: Multiple inheritance means that a class inherits behaviors and characteristics from more than its parent class at the same time. Which class of method does the X method in the figure inherit? Easy to cause accidents.
1

Follow-up 1: How to implement multiple inheritance?

Answer: Interface or inner class.

4. What is the difference between an interface and an abstract class? [Lecture 13] (*3)

  • 1) An interface is an abstraction of behavior and a collection of abstract methods. Interfaces can be used to achieve the separation of API definition and implementation.
  • 2) An abstract class is a class that cannot be instantiated, and is the same in form as a general class, mainly for code reuse . Many common parts (method implementation or member variables) in the Java standard library (such as the collection framework) are extracted into abstract classes.
接口说明:
1. 不能实例化,不能包含任何非常量成员,任何field都隐含public static final2. 没有非静态方法实现,只能是抽象或静态方法。接口举例:java.util.List[Java标准库]

// 实现interface用implements关键词,继承abstract class用extends关键词。
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    
    
//...
}

5. What is an inner class and what is an anonymous inner class?

  • 1) Inner class : Put the definition of one class inside the definition of another class. The inner class inherits from a certain class or implements a certain interface, and manipulates the objects of the outer class.
  • 2) Anonymous inner class : an inner class without a name. Can only be used once (because there is no name), it is often used to simplify code writing,
  • 3) Prerequisite for the use of anonymous classes : must inherit a parent class or implement an interface.
    5

6. The difference between rewriting and reloading. (*2)

1) Meaning

  • Rewrite: The subclass reimplements the method of the parent class. That is, the shell remains unchanged and the core is rewritten .
  • Overloading: Each overloaded method (or constructor) must have a unique list of parameter types .
    2

2) Comparison

Difference Rewrite Overload
parameter list Must not be modified Must be modified
Return type Must not be modified Can be modified
abnormal Can be reduced or deleted, and must not throw new or broader exceptions Can be modified
access Strict restrictions must not be made, restrictions can be lowered Can be modified
Types of Dynamic binding, determined at runtime Static allocation, determined when the class is loaded
Follow-up 1: What does polymorphism mean?
  • 1) Meaning & Function
    Polymorphism means that the same behavior (interface, message) can take many different behaviors according to different objects. It can eliminate the coupling between types and has good scalability.

7

  • 2) Implementation methods & necessary conditions
    Implementation methods: rewrite, interface (socket), abstract class and abstract method.
    Three necessary conditions: inheritance, rewrite, parent class reference points to subclass pair [ Parent p = new Child();]
// 例1:
package objectandclass;  
	class A {
    
        
		public void show(D obj){
    
        
			System.out.println("A and D");  
		}     
		public void show(A obj){
    
        
	    	System.out.println ("A and A");    
		}     
	}     
	class B extends A{
    
        
		public void show(B obj){
    
        
			System.out.println("B and B");    
		}    
		public void show(A obj){
    
        
			System.out.println("B and A");    
		}     
	}    
	class C extends B{
    
    }     
	class D extends B{
    
    }    
}

... {
    
     
	A a1 = new A();    
	A a2 = new B();    
	B b = new B();    
	C c = new C();     
	D d = new D();     
	a1.show(b);  // A and A
	a1.show(c);  // A and A
	a1.show(d);  // A and D
	a2.show(b);  // B and A
	a2.show(c);  // B and A
	a2.show(d);  // A and D
	b.show(b);   // B and B
	b.show(c);   // B and B
	b.show(d);   // A and D
}

7. What is the difference between Exception and Error? [Lecture 2]: Throwable class; predictable VS unrecoverable; checkable + uncheckable

1) Same

  • Both Exception and Error inherit the Throwable class, and only Throwable instances can be thrown (throw) or caught (catch).
    9

2) Explanation

  • Exception is a predictable unexpected situation, which may and should be caught and handled;
  • Error is a normal and unlikely situation, most of which will cause the program (such as JVM) to be in an unrecoverable abnormal state, which is inconvenient and does not need to be caught.

3) Exception classification :

  • Exception divided can not abnormalities and abnormalities , abnormalities can be treated explicitly in the source code, which is part of the compiler checks; no abnormalities (NullXXX, ArrayIndexOutofBoundsXXX), are generally logical errors can be avoided, Capture as needed.
Follow-up 1: What Error, Exception or RuntimeException do you know?

……

Follow-up 2: What is the difference between NoClassDefFoundError and ClassNotFoundException?

NoClassDefFoundError is an error, and ClassNOtFoundException is an exception.

  • 1) NoClassDefFoundError : exists at compile time, and the class definition cannot be found when the JVM or ClassLoader instance is loaded (normal call or new object), then NoClassDefFoundError will be thrown at this time;
  • 2) ClassNotFoundException : The dynamically loaded class is not found in the classpath, and ClassNotFoundException will be thrown at this time.
Follow-up 3: What are the principles of exception handling?

1) Catch specific exceptions. Try not to catch general exceptions, such as Exception. [Basic]
2) Don't swallow abnormally. This can lead to weird situations that are difficult to diagnose. [Basic]
3) Throw early, catch late principle.

补充:
1. 不捕获某些异常。如RuntimeException 被扩散出来,而不是被捕获。除非深思熟虑,否则不要捕获 Throwable 或者 Error,这样很难保证我们能够正确程序处理 OutOfMemoryError。
2. 分布式系统最好使用产品日志,详细地输出到日志系统里,printStackTrace()无法找到堆栈轨迹(stacktrace)。

8. Talk about the difference between final, finally, and finalize? [Lecture 3] (*2)

  • 1) Final can modify the class/variable/method, which means that it cannot be inherited/modified/overwritten ;
  • 2) A mechanism to finally ensure that the key code must be executed . 如try-catch-finally关闭JDBC连接、unlock锁
  • 3) finalize in order to ensure that the object completes the collection of specific resources before garbage collection. JDK 9 is marked deprecated.
Follow-up 1: Is final and immutable the same?

Answer: No, it only guarantees that the object reference cannot be assigned, but the object behavior (such as adding) is not affected.

 final List<String> strList = new ArrayList<>();
 strList.add("Hello");
 strList.add("world");  
 List<String> unmodifiableStrList = List.of("hello", "world");  // List.of本身不可变
 unmodifiableStrList.add("again");  // 会抛出错误
 
说明:
final 只约束 strList 引用不可被赋值,但 strList 对象行为不被 final 影响,添加等操作正常。若希望对象本身不可变,需要相应类支持不可变行为。

9. What is the difference between String, StringBuffer and StringBuilder? [Lecture 5] (*3) Immutable, intermediate object; thread-safe; non-thread-safe

String providing configuration and management of basic logic string, typical Immutableclass. All classes and attributes are final, and actions such as splicing and cropping will generate new String objects.
StringBuffer is provided to reduce the intermediate target class, it can be used append/addto add a string, thread safe. StringBuilder is not thread-safe. Others are the same as StringBuffer. It is preferred in most cases.

Follow-up 1: Is String a basic data type?

Answer: No, String is a class.

  • supplement
  • 1) Integer: byte, short, int, long ( 分别是8、16、32、64位)
  • 2) Floating point: double, float
  • 3) Logic: boolean
  • 4) Text: char

10. What is the difference between int and Integer? [Lecture 7] (*2): Package, automatic packing and unpacking, value buffering, smaller value range

  • 1) int is one of Java 8 primitive data types.
  • 2) Integer is a packaging class of int . There are int fields to store data and provide basic operations such as calculations and conversions. In Java 5, auto-boxing and auto-unboxing are introduced (primitive type <= conversion => object); value caching (valueOf method) has brought significant performance improvements.
补充:
1、原始数据类型不是对象。
2、实践发现大部分数据操作都是集中在较小的有限范围,所以引入值缓存,范围:[-128-127]

11. Talk about the design patterns you know (*2)? [Lecture 14]

category Application goal example
Creation mode A summary of various problems and solutions in the object creation process Factory mode, singleton mode, builder mode, prototype mode
Structural model A summary of the software design structure, focusing on the practical experience of class, object inheritance, and combination methods Bridge mode, adapter mode, decorator mode, proxy mode, combination mode, appearance mode, flyweight mode
Behavioral model A model summarized from the perspective of interaction between classes or objects, division of responsibilities, etc. Strategy mode, interpreter mode, command mode, observer mode, iterator mode, template method mode, visitor mode

supplement:

Application Classification Chinese English
Creation mode Factory mode Factory、Abstract Factory
Singleton mode Singleton
Builder mode Builder
Prototype mode ProtoType
Structural model Bridge mode Bridge
Adapter mode) Adapter
Decorator pattern Decorator
Agency model Proxy
Combination mode Composite
Appearance mode Facade
Flyweight model Flyweight
Behavioral model Strategy mode Strategy
Interpreter mode Interpreter
Command mode Command
Observer mode Observer
Iterator mode Iterator
, Template method pattern Template Method
Visitor mode Visitor
  • Follow-up 1: Which design pattern is most commonly used?
    Answer: Singleton mode, factory method, abstract factory, strategy mode, observer mode, agent mode...

  • Follow-up 2: What is the singleton mode, please implement it manually (*3)
    ……

  • Follow-up 3: What patterns are used in frameworks such as Spring? The principle of dynamic proxy implementation?
    ...

Two, reference

1. Java basics: the difference between static methods and non-static methods
2. Introduction to advanced Java features-generics, reflection and annotations
3. Java improvement articles (9)-realization of multiple inheritance
4. Java 8 default methods and Multiple inheritance
5. The difference between Java rewriting and overloading
6. JAVA rewriting and overloading
7. Java rewriting (Override) and overloading (Overload)
8. An article to give you a thorough understanding of Java internal classes
9. Java internals The usage of classes and anonymous inner classes
10. Summary of anonymous inner classes in java
11. The difference between ClassNotFoundException and NoClassDefFoundError

Guess you like

Origin blog.csdn.net/HeavenDan/article/details/112608970