The data type

Basic types of

Byte /8, char/16, short/16, int/32, float/32, long/64, double/64, Boolean /~

Boolean has only two values: true and false. It can be stored as 1 bit, but the size is not specified. The JVM converts Boolean data to int at compile time, using 1 for true and 0 for false. The JVM supports Boolean arrays, but does so by reading and writing byte arrays.

Packing type

Each basic type has a corresponding package type, and the assignment between the basic type and its corresponding package type is done by automatic packing and unpacking.

Integer s = 10;   Integer.valueof (10)

 int t = x;         // 拆箱 调⽤用了了 X.intValue()
Copy the code

Three major features of Java object-oriented programming: encapsulation inheritance polymorphism

encapsulation

Encapsulation privatized the properties of an object while providing 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 to access them. But if a class has no methods to access from the outside world, then that class is meaningless.

inheritance

Inheritance is the technique of using the definition of an existing class as a basis to create 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 can not selectively inherit the parent class. Using inheritance makes it very easy to reuse old code.

Here are three things to remember about inheritance:

  1. A subclass owns all the attributes and methods of the parent object (including private attributes and methods), but the private attributes and methods of the parent object are not accessible to the subclass.
  2. Subclasses can have their own attributes and methods, that is, they can extend their parent class.
  3. Subclasses can implement the methods of their parent class in their own way. (More on that later).

polymorphism

So-called polymorphism is refers to the procedures defined in the reference variable is pointing to the specific type and referenced by the variable from method calls are not sure when programming, but during the program is run to determine, that is, a reference variable will point to which class instance of the object, the reference variable from method calls the method to realize exactly is which class, It must be decided during the running of the program.

Polymorphism can be implemented in Java in two forms: inheritance (overwriting the same method by multiple subclasses) and interfaces (implementing the interface and overwriting the same method in the interface).

What is the difference between the JDK and the JRE? . What is bytecode? Why bytecode?

JVM

A Java Virtual machine (JVM) is a virtual machine that runs Java bytecode. The JVM has specific implementations for different systems (Windows, Linux, macOS) that aim to use the same bytecode, and they all give the same results.

What is bytecode? What are the benefits of adopting bytecode?

In Java, code that can be understood by the JVM is called bytecodes (files with a.class extension) that are not oriented to any particular processor, just to the virtual machine. Java solves the problem of low efficiency of traditional interpreted languages by means of bytecode to some extent, and at the same time retains the portability of interpreted languages. So Java programs run more efficiently, and because bytecode is not specific to a particular machine, Java programs can run on many different operating systems without recompiling.

Java programs from source to run generally have the following three steps:

We need to pay special attention to the.class-> machine code step. In this step, the JVM classloader loads the bytecode file and then executes it line by line through the interpreter, which is relatively slow. Also, some methods and blocks of code need to be called frequently (so-called hot code), so a JIT compiler was introduced later, and JIT is runtime compilation. When the JIT compiler completes the first compilation, it saves the machine code corresponding to the bytecode for direct use next time. And we know that machine code is certainly more efficient than Java interpreters. This explains why we often talk about Java as a compilation and interpretation language.

Summary: A Java Virtual machine (JVM) is a virtual machine that runs Java bytecode. The JVM has specific implementations for different systems (Windows, Linux, macOS) that aim to use the same bytecode, and they all give the same results. Bytecode and JVM implementations for different systems are key to the Java language’s “compile once, run anywhere” approach.

The JDK and JRE

The JDK is the Java Development Kit, which is a full-featured Java SDK. It has everything the JRE has, as well as a compiler (Javac) and tools (such as Javadoc and JDB). It can create and compile programs.

JRE is the Java runtime environment. It is the collection of everything you need to run a compiled Java program, including the Java Virtual Machine (JVM), Java class libraries, Java commands, and other basic artifacts. However, it cannot be used to create new programs.

If you just want to run a Java program, you just need to install the JRE. If you need to do some Java programming, you’ll need to install the JDK. However, this is not absolute. Sometimes, even if you don’t plan on doing any Java development on your computer, you still need to install the JDK. For example, if you deploy a Web application using JSPS, you are technically just running Java programs in the application server. So why do you need the JDK? Because the application server converts JSPS into Java servlets, you need to use JDK to compile the servlets.

The difference between Java and C++?

I know many people have never learned C++, but the interviewer likes to compare Java with C++. No way!! Even if you haven’t learned C++, write it down!

  • Both are object-oriented languages that support encapsulation, inheritance, and polymorphism;
  • Java does not provide Pointers to access memory directly, making program memory more secure;
  • Java classes are single inheritance, C++ supports multiple inheritance; Although Java classes cannot be multiinherited, interfaces can be;
  • Java has automatic memory management mechanisms that do not require programmers to manually free unwanted memory

What’s the difference between overloading and overwriting? Can the Constructor be override?

  • Overloading: Occurs in the same class, the method name must be the same, the parameter type must be different, the number of arguments must be different, and the method return value and access modifier can be different. This occurs at compile time.
  • Overwrite: occurs in the parent class, the method name, parameter list must be the same, the return value range is less than or equal to the parent class, the exception range is less than or equal to the parent class, access modifier range is greater than or equal to the parent class; If the superclass method access modifier is private, the subclass cannot override the method

String

An overview of

String is declared final, so it cannot be inherited. (Wrapper classes such as Integer are not inherited either.) In Java 8, strings use char arrays internally to store data.

After Java 9, implementations of the String class switched to byte arrays to store strings, and used the coder to identify which encoding was used.

The value array is declared final, which means that once the value array is initialized, it cannot reference any other array. And there’s no way to change the value array inside a String, so it’s guaranteed to be immutable.

What are the benefits of String immutable?

1. You can cache hash values because String hash values are often used. For example, String is used as the key of a HashMap. Immutable properties make hash values immutable, so only one evaluation is required.

2.String Pool requirements. If a String object has already been created, the reference will be fetched from the String Pool. String Pool can only be used if String is immutable.

3. Security String is often used as a parameter, String immutability, can ensure that the parameter is immutable. For example, if String is mutable as a network connection parameter, then during the network connection, String is changed, and the party that changed String thinks it is connected to another host, which is not necessarily the case.

4. Thread-safe String immutability is inherently thread-safe and can be used safely across multiple threads.

String str=”abcd”withString str1=new String(“abcd”) same? Is STR equal to str1?

There is a difference between these two different creation methods.

– The first method is to check for “abcd” in the string constant pool. If not, create one. Then STR points to an object in the string constant pool.

– Two ways are to create a new object directly in the heap memory space. The first method is recommended for creating strings.

STR and STR1 are different because one is a String in the heap and the other is a String in the constant pool.

What is the difference between Sring StringBuffer and StringBuilder? Why is String immutable?

In simple terms: The String class uses the final keyword to modify character arrays to hold strings, and the private final char value[], so strings are immutable.

AbstractStringBuilder and StringBuffer both inherit from AbstractStringBuilder classes, AbstractStringBuilder also uses an array of characters to hold the string char[]value but does not use the final keyword, so both objects are mutable.

Thread safety

Objects in strings are immutable, which means they are considered constants, thread-safe. AbstractStringBuilder AbstractStringBuilder is a common parent of StringBuilder and StringBuffer. AbstractStringBuilder defines some basic string operations, such as expandCapacity, Append, insert, indexOf and other public methods. StringBuffer places synchronization locks on methods or on invoked methods, so it is thread-safe. StringBuilder does not lock methods synchronously-so it is not thread-safe.

performance

Each time a String type is changed, a new String is generated and a pointer is pointed to the new String. A StringBuffer operates on the StringBuffer object itself each time, rather than generating new objects and changing object references. Using StringBuilder in the same situation yields only 10% to 15% performance improvement over using StringBuffer, but at the risk of multithreading insecurity.

Summary of the use of the three:

  1. Manipulation of small amounts of data: applicableString
  2. Single thread manipulation of large amounts of data in string buffers: applicableStringBuilder
  3. Multithreaded operation word

What is the difference between interfaces and abstract classes? Must abstract classes have abstract methods? Can abstract classes use final decoration?

What is the difference between interfaces and abstract classes?

  1. Methods on interfaces are public by default, all methods cannot have implementations in interfaces (Java 8 begins with interface methods having default implementations), and abstract classes can have non-abstract methods.
  2. Instance variables in interfaces are final by default, but not necessarily in abstract classes.
  3. A class can implement multiple interfaces, but only one abstract class at most.
  4. A class that implements an interface must implement all the methods of the interface, not necessarily an abstract class.
  5. Interfaces cannot be instantiated with new, but can be declared, but must reference an object that implements the interface. From the design level, abstraction is the abstraction of class, is a kind of template design, and interface is the abstraction of behavior, is a kind of behavior specification.

Note: In JDK8, interfaces can also define static methods that can be called directly with the interface name. Implementation classes and implementations are not callable. If two interfaces define the same default method, they must be overridden, or an error will be reported.

Must abstract classes have abstract methods?

Abstract classes do not necessarily contain abstract methods, but classes that contain abstract methods must be declared as abstract classes.

Can abstract classes use final decoration?

Abstract classes cannot be modified with final. When you modify a class with final, it indicates that the class cannot be inherited. All member methods ina final class are implicitly specified as final methods, which clearly defeats the purpose of abstract classes.

What is the reflex mechanism? What are the application scenarios of reflection mechanism?

Introduction to reflection Mechanism

The JAVA reflection mechanism allows you 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 ability to dynamically retrieve information and invoke methods on objects is called the Reflection mechanism of the Java language.

Static and dynamic compilation

  • Static compilation: Determine the type and bind the object at compile time
  • Dynamic compilation: Determine the type and bind the object at run time

Pros and cons of reflection

  • Advantages: Runtime type judgment, dynamic loading classes, improve code flexibility.
  • Disadvantages: Performance bottleneck: Reflection is equivalent to a series of interpreted operations telling the JVM what to do, and performance is much slower than direct Java code.

Reflection application scenarios

Reflection is the soul of frame design. In our daily project development process, reflection mechanism is rarely used directly, but this does not mean that reflection mechanism is useless, in fact, there are a lot of design and development related to reflection mechanism, such as modular development, through reflection to call the corresponding bytecode; Reflection is also used in dynamic proxy design patterns, as well as in frameworks like Spring/Hibernate that we use every day.

For example: ① We use class.forname () to load the driver of the database by reflection when connecting to the database using JDBC; ② The Spring framework also uses many reflection mechanisms, the most classic of which is the CONFIGURATION schema of XML. Spring loads beans through XML configuration schema: 1) Loads all XML or Properties configuration files in the program into memory; 2) The Java class parses the content in XML or Properties to get the bytecode string and related attribute information of the corresponding entity class; 3) Use reflection to get an instance of a Class based on this string; 4) Dynamically configure instance properties

How many IO streams are there in Java? What’s the difference between BIO,NIO and AIO?

How many IO streams are there in Java?

  • According to the flow direction, it can be divided into input flow and output flow.
  • According to operation unit, it can be divided into byte stream and character stream.
  • Flows are divided into node flows and processing flows according to their roles.

The Java I/O stream consists of more than 40 classes that look clutter-like but are actually very regular and closely related to each other. The Java I0 stream’s more than 40 classes are derived from the following four abstract base classes.

  • InputStream/Reader: The base class for all input streams, which are byte input streams and character input streams.
  • OutputStream/Writer: Base class for all output streams, byte output streams and character output streams.

Classification structure drawing according to operation mode:

Structure diagram by operation object

What’s the difference between BIO,NIO and AIO?

  • BIO (Blocking I/O): Synchronous Blocking in I/O mode, data reads and writes must be blocked in a thread waiting for it to complete. In the case that the number of active connections is not particularly high (less than 1000 for a single machine), this model is relatively good, allowing each connection to focus on its OWN I/O and simple programming model, without too much consideration of system overload, current limiting and other problems. The thread pool itself is a natural funnel to buffer connections or requests that the system can’t handle. However, when faced with hundreds of thousands or even millions of connections, the traditional BIO model is powerless. Therefore, we need a more efficient I/O processing model to handle the higher concurrency.
  • NIO (New I/O):NIO is a synchronous non-blocking I/O model. The NIO framework was introduced in Java 1.4, corresponding to the Java.niO package, which provides abstractions such as channels, selectors, and buffers. N in NIO can be interpreted as non-blocking, not just New. It supports buffer-oriented, channel-based approaches to I/O operations. NIO provides a comparison with the traditional BIO modelSocketServerSocketThe correspondingSocketChannelServerSocketChannelTwo different socket channel implementations, both of which support blocking and non-blocking modes. Blocking mode, like traditional support, is relatively simple, but has poor performance and reliability. Non-blocking mode is the opposite. For low-load, low-concurrency applications, synchronous blocking I/O can be used for faster development and better maintenance; For high-load, 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 introduced in Java 7, is an asynchronous, non-blocking IO model. Asynchronous IO is implemented based on events and callbacks, meaning that an action is applied and returned, not blocked, and when the background processing is complete, the operating system notifies the appropriate thread to proceed with the subsequent action. AIO is short for asynchronous IO. Although NIO provides a non-blocking method for network operations, NIO’s I/O 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, which is synchronous. Looking around the Internet, I found that AIO is not widely used so far, and Netty tried and abandoned AIO before.