Java interview summary summary, including Java key knowledge, as well as common open source framework, welcome to read. The article may have wrong place, because individual knowledge is limited, welcome everybody big guy to point out! The article continues to be updated at……

ID The title address
1 Design Mode Interview Questions (Most comprehensive summary of interview questions) Juejin. Cn/post / 684490…
2 Java Basics (most comprehensive interview questions) Juejin. Cn/post / 684490…
3 Java Set interview Questions (the most comprehensive interview questions) Juejin. Cn/post / 684490…
4 JavaIO, BIO, NIO, AIO, Netty Interview Questions (Most comprehensive summary of interview questions) Juejin. Cn/post / 684490…
5 Java Concurrent Programming Interview questions (most comprehensive interview questions) Juejin. Cn/post / 684490…
6 Java Exception Interview Questions (The most comprehensive interview Questions) Juejin. Cn/post / 684490…
7 Java Virtual Machine (JVM) Interview Questions Juejin. Cn/post / 684490…
8 Spring Interview Questions (the most comprehensive interview questions) Juejin. Cn/post / 684490…
9 Spring MVC Interview Questions (The most comprehensive interview Questions) Juejin. Cn/post / 684490…
10 Spring Boot Interview Questions (Most comprehensive summary of interview questions) Juejin. Cn/post / 684490…
11 Spring Cloud Interview Questions (The most comprehensive interview questions) Juejin. Cn/post / 684490…
12 Redis Interview Questions (most comprehensive summary of interview questions) Juejin. Cn/post / 684490…
13 MyBatis Interview Questions (most comprehensive interview questions) Juejin. Cn/post / 684490…
14 MySQL Interview Questions (most comprehensive interview questions) Juejin. Cn/post / 684490…
15 TCP, UDP, Socket, HTTP interview questions Juejin. Cn/post / 684490…
16 Nginx Interview Questions (The most comprehensive interview Questions) Juejin. Cn/post / 684490…
17 ElasticSearch interview questions
18 Kafka interview questions
19 RabbitMQ interview questions (most comprehensive summary of interview questions) Juejin. Cn/post / 684490…
20 Dubbo Interview Questions (the most comprehensive interview questions) Juejin. Cn/post / 684490…
21 ZooKeeper Interview Questions Juejin. Cn/post / 684490…
22 Netty Interview Questions (Most comprehensive summary of interview questions)
23 Tomcat Interview Questions (The most comprehensive interview questions) Juejin. Cn/post / 684490…
24 Linux Interview Questions (Most comprehensive Summary of interview questions) Juejin. Cn/post / 684490…
25 Internet Related interview Questions (the most comprehensive summary of interview questions)
26 Internet Security Questions (Summary of the most comprehensive interview questions)

Java overview

What is a programming

  • Programming is to let the computer to solve a problem and use a programming language to write program code, and finally get the result of the process.

  • In order for the computer to understand the intention of man, man must tell the thought, method and means of the problem to be solved to the computer in a form that the computer can understand, so that the computer can work step by step according to the instructions of man and complete a specific task. This process of communication between humans and computers is called programming.

What is the Java

  • Java is an object-oriented programming language, not only absorb the advantages of C++ language, but also abandon C++ difficult to understand multiple inheritance, Pointers and other concepts, so Java language has powerful and easy to use two characteristics. As a representative of static object-oriented programming languages, Java language has implemented object-oriented theory well, allowing programmers to do complex programming in an elegant way of thinking.

Three major versions after jdk1.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 in desktop, server, embedded, and real-time environments. Java SE contains classes that support Java Web services development and provide the foundation for Java EE and Java ME.
  • Java EE (J2EE, Java 2 Platform Enterprise Edition, Enterprise Edition) Java EE was formerly known as J2EE. The Enterprise version helps develop and deploy portable, robust, scalable, and secure server-side Java applications. Java EE is built on Java SE and provides Web services, component models, management and communication apis that can be used to implement enterprise-level Service-oriented Architecture (SOA) and Web2.0 applications. In February 2018, Eclipse announced that it was officially changing the name of JavaEE to JakartaEE
  • 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 cell phones, PDAs, TV set-top boxes, and printers. Java ME includes a flexible user interface, a robust security model, a number of built-in network protocols, and rich support for both networked and offline applications that can be downloaded dynamically. Applications based on the Java ME specification can be written once for many devices and can take advantage of the native capabilities of each device.

3 Differences between Jdk and Jre and JVM

Look at the official picture of Java, Jdk includes Jre, Jre includes JVM

  • JDK: The JDK also includes some other things that help you compile Java code, as well as tools for monitoring the Jvm. The Java Development Kit is intended for Java developers, which includes the Java Development tools as well as the Jre. So with the JDK installed, there is no need to install the JRE separately. The development tools: compilation tool (javac.exe), packaging tool (jar.exe) and so on

  • JRE: Most of the JRE is written in C and C++. It is the basic class library required by Java compilation. The Java Runtime Environment includes the core class library required by Java virtual machines and Java programs. The core class library is mainly the java.lang package: it contains the essential system classes for running Java programs, such as basic data types, basic mathematical functions, string handling, threading, 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 the JRE on your computer.

  • Java Virtual Machine is a Java Virtual Machine. Java programs need to run on Virtual machines. Different platforms have their own Virtual machines, so the Java language can be implemented across platforms.

What is cross-platform? How does it work

  • Cross-platform means that programs written in the Java language can run on multiple system platforms once compiled.

  • 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 features of the Java language

  • Simple and easy to learn (the Syntax of the Java language is close to THAT of C and C++)

  • Object oriented (encapsulation, inheritance, polymorphism)

  • Platform independence (Java Virtual machine implementation platform independence)

  • Network programming support and convenience (the Java language itself was designed to simplify network programming)

  • Support for multithreading (a mechanism that allows applications to execute multiple tasks in parallel at the same time)

  • Robustness (Java language’s strong typing mechanism, exception handling, automatic garbage collection, etc.)

  • Good safety

What is bytecode? What are the biggest benefits of bytecode adoption

  • Bytecode: A file generated by Java source code compiled by the virtual machine compiler (that is, a file extended to.class) that is not oriented to any particular processor, but only to the virtual machine.

  • Advantages of using bytecode:

    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 machines without recompiling.

  • Take a look at compilers and interpreters in Java:

    Java introduced the concept of a virtual machine, a layer of abstraction between the machine and the compiler. This virtual machine provides a common interface for compilers on any platform. The compiler simply faces the virtual machine, generates code that the virtual machine understands, and then the interpreter translates the virtual machine code into system-specific machine code for execution. In Java, this code for virtual machine understanding is called bytecode (that is, files that extend to.class) and is not oriented to any particular processor, just to the virtual machine. The interpreter for each platform is different, but the virtual machine implemented is the same. After compiler to compile the Java source code into the bytecode, byte code execution is interpreted by a virtual machine, virtual machine will each to execute bytecode to interpreter, the interpreter translated into machine code on specific machines, and then run on a particular machine, this is the characteristics of the above mentioned Java compilation explanation and interpretation.

    Java source code — — — — — — — — > > compiler JVM executable Java bytecode (that is, the virtual instruction) — — — — — — — — > > JVM JVM interpreter — — — — — > machine executable binary machine code — — — — > program is running.

What is the main class of a Java program? What is the difference between the main class of an application and a applet?

  • A program can have more than one class, but only one class can be the main class. In A Java application, this main class is the class that contains the main() method. In Java applets, the main class is a subclass that descends from the system class JApplet or Applet. The main class of the application is not required to be public, but the main class of the applet must be public. The main class is the entry point for Java program execution.

What are the differences between a Java application and a small program?

  • Simply put, the application starts from the main thread (the main() method). Applets do not have a main method, but instead run embedded in a browser page (init() or run() is invoked), similar to flash mini-games.

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; program memory is more secure
  • Java classes are single inheritance, C++ supports multiple inheritance; Although Java classes cannot be multiinherited, interfaces can.
  • Java has automatic memory management mechanisms that do not require programmers to manually free unwanted memory

Oracle JDK vs. OpenJDK

  1. Oracle JDK versions will be released every three years, while OpenJDK versions will be released every three months;

  2. The OpenJDK is a reference model and is fully open source, whereas the Oracle JDK is an implementation of OpenJDK and is not fully open source;

  3. The Oracle JDK is more stable than the OpenJDK. The OpenJDK and Oracle JDK have nearly the same code, but the Oracle JDK has more classes and some bug fixes. Therefore, if you want to develop enterprise/business software, I recommend you choose the Oracle JDK because it is thoroughly tested and stable. In some cases, some people have mentioned that they may encounter many application crashes while using OpenJDK, but simply switch to the Oracle JDK to solve the problem;

  4. The Oracle JDK provides better performance than the OpenJDK in terms of responsiveness and JVM performance;

  5. The Oracle JDK does not provide long-term support for upcoming releases; users must update to the latest version each time to get support;

  6. The Oracle JDK is licensed under the binary code License, while the OpenJDK is licensed under the GPL V2 license.

Basic grammar

The data type

What data types are available in Java

Definition: The Java language is strongly typed. It defines specific data types for each type of data and allocates different sizes of memory space in memory.

classification

  • Basic data types
    • numeric
      • Integer types (byte,short,int,long)
      • Floating point type (float,double)
    • Character (char)
    • The Boolean (Boolean)
  • Reference data type
    • Class (class)
    • Interface (interface)
    • Array ([])

Java basic data type diagram

Whether the switch works on byte, whether it works on long, and whether it works on String

  • Before Java 5, in switch(expr), expr could only be byte, short, char, or int. Since Java5, enumeration types have been introduced in Java. Expr can also be enum types. Since Java 7, expr can also be strings, but long integers are not allowed in all current versions.

Let’s do 2 times 8 the most efficient way

  • 2 << 3 (moving three places to the left is the same as multiplying by two to the third, moving three places to the right is the same as dividing by two to the third).

Math.round(11.5) equals what? Math.round(-11.5) equals what

  • Math.round(11.5) returns 12 and math.round (-11.5) returns -11. Rounding works by adding 0.5 to a parameter and rounding it down.

Float f = 3.4; Whether it is right

  • Is not correct. 3.4 is a double. Assigning a double to a float is down casting and will result in a loss of precision. Therefore, a cast float f =(float)3.4 is required. Or float f = 3.4f; .

short s1 = 1; s1 = s1 + 1; Didn’t you? short s1 = 1; s1 += 1; Is wrong?

  • For short s1 = 1; s1 = s1 + 1; Since 1 is an int, s1+1 is also an int and requires a cast to assign to short.

  • Short s1 = 1; s1 += 1; It compiles correctly because s1+= 1; S1 = (short(s1 + 1); There is an implicit cast.

coding

What coding scheme does the Java language use? What are the characteristics?

  • The Java language uses the Unicode coding standard, Unicode (Standard code), which specifies a unique numeric value for each character, so it can be used safely in any language, platform, and program.

annotation

What Java annotations

Definition: Text used to explain a program

classification

  • Single-line comment format: // Comment text
  • Multi-line comment format: /* Comment text */
  • Document comment format: /** Comment text */

role

  • In the program, especially in the complex program, the annotation can increase the readability of the program, which is conducive to the modification, debugging and communication of the program. The contents of the comments are ignored during compilation, no object code is generated, and the comments have no effect on the results of program execution.

Note: Multiple lines and document comments cannot be nested.

Access modifier

Access modifier public, private, protected, and don’t write the difference (default)

  • Definition: In Java, access modifiers can be used to protect access to classes, variables, methods, and constructors. Java supports four different access permissions.

  • classification

    • Private: visible within the same class. Use objects: variables, methods. Note: You cannot decorate classes (external classes)

    • Default (that is, write nothing and use no keywords) : visible within the same package without any modifiers. Use objects: classes, interfaces, variables, methods.

    • Protected: Visible to classes and all subclasses within the same package. Use objects: variables, methods. Note: You cannot decorate classes (external classes).

    • Public: visible to all classes. Use objects: classes, interfaces, variables, methods

Access the modifier graph

The operator

The difference between & and &&

  • The & operator can be used in two ways :(1) bitwise and; (2) Logic and.

  • The && operator is the short-circuit and operation. The difference between logic and short-circuit and is huge, although both require booleans on the left and right sides of the operator to be true for the entire expression. Am& is called short-circuited because if the expression to the left of am& is false, the expression to the right will be short-circuited and will not be evaluated.

Note: the Boolean or operator (|) and short circuit or operator (| |) difference, too.

The keyword

Java has no Goto

  • Goto is a reserved word in Java that is not used in the current version of Java.

What is final for?

Used to modify classes, properties, and methods;

  • Classes modified by final may not be inherited
  • Methods decorated with final cannot be overridden
  • A variable that is modified by a final cannot be changed. It is the reference to the variable that is modified by a final, not the reference to the content, which can be changed

Final Finally Finalize difference

  • Final can modify classes, variables, and methods. A modifier class indicates that the class cannot be inherited, a modifier method indicates that the method cannot be overridden, and a modifier variable table indicates that the variable is a constant and cannot be reassigned.
  • Finally is usually used ina try-catch block. When handling an exception, the method finally is always executed, indicating that the block will be executed regardless of whether an exception occurs. It is used to store code that closes a resource.
  • Finalize is a method of Object class, which is the parent of all classes. This method is generally called by garbage collector, when we call System.gc(), finalize() is called by garbage collector to collect garbage. The final determination of whether an object is recyclable.

Usage of this keyword

  • This is an object of itself, representing the object itself.

  • The usage of this in Java can be roughly divided into three ways:

    • 1. As a normal direct reference, this refers to the current object itself.

    • 2. The members have the same name as each other.

      public Person(String name, int age) {
          this.name = name;
          this.age = age;
      }
      Copy the code
    • 3. Reference the constructor of this class

      class Person{
          private String name;
          private int age;
          
          public Person(a) {}public Person(String name) {
              this.name = name;
          }
          public Person(String name, int age) {
              this(name);
              this.age = age; }}Copy the code

Usage of the super keyword

  • Super can be understood as a pointer to the object of one’s superclass, which in turn refers to the nearest superclass.

  • Super can also be used in three ways:

    • 1. Plain direct quotes

      Like this, super is equivalent to a reference to the parent class of the current object, so you can use super.xxx to refer to the members of the parent class.

    • 2. If a member variable or method in a subclass has the same name as a member variable or method in a parent class, use super to distinguish it

      class Person{
          protected String name;
       
          public Person(String name) {
              this.name = name; }}class Student extends Person{
          private String name;
       
          public Student(String name, String name1) {
              super(name);
              this.name = name1;
          }
       
          public void getInfo(a){
              System.out.println(this.name);      //Child
              System.out.println(super.name);     //Father}}public class Test {
          public static void main(String[] args) {
             Student s1 = new Student("Father"."Child"); s1.getInfo(); }}Copy the code
    • 3. Reference the parent constructor

      • Super: calls one of the constructors in the parent class (should be the first statement in the constructor).
      • This (argument) : Calls another form of the constructor of this class (should be the first statement in the constructor).

The difference between this and super

  • Super: It refers to a member in the immediate parent of the current object (used to access the member data or functions in the hidden parent of the immediate parent, 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: This represents the name of the current object (this should be used to indicate the current object where ambiguity is possible in the program; If the function has the same name as the member of the class, use this to specify the member variable name.
  • Super () is similar to this(), except that super() calls the parent constructor in a subclass, while this() calls other constructors in its own class.
  • Both super() and this() need to be placed on the first line in the constructor.
  • Although you can call one constructor with this, you cannot call two.
  • This and super cannot be in the same constructor, because this must call other constructors, and other constructors must also have super statements, so having the same statement in the same constructor loses its meaning, and the compiler will not pass.
  • Both this() and super() refer to objects, so neither can be used in static environments. Static variable,static method,static statement block.
  • Essentially, this is a pointer to this object, whereas super is a Java keyword.

Is static

  • The main meaning of static is to create domain variables or methods that are independent of concrete objects. So that you can use properties and call methods without creating objects!

  • Another key use of the static keyword is to form static blocks of code to optimize program performance. Static blocks can be placed anywhere in a class, and there can be more than one static block in a class. When the class is first loaded, each static block is executed in the same order as the static block, and only once.

  • The static block can be used to optimize program performance because it is executed only once when the class is loaded. As a result, many times initialization operations that only need to be done once are placed in static code blocks.

Static is unique

  • 1. Static variables or methods are independent of any object of the class. That is, they do not belong to any instance object, but are shared by instance objects of the class.

What do you mean by “shared by instances of a class”? That is, a static member of a class that belongs to everyone. All class objects are shared, unlike member variables that are self-contained… I think I’ve made it very colloquial, you see?

  • When the class is first loaded, the static part is loaded and initialized only when the class is used for the first time.

  • Static variable values are allocated at class load time and are not reallocated when class objects are created. If you assign, you can assign anything!

  • 4. Static variables or methods take precedence over objects. That is, when a class is loaded, it can be accessed even if no object has been created.

Static Application Scenarios

  • Since static is shared by instance objects of the class, if a member variable is shared by all objects, it should be defined as a static variable.

  • Therefore, the most common static application scenarios are:

1, modify member variable 2, modify member method 3, static code block 4, modify class [can only modify inner class that is static inner class] 5, static guide package

Static Precautions

  • 1. Static access can only be static.
  • 2. Non-static can access both non-static and static.

Flow control statement

Break,continue,return

  • Break: no longer executes the loop (terminates the current loop body)

  • Continue Breaks out of the current loop and continues with the next loop (terminating the current loop and entering the next loop condition)

  • Return the program returns, not executing the following code (directly returning from the current method)

How do I get out of the current multiple nested loops in Java

  • In Java, you can break out of multiple loops by defining a label in front of the outer loop statement, and then breaking out of the outer loop by using a labeled break statement in the inner loop body code. Such as:

    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) {
                    breakok; }}}}Copy the code

object-oriented

Object-oriented Overview

The difference between object-oriented and procedural

  • Process-oriented:

    • Advantages: Higher performance than object-oriented, because class invocation needs to be instantiated, the overhead is relatively large, more consumption of resources; For example, SCM, embedded development, Linux/Unix and so on generally adopt process-oriented development, performance is the most important factor.

    • Disadvantages: No object-oriented easy maintenance, easy reuse, easy to expand

  • Object-oriented:

    • Advantages: easy to maintain, easy to reuse, easy to expand, because of the characteristics of object-oriented encapsulation, inheritance, polymorphism, can design a low coupling system, make the system more flexible, more easy to maintain

    • Disadvantages: Lower performance than process-oriented

Process-oriented is specific and process-oriented. To solve a problem, you need to analyze step by step and realize step by step.

Object orientation is modeled, you just abstract out a class, it's a closed box where you have the data and you have the solutions to the problem. Need what function to use directly can, do not have to go step by step to achieve, as for this function is how to achieve, what matter we care? We just need to know how to use it.

In fact, the bottom of the object-oriented is still oriented to the process, the process of abstraction into a class, and then encapsulated, convenient for us to use is oriented to the object.

Three characteristics of object orientation

What are the aspects of object-oriented characteristics

The characteristics of object-oriented mainly include the following aspects:

  • Abstract: Abstract is the process of constructing a class by summarizing the common characteristics of a class of objects, including data abstraction and behavior abstraction. Abstractions focus only on what properties and behaviors an object has, not on the details of those behaviors.

  • 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 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:

      • Subclasses have properties and methods that are not private from their parent class.

      • Subclasses can have their own attributes and methods, that is, they can extend their parent class.

      • Subclasses can implement the methods of their parent class in their own way. (More on that later).

  • Polymorphic: A reference variable of a parent class or interface definition can point to an instance object of a subclass or concrete implementation class. Improve the extensibility 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 polymorphic mechanism? How is polymorphism implemented in the Java language?

  • 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 STLL can point to which class instance 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. Because the program is running to identify a specific class, so, don’t need to modify the source code, can make reference variables bound to the different class implements, leading to the reference call specific methods change, namely do not modify the program code can change the program of the specific binding in the runtime code, let the program can select multiple running state, this is polymorphism.

  • Polymorphism is divided into compile-time polymorphism and run-time polymorphism. Among them, when editing polymorphism is static, mainly refers to the method overload, it is according to the different parameter list to distinguish different functions, after editing will become two different functions, not polymorphic at run time. While runtime polymorphism is dynamic, it is achieved through dynamic binding, which we call polymorphism.

Implementation of polymorphism

  • There are three necessary conditions for Java to implement polymorphism: inheritance, rewriting, and upward transition.

    • Inheritance: In polymorphism, there must be a subclass and a parent class that have an inheritance relationship.

    • Override: A subclass redefines methods in its parent class that are called when those methods are called.

    • Upward transition: In polymorphism, a reference to a subclass is assigned to a superclass object so that the reference has the ability to call methods of the parent class and methods of the subclass.

Only when the above three conditions are met, can we use the same logical implementation code in the same inheritance structure to handle different objects, thus achieving different behavior.

For Java, for its part, the implementation of polymorphic mechanism follows a principle: when the superclass object reference variable subclass object reference and cited the type of object rather than a reference variable type determines the call who is a member of the method, but this is the method called must be defined in a superclass, method that is covered by a subclass.

What are the five basic principles of object Orientation (optional)

  • SRP(Single Responsibility Principle) class functions should be a Single, not all-inclusive, like a grocery store.
  • OCP(open-close Principle) 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, you are not happy.
  • Subclasses can replace the parent class and appear anywhere the parent class can. Like you representing your dad at your grandma’s house. Ha ha ~ ~
  • The Dependency Inversion Principle DIP high-level modules should not depend on low-level modules, they should all depend on abstraction. Abstraction should not depend on concrete implementation; concrete implementation should depend on abstraction. When you go abroad, you should say you are Chinese, not which village you are from. For example, the Chinese are abstract, with specific xx province, XX city and XX county below. The abstraction you have to rely on is Chinese, not that you are xx village.
  • It is better to use multiple interfaces related to specific customer classes rather than one general Interface when designing AN ISP. For example, if a mobile phone has the functions of making calls, watching videos, playing games and so on, it is much better to separate these functions into different ports than to put them into one port.

Classes and interfaces

Abstract classes versus interfaces

  • Abstract classes are used to capture common features of subclasses. An interface is a collection of abstract methods.

  • From the design level, abstract class is the abstraction of class, is a template design, interface is the abstraction of behavior, is a behavior specification.

The same

  • Neither interfaces nor abstract classes can be instantiated
  • Are at the top of inheritance and used to be implemented or inherited by other implementations
  • Both contain abstract methods that must be overridden by their subclasses

The difference between

parameter An abstract class interface
The statement Abstract classes are declared using the abstract keyword The interface is declared using the interface keyword
implementation Subclasses inherit abstract classes using the extends keyword. If a subclass is not abstract, it needs to provide implementations of all methods declared in the abstract class Subclasses implement the interface using the implements keyword. It needs to provide implementations of all declared methods in the interface
The constructor Abstract classes can have constructors Interfaces cannot have constructors
Access modifier Methods in abstract classes can be arbitrary access modifiers The default modifier for interface methods is public. It is not allowed to be private or protected
Multiple inheritance A class can inherit at most one abstract class A class can implement multiple interfaces
Field declarations The field declaration of an abstract class can be arbitrary Interface fields are static and final by default

Note: Java8 introduced default methods and static methods in interfaces 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 each have their advantages and disadvantages. In the selection of interfaces and abstract classes, the following principles must be followed:
    • Behavior models should always be defined through interfaces rather than abstract classes, so interfaces are often preferred over abstract classes.
    • When you choose an abstract class, you usually want to define the behavior of the subclass, but you also want to provide common functionality for the subclass.

What are the differences between ordinary classes and abstract classes?

  • Ordinary classes cannot contain abstract methods. Abstract classes can contain abstract methods.
  • Abstract classes cannot be instantiated directly; ordinary classes can be instantiated directly.

Can abstract classes use final decoration?

  • No, an abstract class is defined to be inherited by other classes. If it is defined as final, the class cannot be inherited, and thus conflicts with each other. Therefore, final cannot modify an abstract class

What keyword is used to create an object? How is an object instance different from an object reference?

  • The new keyword creates the object instance (the object instance is in heap memory) and the object reference points to the object instance (the object reference is in stack memory). An object reference can point to zero or one object (a string can be tied to either a balloon or a balloon); An object can have n references to it (a balloon can be tied with n strings)

Variables and Methods

What is the difference between a member variable and a local variable

  • Variable: An amount whose value can change within a range during the execution of a program. In essence, a variable is a small area of memory

  • Member variables: Variables defined outside a method but inside a class

  • Local variables: variables in a method of a class.

  • The difference between member variables and local variables

scope

  • Member variables: Valid for the entire class.
  • Local variables: valid only in a certain scope. (Usually refers to the method, the body of the statement)

Storage location

  • Member variables: Exist as the object is created, disappear as the object disappears and are stored in heap memory.
  • Local variables: They exist when methods are called or statements are executed and are stored in stack memory. When the method is called or the statement is finished, it is automatically released.

The life cycle

  • Member variables: They exist as the object is created and disappear as the object disappears
  • Local variables: Automatically released when the method is called or the statement is finished.

The initial value

  • Member variables: have default initial values.
  • Local variables: there is no default initial value and must be assigned before use.

Define the role of a constructor in Java that does nothing and takes no arguments

  • If a Java program calls a superclass-specific constructor without super() before executing a subclass constructor, it will call the “no-arguments constructor” in the superclass. Therefore, if only the constructor with arguments is defined in the parent class and no super() is used to call the specific constructor in the parent class in the constructor of the child class, an error will occur at compile time because the Java program will not find a constructor without arguments in the parent class to execute. The solution is to add a constructor to the parent class that does nothing and takes no arguments.

The subclass constructor is called before the subclass constructor is called.

  • Help subclasses do initialization work.

What does a class constructor do? If a class does not declare a constructor, does the modifier execute correctly? Why is that?

  • The main function is to complete the initialization of the class object. Yes. Because a class will have a default constructor that takes no arguments even if it does not declare a constructor.

What are the properties of constructors?

  • The name is the same as the class name;

  • There is no return value, but the constructor cannot be declared with void;

  • Automatically executed when an object of the class is generated, no call required.

Static and instance variables

  • Static variables: Static variables are classes that do not belong to any instance objects, so they only have one copy in memory. The JVM allocates memory for static variables only once during class loading.

  • Instance variables: Each time an object is created, it will allocate memory space for member variables for each object. Instance variables belong to instance objects. In memory, there are several copies of member variables when objects are created several times.

Static variables are different from ordinary variables

  • Static variables are also called static variables. The difference between static and non-static variables is that static variables are shared by all objects and have only one copy in memory, which is initialized if and only if the class is first loaded. Non-static variables are owned by the object, initialized when the object is created, and have multiple copies that do not affect each other.

  • Also, static member variables are initialized in the order they are defined.

How are static methods different from instance methods?

Static methods differ from instance methods in two main ways:

  • You can use the “class name” when calling static methods externally. Method name, or object name. Method name “. Instance methods have only the latter. That is, you can call a static method without creating an object.

  • When a static method accesses a member of the class, it only allows access to a static member (that is, static member variables and static methods), but not to instance member variables and instance methods. Instance methods do not have this limitation

Why is it illegal to call a non-static member in a static method?

  • Because static methods can be called without an object, other non-static variables cannot be called in a static method, nor can members of a non-static variable be accessed.

What is the return value of a method? What does the return value do?

  • The return value of a method is the result of executing code in a method body. (provided that the method is likely to produce results). Return value: receives the result so that it can be used for other operations!

The inner class

What is an inner class?

  • In Java, you can put the definition of one class inside the definition of another class, called an inner class. The inner class is itself an attribute of the class, as defined by other attributes.

What are the classifications of inner classes

Inner classes can be divided into four types: ** member inner classes, local inner classes, anonymous inner classes, and static inner classes.

Static inner class
  • A static class defined inside a class is a static inner class.

    public class Outer {
    
        private static int radius = 1;
    
        static class StaticInner {
            public void visit(a) {
                System.out.println("visit outer static variable:"+ radius); }}}Copy the code
  • A static inner class can access all the static variables of the outer class, but not the non-static variables of the outer class. Static inner class creation, new outer class. Static inner class (), as follows:

    Outer.StaticInner inner = new Outer.StaticInner();
    inner.visit();
    Copy the code
Member inner class
  • A non-static class defined inside a class at a member location is an intra-member class.

    public class Outer {
    
        private static  int radius = 1;
        private int count =2;
        
         class Inner {
            public void visit(a) {
                System.out.println("visit outer static variable:" + radius);
                System.out.println("visit outer variable:"+ count); }}}Copy the code
  • Member inner classes can access all variables and methods of the external class, including static and non-static, private and public. A member inner class depends on an instance of an external class and is created in the same way as an external class instance. new inner class (), as follows:

    Outer outer = new Outer();
    Outer.Inner inner = outer.new Inner();
    inner.visit();
    Copy the code
Local inner class
  • An inner class defined in a method is a local inner class.

    public class Outer {
    
        private  int out_a = 1;
        private static int STATIC_b = 2;
    
        public void testFunctionClass(a){
            int inner_c =3;
            class Inner {
                private void fun(a){
                    System.out.println(out_a);
                    System.out.println(STATIC_b);
                    System.out.println(inner_c);
                }
            }
            Inner  inner = new Inner();
            inner.fun();
        }
        public static void testStaticFunctionClass(a){
            int d =3;
            class Inner {
                private void fun(a){
                    // System.out.println(out_a); A compilation error. A local class defined in a static method cannot access instance variables of an external class
                    System.out.println(STATIC_b);
                    System.out.println(d);
                }
            }
            Inner  inner = newInner(); inner.fun(); }}Copy the code
  • A local class defined in an instance method can access all variables and methods of the external class. A local class defined in a static method can access only static variables and methods of the external class. The local inner class is created in the corresponding method, new inner class (), as follows:

    public static void testStaticFunctionClass(a){
        class Inner {
        }
        Inner  inner = new Inner();
     }
    Copy the code
Anonymous inner class
  • Anonymous inner classes are inner classes that do not have a name and are often used in daily development.

    public class Outer {
    
        private void test(final int i) {
            new Service() {
                public void method(a) {
                    for (int j = 0; j < i; j++) {
                        System.out.println("Anonymous inner class"); } } }.method(); }}// Anonymous inner classes must inherit or implement an existing interface
     interface Service{
        void method(a);
    }
    Copy the code
  • In addition to not having a name, anonymous inner classes have the following characteristics:

    • An anonymous inner class must inherit an abstract class or implement an interface.
    • Anonymous inner classes cannot define any static members or methods.
    • When the parameter of the method needs to be used by an anonymous inner class, it must be declared final.
    • An anonymous inner class cannot be abstract; it must implement all the abstract methods of the inherited class or implemented interface.
  • Anonymous inner class creation:

    newClass/interface {// Anonymous inner class implementation section
    }
    Copy the code

Advantages of inner classes

Why do we use inner classes? Because it has the following advantages:

  • An inner class object can access the contents of the outer 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.
  • Inner classes effectively implement “multiple inheritance”, optimizing the pitfalls of Java single inheritance.
  • Anonymous inner classes make it easy to define callbacks.

What are the application scenarios of inner classes

  1. Some multi-algorithm scenarios
  2. Resolves some non-object-oriented blocks of statements.
  3. The proper use of inner classes makes your code more flexible and extensible.
  4. When a class is no longer used by any other class than its external class.

When a local inner class or an anonymous inner class accesses a local variable, why must the variable be final?

  • When a local inner class or an anonymous inner class accesses a local variable, why must the variable be final? What’s inside it? Take a look at this code:

    public class Outer {
    
        void outMethod(a){
            final int a =10;
            class Inner {
                void innerMethod(a){ System.out.println(a); }}}}Copy the code
  • In the example above, why final? Because of the inconsistent lifecycle, local variables are stored directly on the stack, and non-final local variables are destroyed when the method execution ends. The local inner class’s reference to the local variable still exists, and if the local inner class calls the local variable, an error will occur. Adding final solves this problem by ensuring that variables used by local inner classes are separated from outer local variables.

Internal class correlation, see the program to say the results

public class Outer { private int age = 12; class Inner { private int age = 13; public void print() { int age = 14; System.out.println(" local variable: "+ age); System.out.println(" inner class variable: "+ this.age); System.out.println(" Outer class variable: "+ Outer.this.age); } } public static void main(String[] args) { Outer.Inner in = new Outer().new Inner(); in.print(); }}Copy the code

Running results:

Local variable: 14 Internal variable: 13 External variable: 12Copy the code

Rewriting and overloading

Whether the constructor can be overridden

  • Constructors cannot be inherited and therefore cannot be overridden, but can be overridden.

The difference between Overload and Override. Can overloaded methods be differentiated by return type?

  • Methods overloading and overwriting are both ways of implementing polymorphism, the difference being that the former implements compile-time polymorphism while the latter implements runtime polymorphism.

  • Overloading: Occurs in the same class with the same method name and different parameter lists (different parameter types, numbers, and orders), regardless of method return values and access modifiers, that is, overloaded methods cannot be distinguished by their return types

  • Overwrite: in a parent class, the method name and parameter list must be the same, the return value must be less than or equal to the parent class, the exception thrown 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 rule); If the superclass method access modifier is private then the subclass is not overridden.

Object equality judgment

What is the difference between equals and equals

  • == : This is used to determine whether the addresses of two objects are equal. That is, determine whether two objects are the same object. (Base data type == compares values, reference data type == compares memory addresses)

  • Equals () : Also checks whether two objects are equal. But it is generally used in two ways:

    • Case 1: The class does not override equals(). Comparing two objects of that class through equals() is equivalent to comparing them through “==”.

    • Case 2: The class overrides equals(). In general, we override equals() to make the contents of two objects equal; Return true if their contents are equal (that is, the objects are considered equal).

    • Here’s an example:

      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, the object has the same content
              String aa = "ab"; // Put it in the constant pool
              String bb = "ab"; // Search from the constant pool
              if (aa == bb) // true
                  System.out.println("aa==bb");
              if (a == b) // false, different object
                  System.out.println("a==b");
              if (a.equals(b)) // true
                  System.out.println("aEQb");
              if (42= =42.0) { // true
                  System.out.println("true"); }}}Copy the code
  • Description:

    • The equals method on String is overridden, because the equals method on object compares the memory addresses of objects, while the equals method on String compares the values of objects.
    • When creating an object of type String, the virtual machine looks in the constant pool for an existing object with the same value as the object to be created, and assigns it to the current reference if it does. If not, create a new String in the constant pool.

HashCode vs. Equals (Important)

  • How does a HashSet check for repetitions

  • If two objects have the same hashCode(), equals() must also be true, right?

  • Relation between hashCode and equals methods

  • The interviewer may ask you, “Have you overridden hashcode and equals? Why do you have to override hashCode to override equals?”

HashCode () is introduced

  • HashCode () is used to get a hashCode, also known as a hashCode; It actually returns an int. The purpose of this hash code is to determine the index position of the object in the hash table. HashCode () is defined in the JDK’s Object.java, which means that any class in Java contains a hashCode() function.

  • Hash table stores key-value pairs. It can quickly retrieve the corresponding value according to the key. That’s where the hash code comes in! (Can quickly find the desired object)

Why hashCode

Let's use "how a HashSet checks for duplicates" as an example of why hashCode is needed:

  • When you add an object to a HashSet, the HashSet evaluates the object’s Hashcode value to determine where the object was added. It also compares the object’s Hashcode value to the hashcode value of other objects that have already been added. If there is no matching Hashcode, the HashSet assumes that the object is not repeated. But if objects with the same Hashcode value are found, the equals() method is called to check whether objects with hashCode equality are really the same. If they are the same, the HashSet will not let the join succeed. If it is different, it will be rehashed to another location. (From the second edition of my Java primer, Head First Java). This significantly reduced the number of equals calls, which in turn significantly increased the execution speed.

HashCode () and equals()

  • If two objects are equal, the Hashcode must also be the same

  • If two objects are equal, calling equals on both objects returns true

  • Two objects have the same hashCode value, and they are not necessarily equal

Therefore, if equals is overridden, hashCode must be overridden as well

The default behavior of hashCode() is to generate unique values for objects on the heap. If hashCode() is not overridden, the two objects of the class will never be equal anyway (even if they point to the same data)

What is the difference between the equality of objects and the equality of references to them?

  • Object equality compares whether the contents in memory are equal while reference equality compares whether the memory address they point to is equal.

Value passed

When an object is passed as a parameter to a method that changes the object’s properties and returns the changed result, it is passed by value or by reference

  • It’s value passing. Method calls in the Java language only support value passing of parameters. When an object instance is passed to a method as a parameter, the parameter’s value is a reference to that object. Properties of objects can be changed during invocation, but changes to object references do not affect the caller

Why is there only value passing in Java

  • Let’s start by reviewing some of the technical terms used in programming languages for passing parameters to methods (or functions). A call by value method receives a value provided by the caller, while a call by reference method receives a variable address provided by the caller. A method can change the value of the variable that corresponds to a pass-reference, but not to a pass-value call. It is used to describe how method parameters are passed in various programming languages (not just Java).

  • The Java programming language has always adopted call-by-value. That is, a method gets a copy of all the parameter values, that is, it 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;

    swap(num1, num2);

    System.out.println("num1 = " + num1);
    System.out.println("num2 = " + num2);
}

public static void swap(int a, int b) {
    int temp = a;
    a = b;
    b = temp;

    System.out.println("a = " + a);
    System.out.println("b = " + b);
}
Copy the code
  • Results:

    a = 20 b = 10 num1 = 10 num2 = 20

  • Resolution:

  • In swap, the values of A and B are swapped without affecting NUM1 and NUM2. The values in a and b are copied from num1 and num2. Num1, num2, num1, num2, num1, NUM2, num1, NUM2, NUM1, NUM2

As you can see from the above example, a method cannot modify the parameters of a primitive datatype. Object references are different.


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]); } public static void change(int[] array) {array[0] = 0; }Copy the code
  • Results:

    1 0

  • Resolution:

  • Array is initialized and a copy of arR is a reference to an object, that is, array and ARR refer to the same array object. Therefore, external changes to the referenced object are reflected in the corresponding object.

As we have seen with Example2, it is not difficult to implement a method that changes the state of an object's parameters. The reason is simple: the method gets a copy of the object reference, and the object reference and other copies reference the same object at the same time.

Many programming languages (in particular, C++ and Pascal) provide two ways to pass parameters: value calls and reference calls. Some programmers (and even the author of this book) think that the Java programming language makes referential calls to objects. Since this misconception is somewhat common, a counter example is given to illustrate the problem in detail.


example 3
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Student s1 = new Student (" zhang "); Student s2 = new Student("小李"); Test.swap(s1, s2); System.out.println("s1:" + s1.getName()); System.out.println("s2:" + s2.getName()); } public static void swap(Student x, Student y) { Student temp = x; x = y; y = temp; System.out.println("x:" + x.getName()); System.out.println("y:" + y.getName()); }}Copy the code
  • Results:

    X: Xiao Li Y: Xiao Zhang S1: Xiao Zhang S2: Xiao Li

  • Resolution:

  • Before the exchange:

  • After the exchange:

  • It is clear from the above two figures that the method does not change the object references stored in the variables S1 and S2. The arguments x and y to the swap method are initialized as copies of two object references that this method swaps

  • conclusion

    • The Java programming language does not make reference calls to objects; in fact, object references are passed by value.
  • To summarize the usage of method parameters in Java:

    • A method cannot modify the parameters of a primitive 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 to a new object.

What is the difference between value passing and reference passing

  • Value passing: When a method is called, the parameters are passed as a copy of the value, that is, they are not related to each other.

  • Reference pass: refers to the method call, the parameter is passed by reference, actually passed the address of the reference, that is, the address of the memory space corresponding to the variable. A reference to a value is passed, meaning that both before and after the pass point to the same reference (that is, the same memory space).

Java packages

What packages are commonly used in the JDK

  • Java.lang: This is the base class of the system;
  • Java.io: this contains all the input/output classes, such as file operations, etc.
  • Java.nio: a new package written to improve functionality and performance in IO packages;
  • Java.net: Here are the net-related classes;
  • Java.util: This is the system helper class, specifically the collection class;
  • Java.sql: This is the class for database operations.

What is the difference between import Java and Javax

  • At the beginning, the packages required for Java apis were Java-starting packages, and Javax was only used to extend API packages. Over time, however, Javax has expanded to become part of the Java API. However, moving extensions from the Javax package to the Java package would be too cumbersome and would end up breaking a bunch of existing code. Therefore, it was ultimately decided that the Javax package would become part of the standard API.

So, there's really no difference between Java and Javax. It's all one name.

IO stream

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 of classification by operation object:

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

  • Short answer

    • BIO: Block IO Synchronous blocking IO is the traditional IO that we usually use. It is characterized by simple mode and convenient use, and low concurrent processing capability.
    • NIO: Non IO Synchronous non-blocking IO. NIO is an upgrade of traditional IO. The client and server communicate through channels, realizing multiplexing.
    • AIO: Asynchronous IO is an upgrade of NIO, also known as NIO2, which implements Asynchronous non-blocking I/O operations based on events and callbacks.
  • A detailed answer

    • 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.

What are the common methods of Files?

  • Files.exists () : checks whether a file path exists.
  • Files.createfile () : Creates a file.
  • Files.createdirectory () : Creates a folder.
  • Files.delete () : Deletes a file or directory.
  • Files.copy () : copies Files.
  • Files.move () : moves a file.
  • Files.size () : Displays the number of Files.
  • Files.read () : Reads Files.
  • Files.write () : writes Files.

reflection

What is the reflex 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.

What are the application scenarios of reflection mechanism?

  • 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

Java gets reflection in three ways

1. Implement reflection mechanism through new object 2. Implement reflection mechanism 3 through path. The reflection mechanism is implemented by class name

public class Student {
    private int id;
    String name;
    protected boolean sex;
    public float score;
}


public class Get {
    //获取反射机制三种方式
    public static void main(String[] args) throws ClassNotFoundException {
        //方式一(通过建立对象)
        Student stu = new Student();
        Class classobj1 = stu.getClass();
        System.out.println(classobj1.getName());
        //方式二(所在通过路径-相对路径)
        Class classobj2 = Class.forName("fanshe.Student");
        System.out.println(classobj2.getName());
        //方式三(通过类名)
        Class classobj3 = Student.class;
        System.out.println(classobj3.getName());
    }
}
Copy the code

Commonly used API

String related

Character constants and string constants

  1. Form: A character constant is a single character caused by a single quotation mark. A string constant is several characters caused by a double quotation mark
  2. A string constant represents an address value (where the string is stored in memory).
  3. Memory size Character constant takes up only one byte String constant takes up several bytes (at least one end of character flag)

What is a string constant pool?

  • String constant pool is located in the heap memory, specially used to store the string constants, can improve the utilization rate of memory, avoid open up more space to store the same piece of string, the JVM will first check when creating a string string constant pool, if the string already exists in the pool, it returns its reference, if not, the instantiation of a string in the pool, And returns its reference.

Is String the most basic data type

  • It isn’t. There are only eight basic data types in Java: byte, short, int, long, float, double, char, Boolean. All but primitive types are referencetypes. Enumeration types introduced later in Java 5 are a special type of reference.

A String is not one of Java's eight basic data types. A char is one of the basic data types used to describe text data, but it can only represent a single character, such as' a ', 'ok', etc. If you want to describe a piece of text, For example, "hello" is an array of length 2 char\[\] chars = {' you ', 'ok'};

But using arrays is too troublesome, so there is a String, String is a char type array, but when using the developer does not need to directly manipulate the underlying array, using a more convenient way to complete the use of strings.

What are the features of String

  • Immutability: String is a read-only String, and is typically an IMmutable object. To manipulate it, you create a new object and refer to it. The main purpose of immutable schema is to ensure data consistency when an object needs to be shared and accessed frequently by multiple threads.

  • Constant pool optimization: After a String object is created, it is cached in the String constant pool, and the next time the same object is created, the cached reference is returned directly.

  • Final: Final is used to define the String class, indicating that the String class cannot be inherited, which improves system security.

Why is String immutable?

  • The String class uses a final char array to store characters.

    /** The value is used for character storage. */ private final char value[];

Is String really immutable?

  • I think if someone asks this question, the answer should be fixed. Here are just two typical examples:

1 Just because a String is immutable does not mean that a reference is immutable

String str = "Hello";
str = str + " World";
System.out.println("str=" + str);
Copy the code
  • Results:

    str=Hello World

  • Resolution:

  • In fact, the contents of the original String remain the same, except that the STR has changed from the memory address pointing to “Hello” to the memory address pointing to “Hello World”, which means that an extra memory area is allocated to the “Hello World” String.

2. It is possible to modify so-called “immutable” objects through reflection

// Create the String "Hello World" and assign the reference s String s = "Hello World"; System.out.println("s = " + s); / / Hello World / / get the String class in the value Field Field valueFieldOfString = String. Class. GetDeclaredField (" value "); / / change the value attribute access valueFieldOfString setAccessible (true); Char [] value = (char[]) valueFieldofString.get (s); // Change the 5th character in the array referenced by value[5] = '_'; System.out.println("s = " + s); // Hello_WorldCopy the code
  • Results:

    s = Hello World s = Hello_World

  • Resolution:

  • Reflection allows you to access private members and then reflect the value attribute in the String, changing the structure of the array by obtaining the value reference. But normally we don’t do that, just to mention that there is this thing.

Whether the String class can be inherited

  • The String class is final and cannot be inherited.

Is String STR =” I “the same as String STR =new String(” I”)?

  • No, because memory is allocated differently. String STR =” I “, which the Java virtual machine allocates to the constant pool; String STR =new String(” I “) is allocated to the heap.

String s = new String(” xyz “); Several string objects are created

  • Two objects, “XYZ” for the static section and an object created on the heap with new.

    String str1 = “hello”; Str2 = new String(“hello”); str2 = new String(“hello”); 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

How do I reverse a string?

  • Use the Reverse () method of StringBuilder or stringBuffer.

  • Sample 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

Does an array have a length() method? String has no length() method

  • Arrays do not have a length() method, they have a length attribute. String has the length() method. In JavaScript, the length of a string is obtained through the length attribute, which is easily confused with Java.

What are the common methods of the String class?

  • IndexOf () : returns the indexOf the specified character.
  • CharAt () : Returns the character at the specified index.
  • Replace () : string replacement.
  • Trim () : Removes whitespace at both ends of a string.
  • Split () : Split string, returns a split array of strings.
  • GetBytes () : Returns a byte array of strings.
  • Length () : Returns the length of the string.
  • ToLowerCase () : converts the string toLowerCase.
  • ToUpperCase () : converts a string toUpperCase characters.
  • Substring () : intercepts a string.
  • Equals () : String comparison.

What is the advantage of using String as a key when using HashMap?

  • The internal implementation of a HashMap uses the hashcode of the key to determine where the value is stored. Since the string is immutable, its Hashcode is cached when the string is created and does not need to be evaluated again, making it faster than other objects.

What’s the difference between a String and a StringBuffer or a StringBuilder? Why is String immutable

variability

  • The String class uses character arrays to hold strings, and private final char value[], so strings are immutable. AbstractStringBuilder and StringBuffer both inherit from AbstractStringBuilder classes. AbstractStringBuilder also uses character arrays to store strings, char[] values, both of which 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 StirngBuilder in the same situation yields only a 10% to 15% improvement over using StringBuffer, but at the risk of multithreading insecurity.

A summary of the three uses

  • If you want to manipulate a small amount of data, use = String

  • Single thread manipulation of large amounts of data in string buffer = StringBuilder

  • Multithreaded manipulation of large amounts of data in string buffers = StringBuffer

The Date related

Packaging related

Automatic packing and unpacking

  • Boxing: Wrapping base types with their corresponding reference types;

  • Unpacking: convert packaging type to basic data type;

What’s the difference between int and Integer

  • Java is an almost pure object-oriented programming language, but it still introduces basic data types for programming convenience, but in order to treat these basic data types as objects, Java introduces a corresponding Wrapper class for each basic data type. The wrapper class for int is Integer, and since Java 5 automatic boxing/unboxing has been introduced to make them interchangeable.

  • Java provides a wrapper type for each primitive type:

    • Primitive types: Boolean, char, byte, short, int, long, float, double

    • Wrapper types: Boolean, Character, Byte, Short, Integer, Long, Float, Double

Is Integer A = 127 the same as Integer B = 127

  • For object reference types: == Compares the memory address of the object.
  • For basic data types: == compares values.

If the Integer literal has a value between -128 and 127, auto-boxing does not new a new Integer object, but refers directly to an Integer object in the constant pool, and results in false beyond the range A1 ==b1

public static void main(String[] args) {
    Integer a = new Integer(3);
    Integer b = 3;  // Automatically box 3 into type Integer
    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 types and then compared with C
    System.out.println(b == c); // true

    Integer a1 = 128;
    Integer b1 = 128;
    System.out.println(a1 == b1); // false

    Integer a2 = 127;
    Integer b2 = 127;
    System.out.println(a2 == b2); // true
}
Copy the code