Basic module (1)

Basic module (1)

1. What is the difference between JDK and JRE?

  • JDK: The abbreviation of Java Development Kit, java development kit, provides a java development environment and operating environment.
  • JRE: The abbreviation of Java Runtime Environment, java runtime environment, provides the required environment for the operation of java.

Specifically, JDK actually includes JRE, as well as javac, a compiler for compiling java source code, as well as many tools for debugging and analyzing java programs. Simply put: if you need to run java programs, you only need to install JRE, if you need to write java programs, you need to install JDK.

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

== Interpretation

The effect of the basic type and the reference type == is different, as shown below:

  • Basic type: the comparison is whether the values ​​are the same;
  • Reference type: compare whether the references are the same;

Code example:

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

12345678

Code interpretation: Because x and y point to the same reference, == is also true, and the new String() method is rewritten to open up memory space, so the result of == is false, and the comparison of equals is always a value, so The results are all true.

equals interpretation

Equals is essentially ==, but String and Integer rewrite the equals method, turning it into a value comparison. Look at the following code to understand.

First, let’s look at the default case that equals compares an object with the same value. The code is as follows:

class Cat {
    
    
    public Cat(String name) {
    
    
        this.name = name;
    }

    private String name;

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }
}

Cat c1 = new Cat("王磊");
Cat c2 = new Cat("王磊");
System.out.println(c1.equals(c2)); // false

1234567891011121314151617181920

The output is beyond our expectations, it turns out to be false? What's going on, you can see the source code of equals. The source code is as follows:

public boolean equals(Object obj) {
    
    
		return (this == obj);
}

1234

It turns out that equals is essentially ==.

The question is, why do two String objects with the same value return true? code show as below:

String s1 = new String("老王");
String s2 = new String("老王");
System.out.println(s1.equals(s2)); // true

1234

Similarly, when we entered the equals method of String and found the answer, the code is 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;
                i++;
            }
            return true;
        }
    }
    return false;
}

12345678910111213141516171819202122

It turns out that String rewrites the equals method of Object, changing reference comparison to value comparison.

Summary : == For basic types is value comparison, for reference types, it is comparison comparison; and equals is reference comparison by default, but many classes override the equals method, such as String, Integer, etc. to change it It becomes a value comparison, so in general, equals compares whether the values ​​are equal.

3. If the hashCode() of two objects is the same, equals() must also be true, right?

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

Code example:

String str1 = "通话";
String str2 = "重地";
System.out.println(String.format("str1:%d | str2:%d",  str1.hashCode(),str2.hashCode()));
System.out.println(str1.equals(str2));

12345

The result of execution:

str1:1179395 | str2:1179395

false

Code interpretation: Obviously the hashCode() of "Call" and "Chongdi" are the same, but equals() is false, because in the hash table, hashCode() is equal, that is, the hash values ​​of the two key-value pairs are equal, but ha It is hoped that the values ​​are equal, and the key-value pairs are not necessarily equal.

4. What is the role of final in java?

  • The final modified class is called the final class, and this class cannot be inherited.
  • Final modified methods cannot be overridden.
  • The final modified variable is called a constant, the constant must be initialized, and the value cannot be modified after initialization.

5. How much is Math.round(-1.5) in java?

Equal to -1.

6. Is String a basic data type?

String is not a basic type. There are 8 basic types: byte, boolean, char, short, int, float, long, double, and String is an object.

7. What are the classes of manipulation strings in java? What is the difference between them?

The classes for manipulating strings are: String, StringBuffer, StringBuilder.

The difference between String and StringBuffer and StringBuilder is that String declares an immutable object. Each operation generates a new String object, and then points the pointer to the new String object. StringBuffer and StringBuilder can operate on the basis of the original object. Therefore, it is best not to use String when the content of a string is frequently changed.

The biggest difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe, while StringBuilder is non-thread-safe, but StringBuilder has higher performance than StringBuffer, so StringBuilder is recommended in a single-threaded environment, and StringBuffer is recommended in a multi-threaded environment.

8. Is String str="i" the same as String str=new String("i")?

Not the same, because the memory allocation method is different. With String str="i", the java virtual machine will allocate it to the constant pool; and String str=new String("i") will be allocated to the heap memory.

9. How to reverse the 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

123456789

10. What are the commonly used methods of the String class?

  • indexOf(): Returns the index of the specified character.
  • charAt(): Returns the character at the specified index.
  • replace(): string replacement.
  • trim(): Remove the blanks at both ends of the string.
  • split(): Split the string and return a split string array.
  • getBytes(): Returns the byte type array of the string.
  • length(): Returns the length of the string.
  • toLowerCase(): Convert the string to lowercase letters.
  • toUpperCase(): Convert a string to uppercase characters.
  • substring(): Intercept the string.
  • equals(): String comparison.

11. Does an abstract class have to have abstract methods?

No, abstract classes do not have to have abstract methods.

Sample code:

abstract class Cat {
    
    
    public static void sayHi() {
    
    
        System.out.println("hi~");
    }
}

123456

In the above code, the abstract class does not have abstract methods but can run normally.

12. What are the differences between ordinary classes and abstract classes?

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

13. Can abstract classes use final modification?

No, the definition of an abstract class is to let other classes inherit. If it is defined as final, the class cannot be inherited, which will cause conflicts with each other. Therefore, final cannot modify the abstract class. As shown in the figure below, the editor will also prompt an error message:

final definition of abstract class

14. What is the difference between an interface and an abstract class?

  • Implementation: Subclasses of abstract classes use extends to inherit; interfaces must use implements to implement interfaces.
  • Constructor: Abstract classes can have constructors; interfaces cannot.
  • Main method: An abstract class can have a main method, and we can run it; an interface cannot have a main method.
  • Number of implementations: A class can implement many interfaces; but only one abstract class can be inherited.
  • Access modifier: The methods in the interface use public modification by default; the methods in the abstract class can be any access modifier.

15. What are the types of IO streams in java?

Divided by function: input stream (input), output stream (output).

Divided by type: byte stream and character stream.

The difference between byte stream and character stream is: byte stream transfers input and output data in bytes according to 8 bits, and character stream transfers input and output data in characters according to 16 bits.

16. What is the difference between BIO, NIO and AIO?

  • BIO: Block IO Synchronous blocking IO is the traditional IO we usually use. It is characterized by its simple mode and convenient use, and low concurrent processing capability.

  • NIO: New IO synchronous non-blocking IO is an upgrade of traditional IO. The client and server communicate through Channel to achieve multiplexing.

  • AIO: Asynchronous IO is an upgrade of NIO, also called NIO2, which implements asynchronous non-blocking IO. The operation of asynchronous IO is based on events and callback mechanisms.

17. What are the common methods of Files?

  • Files.exists(): Check whether the file path exists.
  • Files.createFile(): Create a file.
  • Files.createDirectory(): Create a folder.
  • Files.delete(): Delete a file or directory.
  • Files.copy(): Copy files.
  • Files.move(): Move files.
  • Files.size(): View the number of files.
  • Files.read(): Read files.
  • Files.write(): Write files.

[3 differences between StringBuffer and StringBuilder] and String

StringBuffer and StringBuilder are both variable strings

Let's take a look at the class structure of StringBuffer and StringBuilder:

img

In fact, very simple, it is inheriting an abstract parent class string: AbstractStringBuilder. Let's take a look at their three differences.

1. StringBuffer: thread safe, StringBuilder: thread unsafe. Because all public methods of StringBuffer are modified by synchronized, and StringBuilder is not modified by StringBuilder.

2. Every time StringBuffer gets toString, it will directly use the toStringCache value of the buffer area to construct a string.

And StringBuilder needs to copy the character array every time, and then construct a string.

3. Since StringBuffer is thread-safe and all its public methods are synchronized, StringBuilder does not lock and synchronize methods, so there is no doubt that the performance of StringBuilder is much greater than StringBuffer.

to sum up

Therefore, StringBuffer is suitable for multi-threaded operation of the same StringBuffer, and StringBuilder is more suitable for single-threaded situations.

String StringBuffer StringBuilder
The value of String is immutable, which leads to a new String object generated every time a String operation is performed, which is not only inefficient, but also wastes a lot of priority memory space StringBuffer is a variable class and a thread-safe string manipulation class. Any operation on the string it points to will not generate new objects. Each StringBuffer object has a certain buffer capacity. When the string size does not exceed the capacity, no new capacity will be allocated. When the string size exceeds the capacity, the capacity will be automatically increased. Variable class, faster
Immutable variable variable
Thread safe Thread unsafe
Multi-threaded manipulation of strings Single-threaded manipulation of strings

One of the three characteristics of object-oriented (encapsulation, inheritance, polymorphism)

Encapsulation thought
  1. Encapsulation overview
    is one of the three characteristics of object-oriented (encapsulation, inheritance, polymorphism)
    is the simulation of the objective world by an object-oriented programming language. In the objective world, member variables are hidden inside the object and cannot be directly operated by the outside world.
  2. Encapsulation principle
    Hide some information of the class inside the class, and do not allow direct access by external programs, but use the methods provided by the class to realize the operation of the hidden information and access the
    member variable private, and provide the corresponding getXxx()/setXxx( )method
  3. The benefits of encapsulation
    The operation of member variables is controlled by methods, which improves the security of
    the code. Encapsulates the code with methods to improve the reusability of the code.
inherit
  • Concept of inheritance
    • Inheritance is one of the three major characteristics of object-oriented, which can make the subclass have the properties and methods of the parent class, and can also redefine in the subclass, and add properties and methods
  • Implement inherited format
    • Inheritance is achieved through extends
    • Format: class subclass extends parent class {}
      • Example: class Dog extends Animal {}
  • Benefits of inheritance
    • Inheritance can make the relationship between the class and the class, the relationship between the child and the parent class, after the child parent class is generated, the child class can use the non-private members of the parent class.
  • Characteristics of inheritance in Java
    1. Classes in Java only support single inheritance, not multiple inheritance
      • Error example: class A extends B, C {}
    2. Classes in Java support multiple levels of inheritance
  • Multi-level inheritance sample code:

public class Granddad {

public void drink() {
    System.out.println("爷爷爱喝酒");
}

}

public class Father extends Granddad {

public void smoke() {
    System.out.println("爸爸爱抽烟");
}

}

public class Mother {

public void dance() {
    System.out.println("妈妈爱跳舞");
}

}
public class Son extends Father { ​ // At this point, the Son class has both a drink method and a smoke method }

Polymorphism
  • What is polymorphism

    ​ Different forms of the same object at different moments

  • The premise of polymorphism

    • Inheritance or realization relationship
    • Method rewrite
    • There must be a parent class reference pointing to a child class object

Member access features

  • Member variables

    ​ Compile to see the parent class, run to see the parent class

  • Member method

    ​ Compile to see the parent class, run to see the child class

  • benefit

    ​ Improve the scalability of the program. When defining a method, use the parent type as a parameter, and when using it, use the specific subtype to participate in the operation

  • Disadvantages

    ​ Cannot use unique members of subclasses

interface

  • The interface is a kind of public specification standard, as long as it conforms to the specification standard, everyone can use it.
  • Two meanings of the existence of interfaces in Java
    1. Used to define specifications
    2. Used to expand the function

Features of the interface

  • The interface is modified with the keyword interface

    public interface 接口名 {
          
          } 
    
  • Class implementation interface is represented by implements

    public class 类名 implements 接口名 {
          
          }
    
  • Interface cannot be instantiated

    ​ We can create an implementation class object of the interface using

  • Subclass of interface

    ​ Or rewrite all abstract methods in the interface

    ​ Either the subclass is also an abstract class

Member characteristics of the interface

  • Member characteristics

    • Member variables

      ​ can only be a constant
      ​ Default modifier: public static final

    • Construction method

      ​ No, because the interface is mainly for extended functions, and there is no specific existence

    • Member method

      ​ Can only be an abstract method

      ​ Default modifier: public abstract

      ​ Regarding the methods in the interface, there are some new features in JDK8 and JDK9, which will be explained later

The relationship between classes and interfaces

  • The relationship between class and class

    ​ Inheritance relationship, only single inheritance, but multi-layer inheritance

  • The relationship between class and interface

    ​ Realization relationship, you can implement single or multiple implementations, you can also implement multiple interfaces while inheriting a class

  • The relationship between interface and interface

    ​ Inheritance relationship, single inheritance or multiple inheritance

Guess you like

Origin blog.csdn.net/xghchina/article/details/114706782