Extract some knowledge points from “Java Core Technology · Volume I”.

The data type

Digital type

  • Java does not have any Unsigned types of int, long, short, byte, etc.

  • There are safer int and long operations in the Math class, including addExact(), subtractExact(), multiplyExact(), incrementExact(), decrementExact(), negateExact(), If overflow throws an ArithmeticException, zhuanlan.zhihu.com/p/80016248; principle can reference

  • The math.round () method rounds a floating-point number and returns a long;

  • Java for Boolean operation, the relational operators && and | | evaluated according to the short circuit calculation, and an operator & and | do not adopt the short-circuit evaluation;

  • The assignment operators =, binary assignment, and ternary operators are right associative and compute from right to left.

  • Java.math.BigInteger and BigDecimal can operate on integer and floating point numbers with arbitrary precision, but do not support arithmetic operators. The common methods are:

    static BigInteger valueof(long x); // Convert to BigInteger or BigDecimal
    int compareTo(BigInteger other); // < returns a negative number, = returns 0, > returns a positive number
    BigInteger add(BigInteger other);
    BigInteger subtract(BigInteger other);
    BigInteger multiply(BigInteger other);
    BigInteger divide(BigInteger other);
    BigInteger mod(BigInteger other); 
    BigInteger sqrt(a);
    Copy the code

character

  • Java.lang. String objects are immutable, allowing variables that refer to the String to refer to other strings;

  • To check for the equality of strings using equals(), the == operator checks whether two strings are in the same position, equivalent to Python’s is;

  • An empty string is a string of length 0, while STR == NULL means that there is no object associated with STR, and that it should be checked separately.

    if(str ! =null&& str.length() ! =0)
    Copy the code
  • Common String operations:

    int compareTo(String strCmp); // In lexicographical order, < returns a negative number, = returns 0, > returns a positive number
    boolean empty(a);
    boolean equals(String strCmp);
    boolean equalsIgnoreCase(String str_cmp);
    String replace(String strOld, String strNew); // Find all old and replace with new
    String substring(int begIndex, int endIndex);
    String repeat(int repCount);
    static String join(String separator, String[] strs);
    Copy the code
  • Some special things about UTF-16 and code points in Java:

    • The Windows path C:\users in the comment will be mistaken for a \u escape (Unicode escape) because Unicode escape is replaced before the code is parsed;
    • Java char uses UTF-16 encoding by default. It is not recommended to use char in programs.
    • length()withcharAt()It’s counting units of code,codePointCount()withcodePointAt()Code points are calculated. For example, emoji is one code point, accounting for two code units. If charAt() is used, it cannot be displayed correctly.
  • The StringBuilder class is used to dynamically build strings:

    int length(a);
    this append(String str);
    this insert(int offset, String str);
    this delete(int begIndex, int endIndex);
    String toString(a);
    Copy the code

 

Input and output

The input

  • Construct a java.util.Scanner object and associate it with System.in to read input from the console;

    Scanner in = new Scanner(System.in);
    Copy the code
  • To read input from a file, construct a java.util.Scanner object and associate it with the file name.

    Scanner in = new Scanner(Path.of("myFile.txt"), StandardCharsets.UTF_8);
    Copy the code
  • Without path.of (), Scanner parses the string to data instead of a file name;

  • Common methods for the Scanner class:

    String nextLine(a); // Enter to separate
    String next(a); // The space is separated
    int nextInt(a);
    double nextDouble(a);
    boolean hasNext(a);
    boolean hasNextInt(a);
    boolean hasNextDouble(a);
    Copy the code

The output

  • Java 5 uses the PRINtf method of C language, that is system.out.printf ();

  • Convert for printf format output:

    • D: a decimal integer
    • X: hexadecimal integer
    • F: fixed point floating point number
    • E: exponential floating point number
    • S: string
  • Flags used for printf format output:

    • + : prints a positive or negative sign
    • Space: A space is added before a number
    • 0: Add a 0 before the number
    • – : Left-aligned
    • # : force the f format to include the decimal point, or prefix the x format with 0x
    • $: specifies the parameter index
  • Construct a java.io.PrintWriter object and associate it with the file name to output to a file.

    PrintWriter out = new PrintWriter("myFile.txt", StandardCharsets.UTF_8);
    Copy the code

 

Control process

  • Java cannot declare variables with the same name in two nested blocks;

  • The switch statement case label can be:

    • Constant expressions for char, byte, short, and int
    • Enumerated constants
    • String literals (Java7 and above)
  • Java supports a labeled break statement. The tag must precede the outermost loop you want to break out of, followed by a colon:

    label:
    {
        if(condition)
            break label;
    }
    Copy the code

 

An array of

  • Array variable declaration and initialization

    int[] a = {1.2.3}; // Declare and allocate space at the same time, not separate
    int[] a = new int[100]; // The declaration is separate from the allocated space and initialized with the default value (num-0, Boolean false, object - NULL)
    int[] a = new int[] {1.2.3}; // The declaration is separate from the allocated space and initialized with the specified value
    Copy the code
  • Copy an array

    int[] newArray = oldArray; / / shallow copy
    int[] newArray = Arrays.copyOf(oldArray, oldArray.length); / / copy
    Copy the code
  • Java.util. Arrays

    static String toString(T[] a); // Convert the array to a string
    static String deepToString(T[][] a); // Convert a two-dimensional array to a string
    static T[] copyOf(T[] a, int end);
    static T[] copyOfRange(T[] a, int beg, int end);
    static void sort(T[] a);
    static int binarySearch(T[] a, T v); // Return subscript if found, otherwise return -(insert position +1)
    static int binarySearch(T[] a, int beg, int end, T v);
    static void fill(T[] a, T v);
    static boolean equals(T[] a, T[] b); // Return true if all elements with the same subscript are equal
    Copy the code

 

Object and class

  • Object variables in Java can be viewed as object Pointers in C++. All Java object variables are stored in the heap. The constructor is always used in conjunction with the new operator.

  • Java always calls by value, but since object variables are Pointers, a method gets a copy of the variable that points to the same object as the original.

  • Do not write accessor methods that return a mutable object reference, which would break encapsulation. Instead, use Clone to return a copy of the mutable object.

  • Final effects in Java are equivalent to top-level const in C++;

  • Constructor calls another constructor using this(params);

  • Java’s package mechanism is similar to the namespace in C++. Package equals namespace and import equals using.

  • If a class, variable, or method is not specified as public or private, it can be accessed by all methods in the package.

  • Java.time. LocalDate Common method

    static LocalData now(a); // Construct an object representing the current date
    static LocalData of(int year, int month, int day); // Construct an object with a specified date, month, and year
    int getYear(a)/getMonthValue(a)/getDayOfMonth(a); // Obtain the year/month/day
    int getDayOfWeek(a).getValue(a); // Get the day of the week
    LocalDate plusDays(int n)/minusDays(int n); // Generate the date n days before/after the date
    Copy the code
  • Java.util. Objects method for handling null references (Java 9)

    // Throw a NullPointerException with a MSG message if the object is NULL
    static <T> void requireNonNull(T obj, String msg); 
    // Return the default object if the object is null, otherwise return the object itself
    static <T> T requireNonNullElse(T obj, T defaultObj); 
    Copy the code

 

inheritance

inheritance

  • In Java, all inheritance is public. There is no private inheritance or protected inheritance.

  • Super is not a reference to an object, it is just a special keyword that instructs the editor to call the superclass method;

  • The statement that calls the constructor using super must be the first statement of the subclass constructor (the superclass must be constructed first);

  • In Java, dynamic binding is the default behavior. If you don’t want a method to be virtual, you can declare it final.

  • The virtual machine computes a method table for each class in advance, listing all the method signatures and the methods to actually call;

  • The abstract keyword is used to declare an abstract class or method;

  • Abstract classes cannot be instantiated, but object variables of the abstract class can be defined to reference instances of the class.

Object class

  • You can use the Object class to reference all types of objects;

  • Arrays of basic types all extend the Object class;

  • X.tostring () can be replaced with “”+x, so x can also be a primitive type or null;

  • Varargs method (Object… Method (new Object[]{arg1, arg2,… });

  • Java.lang. Object provides generic methods:

    boolean equals(Object otherObject);
    String toString(a);
    Copy the code
  • Common methods for java.util.objects

    static boolean equals(Object a, Object b); // Allow null equality
    Copy the code

Generic arraylists

  • Java.util. ArrayList

    boolean add(E obj); / / to add
    void add(int index, E obj) / / insert
    E set(int index, E obj); / / change
    E get(int index); / / check
    E remove(int index); / / delete
    int size(a);
    void ensureCapacity(int capacity); // Specify the capacity
    void trimToSize(a); // Cut the empty position
    Copy the code
  • Common methods for Java.util. Arrays

    static boolean equals(xxx[] a, xxx[] b); // The array is true only if it has the same length and corresponding elements
    Copy the code

Packing and unpacking

  • The wrappers are all subclasses of the Java.lang.number class

  • Autoboxing: When a base type is assigned to a wrapper object, the wrapper’s static method valueOf(base type) is automatically called.

  • Automatic unpacking: A wrapper object is automatically called when a wrapper object is assigned to a primitive type. Basic type Value()

  • Note that == is used for wrapping objects to determine their addresses, not their values. Use equals() instead

  • Common methods of the java.lang. Wrapper, using Integer as an example

    int intValue(a); // Methods used for automatic or manual unpacking
    static String toString(int i);
    static int parseInt(String s); // Return the integer represented by the string s
    static Integer valueOf(String s); // Returns an Integer object initialized with an Integer represented by the string s
    Copy the code

Enumeration class

  • The enumeration class is a subclass of the Java.lang. Enum class

    static Enum valueOf(Class enumClass, String name); // Return an enumeration constant named name in the given class
    String toString(a);
    int ordinal(a); // Return the declared position of the enumeration constant, counting from 0
    int compareTo(Enum otherEnum);
    Copy the code
  • Public enum Gender{MALE,FEMALE} declare an enum class Gender that has only MALE and FEMALE instances

  • So an enumerated class can declare properties, constructors, and methods just like a normal class.

 

Interfaces, Lambda expressions, and inner classes

interface

  • An interface is not a class, but a set of requirements for classes that want to conform to the interface;

  • Abstract classes tend to be abstract classes or things, and can only extend an abstract class;

  • Interfaces tend to be abstract functions or business operations, which can be extended to multiple interfaces.

  • Interfaces can provide most of the benefits of multiple inheritance while avoiding the complexity and inefficiency of multiple inheritance.

  • Methods in an interface are always public and must be public, so there is no need to provide access modifiers.

  • The fields in the interface are always public static final, so there is no need to provide redundant keywords.

  • It is possible to provide a default implementation for an interface method if the class implementing the interface does not need to implement the method, or if it needs to be compatible with older versions of the interface.

  • Instanceof checks whether an object implements an interface;

  • In the library, there are pairs of interface and utility classes such as Collection/Collections or Path/Paths;

  • In Java8, static methods are allowed in interfaces, so that the utility classes that accompany the interface are not required;

  • About the comparison interface Comparable

    public interface Comparable<T>{
            int compareTo(T other);
    }
    The sort(Object[] a) method of Java.util. Arrays requires that the array elements must be classes that implement the Comparable interface;
    // If compareTo uses A-B as an integer to sort, the operation may overflow. Call the static Interger.compare(A, B);
    Copy the code

Lambda expressions

  • A lambda expression is a passable block of code;

  • Writing techniques for lambda expressions:

    • Provide empty parentheses even if the lambda expression has no arguments:
    () - > {for(int i; i < 10; ++i) System.out.println(i); }Copy the code
    • If the argument type of the lambda expression can be derived, then the type can be ignored:
    Comparator<String> comp = (first, second) -> first.length() - second.length();
    Copy the code
    • If the lambda expression takes only one argument, and the type can be derived, then the parentheses can be ignored:
    ActionListener listener = event -> System.out.println(Instant.ofEpochMilli(event.getWhen));
    Copy the code
  • All you do with a lambda expression in Java is convert it to a functional interface (one with only one abstract method, such as Comparator

    );

  • Only variables whose values do not change can be referred to in lambda expressions (in fact, final variables that are not assigned after initialization);

  • A number of very general functional interfaces are defined in java.util.Function:

    • PredicateInterface,ArrayListtheremoveIf()The parameters ofPredicate;
    public interface Predicate<T>{
            boolean test(T t);
    }
    Copy the code
    • SupplierInterface, which returns a value of type T only when called, for lazy computation;
    public interface Supplier<T>{
            T get(a);
    }
    Copy the code

Method references

  • A method reference instructs the compiler to generate an instance of a functional interface, overriding the abstract methods of that interface to call the given method;

  • The code block of a lambda expression can be overridden as a method reference only if it has only method calls;

  • Method references can be passed in three ways:

    • Object ::instanceMethod object::instanceMethod

      For example, system.out ::println is equivalent to x -> system.out.println (x)

    • Class::instanceMethod Class::instanceMethod

      For example String: : compareToIgnoreCase equivalent to (x, y) – > x.com pareToIgnoreCase (y)

    • Class::staticMethod

      For example Math::pow is equivalent to (x,y) -> math.pow (x,y)

The inner class

  • Inner classes can be hidden from other classes in the same package;

  • Inner class methods can access data in the scope of the outer class, including originally private data.

  • An inner class object will have an implicit reference to outerclass. this, which refers to the OuterClass object that instantiates it;

  • A local inner class is an inner class without an access specifier. Its scope is limited to the block that declares the local inner class.

  • The local inner class is completely hidden from the outside world, but it has access to the fields and local variables of the outer class (the actual final variables);

  • An anonymous inner class is a local inner class that does not specify a class name and can be used only when creating an object:

    // Anonymous inner class that inherits from SuperType class
    var anonymousInnerClass = new SuperType(construction parameters){
            method and data
    }
    // An anonymous inner class that implements the InterfaceType interface
    var anonymousInnerClass = new InterfaceType(){
            method and data
    }
    Copy the code
  • To take advantage of the anonymous inner class support for initialization blocks, we can use “double parenthesis initialization” :

    // The outer parenthesis creates an anonymous subclass of ArrayList. The inner parenthesis initializes the object
    invite(new ArrayList<String>(){{add("Henry"); add("Tony"); }});// However, the more common method is to use list.of ()
    invite(List.of("Henry"."Tony"));
    Copy the code
  • The name of the current class is often used to generate log or debug information. Anonymous subclasses can be used to obtain the class name of a static method:

    // new Object(){} creates an anonymous inner class Object, and the getEnclosingClass() method gets information about its outer class
    new Object(){}.getClass().getEnclosingClass();
    Copy the code