java knowledge combing (Foundation) 1 - 10

If there is any deficiency, please correct it

  Java inherits the advantages of C + + language and removes the concepts of multi inheritance and pointer, which are difficult to learn in C + +. It has the characteristics of simplicity, object-oriented, distribution, compilation and interpretation, robustness, security, portability, high performance and so on.

1. What are the three features of Java?

  • Encapsulation is to hide everything that can be hidden and only provide the simplest programming interface to the outside world. For example, in a class, data and operation methods are bound, and data access can only be realized through these get/set methods (also known as interfaces).
  • Inheritance is the process of obtaining inheritance information from an existing class and creating a new class. The information provided is called the parent class (superclass, base class), and the inheritance information obtained is called the child class (derived class). It not only ensures continuity, but also realizes variability..

  • Polymorphism: it allows different subtype objects to respond differently to the same message, that is, using the same object, calling the same method, but doing different things. It is divided into compile time polymorphism (for example, method overloading, the same method implements multiple different logic and can be implemented in the same class. The principle of its implementation is that the method name is the same, and the number or type of parameters are different) and runtime polymorphism (for example: Method rewriting, it is impossible for two methods in a class to define the same method. Therefore, rewriting is the re implementation of the method defined by the subclass on the parent class).

  2. What are the characteristics of Java?

  • Simplicity: Java syntax is a "pure version" of C + + syntax. There are no header files, pointer operations (even pointer syntax), structures, unions, operator overloading, virtual base classes, etc. Moreover, the java development environment is far beyond the development environment of most other programming languages.
  • Object oriented: what is object-oriented? For example, an "Object-Oriented" Carpenter always focuses on the chair, and the second is the tool used; and a "non object-oriented" The carpenter's first consideration is the tools used. In the Java world, everything is object-oriented. The object-oriented characteristics of Java are equal to those of C + +, and the difference from C + + lies in multiple inheritance. In Java, it is replaced by a simpler interface concept. Moreover, compared with C + +, Java provides richer non runtime introspection functions.
  • Distributed (microservice): Java has a rich library of routines for handling TCP/IP protocols such as HTTP and FTP. Java applications can open and access objects on the network through URL s, which is as convenient as accessing local files.
  • Robustness: the biggest difference between Java and C + + is that the pointer model used by java can eliminate the possibility of rewriting memory and damaging data (people who have spent hours checking memory conflicts caused by pointer bug s must like this feature of Java) Not only that, the java compiler can detect many problems that can only be detected at run time in other languages.
  • Security: Java is suitable for network / fractional environment. In order to achieve this goal, a lot of energy has been invested in security. Using java can build anti-virus and tamper proof systems. From the beginning, Java has designed to prevent various common attacks: (1) stack overflow during operation. Common attack means of worms and viruses. (2) Destroy the memory outside your own process space. (3) read and write files without authorization.
  • Architecture neutrality: the compiler generates an architecture neutral object file format, which is compiled code. As long as there is a Java runtime system, these compiled code can run on many processors. The java compiler realizes this feature by generating bytecode instructions independent of a specific computer architecture. Well designed bytecode can not only It can be easily interpreted and executed on any machine, and can also be dynamically translated into local machine code.
  • Portability: unlike C/C + +, there is no "dependency on concrete implementation" in the Java specification . the size of basic data types and related operations are clearly described. For example, int in Java is always a 32-bit integer. Second, in C/C + +, int may be a 16 bit integer, a 32-bit integer, or other sizes specified by the compiler provider. In Java, data types have a fixed size, which eliminates the main problem of headache during code migration.
  • Interpretive: the Java interpreter can execute Java bytecode on any machine that knows the interpreter. Because linking is an incremental and lightweight process, the development process becomes faster and more exploratory.
  • High energy: Although satisfied with the interpreted bytecode performance, more efficient performance may be required in some cases. Bytecode can be dynamically translated (at runtime) into machine code corresponding to the specific CPU running the application.
  • Multithreading: Java was very advanced at that time. It was the first mainstream language to support concurrent programming. Multithreading can bring better interaction and real-time behavior. Concurrent programming is by no means easy, but Java performs well in this regard and can manage this work well.
  • Dynamic: Java is more dynamic than C/C + +. It can adapt to the evolving environment. New methods and instance variables can be added freely in the library without any impact on the client. It is very simple to find out the runtime type information in Java.

3. JDK, JRE and JVM

  • JDK: short for Java Development Kit, it is a Java Development Kit that provides a java development environment and runtime environment.
  • JRE: short for Java Runtime Environment, Java Runtime Environment, which provides a runtime environment for java.
  • JVM: the abbreviation of Java virtual machine. It is a part of Java running environment. It is a fictitious computer. It is realized by simulating various computer functions on an actual computer. JVM is used to parse and run Java programs.

Specifically, the JDK includes JRE, the compiler javac for compiling java source code, and many tools for debugging and analyzing Java programs. Both JDK and JRE contain JVM. In general, if you need to run Java programs (only run), just install JRE. If you need to write Java programs (Development), you need to install JDK.

For example, JDK is like a pot and bowl stove, which can fry delicious food in the hands of chefs (developers). JRE is like a container for food, and customers (users) don't need those tools.

4. How do java programs execute?

    java code is compiled into bytecode. From the perspective of file suffix,. java is compiled into. class file;
    The class file is placed in the Java virtual machine, which usually refers to the official Hotspot JVM of Oracle;
    Java virtual machine uses Class Loader to load class files;
    After loading, bytecode verification will be performed. After bytecode verification is passed, the JVM interpreter will translate the bytecode into machine code and submit it to the operating system for execution.

5. Data types in Java


Encapsulation object corresponding to original data type:

byte--Byte     short--Short    int--Integer    long--Long    float--Float    double--Double         boolean--Boolean      char--Character


Integer x = null;
int y = x.intValue();
//Null pointer exception reported after compilation

Integer a = 10 ; //Automatic boxing, the compiler executes Integer.valueOf(100)
                 // Before Java SE5, auto boxing should be written as follows: Integer a = new Integer(10);

int b = a;//Automatic unpacking, the compiler executes i.intValue()

//Note: since the box is disassembled automatically, pay attention to the null value of a
 Integer a = 200;  
 Integer b = 200;          
 System.out.println("a==b Results: "+(a==b));  //Output the result of a==b: false
 Integer c = 100;  
 Integer d = 100;  
 System.out.println("c==d Results: "+(c==d));  //Output the result of c==d: true

Why are the above output results different? Let's explore the source code:

//Implementation of valueOf method of Integer:
public static Integer valueOf(int i) {
      if(i >= -128 && i <= IntegerCache.high)
          return IntegerCache.cache[i + 128];
          return new Integer(i);

private static class IntegerCache {
        static final int high;
        static final Integer cache[];

        static {
            final int low = -128;

            // high value may be configured by property
            int h = 127;
            if (integerCacheHighPropValue != null) {
                // Use Long.decode here to avoid invoking methods that
                // require Integer's autoboxing cache to be initialized
                int i = Long.decode(integerCacheHighPropValue).intValue();
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - -low);
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

        private IntegerCache() {}

//As can be seen from the above two codes, when creating an Integer object through the valueOf method, if the value is between [- 128127],
//Returns a reference to an existing object in IntegerCache.cache; Otherwise, create a new Integer object.
//Therefore, c and d are 100, the output result is true,a and b are 200, and the output is false

6. What is the difference between a = a + B / A + = B?

+=The operator will perform implicit automatic type conversion. Here, a+=b implicitly converts the result type of addition operation to the type of holding result, while a=a+b will not perform automatic type conversion. For example:

byte a = 127;
byte b = 127;
b = a + b; // Report compilation error: cannot convert from int to byte
b += a; //The compilation runs normally

7. Can I convert int to byte? What happens if the byte range is exceeded?

We can do cast, but in Java, int is 32-bit and byte is 8-bit. Therefore, if cast, the top 24 bits of int type will be discarded, because the range of byte type is - 128 to 127.

8. What is the difference between = = and equals?

For basic type and reference type = =, the effect is different

  • Basic type: compares whether the values are the same;
  • Reference type: compares whether references are the same;

As follows:

String x = "string";
String y = "string";
String z = new String("string");
System.out.println(x==y); // Output result true
System.out.println(x==z); // Output result false
System.out.println(x.equals(y)); //Output result true
System.out.println(x.equals(z)); // Output result true

// x and y point to the same reference, so = = is also true
// The new String() method is rewritten to open up memory space, so x==z results in false,
//equals always compares values, so the result is true

Equals is essentially = =, but String and Integer override the equals method and turn it into value comparison. As follows:

class User{
    public User(String name) { = name;
    private String name;
    public String getName() {
        return name;
    public void setName(String name) { = name;
Cat c1 = new User("Jiang Tao");
Cat c2 = new User("Jiang Tao");
System.out.println(c1.equals(c2)); // The result is false

//The source code is as follows
public boolean equals(Object obj) {
    return (this == obj);

//equals is essentially==

String s1 = new String("Lao Wang");
String s2 = new String("Lao Wang");
System.out.println(s1.equals(s2)); //Result true

//The equals method of string. String overrides the equals method of Object and changes the reference comparison to value comparison, as follows:

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
            return true;
    return false;

Summary: = = value comparison for basic types and reference for reference types; By default, equals is a reference comparison, but many classes have changed the equals method, such as String and Integer, into a value comparison. Therefore, generally, equals compares whether the values are equal.

9. If the hashcodes () of the two objects are the same, equals() must also be true?

Error: the hashCode() of the two objects is the same, and equals() is not necessarily true. Code:

String str1 = "conversation";
String str2 = "Heavily";
System.out.println(String.format("str1: %d | str2: %d", str1.hashCode(),str2.hashCode()));//Output result: str1:1179395 | str2:1179395

System.out.println(str1.equals(str2));//Output result: false

//Obviously, the same value as hashcode, equals, is not necessarily true

10. The role of final in java?

final can modify variables, methods, and classes

  • The class modified by final is called the final class, which cannot be inherited.
  • final decorated methods cannot be overridden.
  • The variable modified by final is called a constant. The constant must be initialized. After initialization, the value cannot be modified.

That's all for today's sorting and sharing

Tags: Java Interview

Posted on Tue, 02 Nov 2021 18:10:37 -0400 by Blicka