Summary of java basics - quick review of java technology stack

java basics

Java basic concepts

  1. java overview and language background

    • The Java language is not a computer language launched by Sun (Stanford University Network: Stanford University Network) in 1995.
    • The father of java: James Gosling (James Gosling)
    • In 2009, Sun was acquired by Oracle Corporation, so just visit Oracle’s official website now: https://www.oracle.com
  2. java version/technology platform

    • javaSE (java standard edition, java platform standard edition): the core and foundation of java technology, and the foundation of the other two types
    • javaEE (java enterprise edition, java platform enterprise edition): A set of solutions for enterprise-level application development, including Servlet, JSP, JDBC and other technologies.
    • javaME (java micro edition, java platform micro version): a solution for mobile device applications, currently replaced by ios and Android
  3. Features/Benefits

    • Object-oriented, platform-independent, multi-threaded. . .
  4. jdk,jre,jvm

    • JDK (Java Development Kit) is called Java development tools, including JRE and development tools (java, javac...)
    • JRE (Java Runtime Environment), the Java runtime environment, includes the core class library of JVM and Java (java API)
    • JVM (Java Virtual Machine), the Java virtual machine, where java actually runs
    • Summary: We only need to install JDK, which contains the java operating environment and virtual machine.
  5. Java environment construction

    • Download and install jdk, pay attention to download LTS (long-term support, long-term support version)
    • Configure environment variables, JAVA_HOME, Path
    • Check whether the configuration is successfuljava -version
    • Environment construction details: https://coderwcb.blog.csdn.net/article/details/127143366
  6. Development and operation process

  7. java quick start

    • Common commands for getting started
      • javac(java compiler): responsible for compiling
      • java: responsible for running
    • write .javaa document
    • compile codejavac xxx.java
    • Run the code java xxxwithout class
  8. Java cross-platform principle

    The Java program is not run directly. The Java compiler compiles the Java source program into a platform-independent bytecode file (class file), and then the Java Virtual Machine (JVM) interprets and executes the bytecode file , that is, " compile first explaining ". Therefore, under different operating systems, you only need to install different Java virtual machines to realize cross-platform java programs. i.e. compile once, run everywhere

  9. Install idea and make relevant configurations

language foundation

  1. Comments: Comments do not affect the running of the program, and will disappear after compilation. But documentation comments can generate API help documentation through Javadoc

    • Annotation classification
      1. single line comment
      2. multiline comment
      3. Documentation comments
  2. Identifier: The identifier is the name used by the user when programming, and is used to name classes, methods, variables, constants, etc.

    • The composition rules of identifiers in Java:
      • It consists of letters, numbers, underscore "_", dollar sign "$", and the first character cannot be a number.
      • You cannot use keywords in java as identifiers.
      • Identifiers are case sensitive (case sensitive).
  3. Keyword: It is a word that has been endowed with a special meaning, also called an identifier with a special meaning, sometimes called a reserved word, and does not need to be memorized, because an error will be reported in the development tool

    • Keyword features: all lowercase letters, commonly used code editors will be highlighted
  4. method body

    • Right now{}
  5. type of data

    1. computer storage unit

      We know that computers can be used to store data, but whether it is a memory or a hard disk, the smallest information unit of a computer storage device is called a "bit (bit)", which we also call a "bit", usually with a lowercase letter "b "Indicates that a binary bit can only represent two states of 0 and 1. The most basic storage unit in a computer is called a "byte (byte)", which is usually represented by a capital letter "B". A byte is composed of 8 consecutive bits.
      In addition to bytes, there are some commonly used storage units, and their conversion units are as follows:

      • 1B (byte) = 8bit

      • 1KB = 1024B

      • 1MB = 1024KB

      • 1GB = 1024MB

      • 1TB = 1024GB

    2. data types in java

      • basic data type

        type of data keywords byte Defaults Packaging
        integer type byte 1 0 Byte
        short 2 0 Short
        int (default) 4 0 Integer
        long 8 0L Long
        floating point type float 4 0.0f Float
        double (default) 8 0.0d Double
        character type char 2 \u0000 (space) -> 0 Character
        Boolean type boolean 1 false Boolean

        When defining a variable of type long, you need to add L after the integer (both uppercase and lowercase letters are acceptable, capitalization is recommended). Because integers are of type int by default, integers that are too large may exceed the range of int.
        When defining a variable of type float, you need to add F after the decimal (both uppercase and lowercase letters are acceptable, capitalization is recommended). Because the default type of floating-point numbers is double, the value range of double is greater than that of float, and the types are incompatible.

      • Reference data type
        array, object

    3. type conversion

      • implicit conversion

        • Assign a value or variable representing a small data range to another variable representing a large data range. This conversion method is automatic, just write directly, as follows
        • insert image description here
      • forced conversion

        • Assign a value or variable representing a large data range to another variable representing a small data range.
      • constant optimization mechanism

        • When assigning a value to a variable, if the right side of "=" is all constants (including the constants defined by the final keyword ), then the result on the right side will be assigned to the variable on the left during the compilation phase. The constant optimization mechanism in Java is aimed at Data typebyte,short,char,String
  6. Constant: A quantity whose value cannot be changed during the running of the program .

    • Classification of constants in Java:
      • Integer constant Integer, eg: -10, 0, 88, etc.
      • Decimal constant Decimal, eg: -5.5, 1.0, 88.88, etc.
      • A character constant is a character enclosed in single quotes, for example: 'a', '5', 'B', 'medium', etc.
      • Boolean constant Boolean value, representing true and false, only two values ​​true and false
      • Empty constant A special value, null, whose value is null
      • String constants are multiple characters enclosed in double quotes (can contain 0, one or more), such as "a", "abc", "China", etc.
    • Except for empty constants, other constants can be output directly using the output statement.
  7. Variable: A quantity whose value can change while the program is running .

    • Note: In the same pair of curly braces, variable names cannot be repeated. Variables must be initialized (assigned) before they can be used.
  8. operator

    • Operators and Expression Concepts
      • Operators: Symbols that operate on constants or variables
      • Expression: A formula that uses operators to connect constants or variables and conforms to the Java syntax can be called an expression. Expressions connected by different operators represent different types of expressions. For example int c = a + b: Since + is an arithmetic operator, this expression is called an arithmetic expression.
    • arithmetic operator
      • add+
        • Character "+" operation
          • The char type participates in arithmetic operations, using the corresponding decimal value at the bottom of the computer.System.out.println((char) 'a' + 1); // 输出98,97 + 1 = 98
        • String "+" operation
          • When a string appears in the "+" operation, this "+" is a string connection character, not an arithmetic operation. When performing "+" operations continuously, execute them one by one from left to right.System.out.println(1 + 2 + "测试" + 3 + 4); // 3测试34 =》 从左往右执行
      • reduce-
      • take*
      • remove/
        • System.out.println(10 / 3); // 3
      • Take the remainder%
        • System.out.println(10 % 3); // 1
      • Notice
        • The difference between / and %: two data are divided, / takes the quotient of the result, and % takes the remainder of the result.
        • **Integer operations can only get integers. To get decimals, floating-point numbers must be involved in the operation. ** ie System.out.println((double) 10 / 3); // 3.33...or System.out.println(10.0 / 3); // 3.33...; why? First calculate 10/3=3.33... Then don't forget, the default type is int, which is equivalent to (int) 10/3 is naturally equal to 3
    • relational operator
      • Greater than >-> GT (greater than)
      • Greater than or equal to >=-> GE (greater equal)
      • Less than <-> LT(less than)
      • Less than or equal to <=-> LE (less equal)
      • Equal to ==-> EQ(equal)
      • not equal !=-> NE(not equal)
      • Note: The results of relational operators are boolean types, either true or false. Never put ""Wrongly written as "=",""It is a relationship of judging whether it is equal,"=" is an assignment.
    • Logical Operators
      • && =" short circuit with
      • || => short circuit or
      • ! => Logical NOT
      • | =" logical or
      • & => Logical NOT
      • Note: What we often use and what we often call is AND or NOT (&&, ||, !) . The difference is that the short circuit may only execute one side, while the logic will execute
    • Increment and decrement operators
      • self-increment++
      • Decrement--
      • Note: ++ and -- can be placed after the variable or in front of the variable. The difference is that when participating in the operation, if it is placed in front of the variable, the latest variable is calculated first, and then the latest variable is used to operate
    • assignment operator
      • =,+=,-=,*=,/=,%=
    • ternary operator
      • 关系表达式 ? 表达式1 : 表达式2;
      • The result of the relational expression is boolean type, call expression 1 when it is true, and call expression 2 when it is false.
    • bitwise operator
      • 左移(<<),右移(>>)practically useless
  9. flow control statement

    • sequential structure

    • Conditional (Branch) Structure

      • if
      • switch
        • Switch statement case penetration problem

        • Defining the same variable in different cases of the switch will result in an error (as follows). What is the reason and how to solve it?

          • Reason: Objects defined in brackets "{}" are scoped within the pair of brackets. The scope of variables is in the entire switch statement, not just in a specific case statement, so repeatedly defining the same variable will cause an error.
          • Solution: Add brackets "{}" to the case to change the scope of the object.switch ("A") {case "A": {int aa = 10;}break; case "B": {int aa = 10;}break; }
      • What is the difference between if and switch?
        • The switch parameter should be an integer such as byte, short, int, or char. Neither long nor string can be applied to swtich. switch can be an enumerated type (after JDK1.5), **string can be used after JDK1.7,** but long still can’t, so why do other integer types work? Because the parameters of switch can be int basic types or Integer Packaging type, byte, short, char can be implicitly converted to int
    • loop structure

      • for,while,do-while
      • The difference between the three cycles
        • The for loop and the while loop first judge whether the condition is true, and then decide whether to execute the loop body (judgment first and then execute)
        • The do...while loop first executes the loop body once, then judges whether the condition is true, and whether to continue to execute the loop body (execute first and then judge)
      • Three formats of infinite loop (infinite loop) = "reason, no termination condition
        • for( ; ; ){}
        • while(true){}
        • do {} while(true);
      • out of loop statement
        • break: Forcibly break out of the current loop directly, without executing the rest of the code. But in the case of multiple loops, if break is in the inner loop, only the inner loop is terminated, and the outer loop is executed as usual.
        • continue: just terminate the loop.
        • return: Make the program return to the place where a method was called.
        • break+label: Can be used to terminate multiple loops. Set a label before multiple loops, and break can terminate the entire loop.
        • System.exit(0) ; Terminate the currently running Java virtual machine. Just pass in a number as a parameter. Usually the input of 0 is recorded as a normal state, and the others are abnormal states.

array

  1. Array overview
    • An array is a fixed-length container for storing data, and the data types for storing multiple data must be consistent. Once the array is defined, the length and type of the array are fixed during program execution.
  2. array definition
    • dynamic initialization
      • The dynamic initialization of the array means that only the length of the array is given, and the default initialization value is given by the system.int[] arr = new int[3];
    • static initialization
      • When creating an array, determine the elements directly.int[] num = {1,2,3};
  3. array access
    • ArrayName[Index]; ie num[0].
    • What is an index?
      • Each element stored in the array will automatically have a number, starting from 0. This automatic number is called the array index (index)
  4. common operations
    • Traverse-"for, for enhancement, Interator (iterator), lambda, stream, Arrays
    • Filter/find = "common filter, binary search
    • Sort = "bubble / selection / insertion sort
    • summation/string concatenation
    • get max value
    • Arrays=>toString、sort、binarySearch
  5. Two-dimensional array - "similarly

object oriented

  1. basic concept

    • Process-Oriented (POP: Procedure-Oriented Programming): is to follow the logic step by step

    • Object-oriented (OOP: Object Oriented Programming): Object-oriented is a kind of thinking, based on process-oriented, it puts data and operations on data together as an interdependent whole

      • Class: A class is the response of the real world in the computer. It encapsulates data and operations on the data (template)

      • Object: It is an entity that can be seen and touched

      • Summary: A class is a description of things, an abstract concept, while an object is a concrete thing. That is, a class is a template for an object, and an object is an instance of a type

    • Which elements are included in the java class? what effect

      • Variables : data used to define objects
      • Method : Used to define the behavior of an object
      • Constructor : used to create objects
      • Code block : used to perform operations when the class is loaded or to perform common operations before each instantiation
      • Inner class : exists as a member of the class and can access the properties and methods of the outer class
  2. member variables and local variables

    • The location in the class is different : member variables (outside the method in the class) local variables (inside the method or on the method declaration)
    • Different locations in memory : member variables (heap memory) local variables (stack memory)
    • The life cycle is different : member variables (exist with the existence of the object, disappear with the disappearance of the object) local variables (exist with the call of the method, and disappear when the method is called)
    • The initialization values ​​are different : member variables (with default initialization values) local variables (without default initialization values, must be defined before assignment can be used)
  3. Construction method

    • Format: 1. The method name is exactly the same as the class name; 2. There is no return value, not even void;public【权限修饰符】 Demo【类名】(){}
    • Function: initialize the object
    • Precautions:
      • No construction method is defined, what? The system defaults to a default no-argument construction method
      • If the constructor is defined, what about the system no longer provides a default constructor
      • In use, a no-argument construction method and a full-argument construction method are usually defined
  4. this/super

    • this: is a reference, pointing to the current object. Generally used to distinguish between local variables and member variables

    • super: parent class object reference

    • keywords access member variables access member method access constructor
      this this.member variable this. member method(parameters...) this(parameters...)
      super super.member variable super. member method(parameters...) super(parameters...)
    • Note: this (parameters...), super (parameters...) must be placed in the first line of the construction method, and the two cannot coexist

  5. permission modifier

    • permissions within the class Same bag different types of buns different package non-subclass
      private × × ×
      default × ×
      protected ×
      public
  6. static keyword

    • Static can modify variables, methods, code blocks, and inner classes;
      • Static modified variables are static variables or class variables. Static variables are shared by all instances and do not belong to objects but to classes. Loaded as the class is loaded, memory is only allocated once for statics.
      • The method modified by Static is a static method, which means that the method belongs to the current class, not to an object, and the static method cannot be rewritten, and can be called directly by using the class name.
      • Static modified code blocks are called static code blocks, which are usually used for program optimization. The code in the static code block will only be executed once when the entire class is loaded. There can be multiple static code blocks, and if there are multiple blocks, they will be executed sequentially.
      • The class modified by Static is a static inner class;
    • The this or super keywords cannot be used in static methods.
    • Static methods can only access static members. Non-static methods can access static members as well as non-static members
  7. override / overload

    • Overload (Overload) : Occurs in a class with the same method name and different parameter lists (type, number, order), and has nothing to do with access modifiers and return values

    • Override (Override) : Occurs in the inherited class, the method name is the same, the parameter list and return value are the same

      • Constructor methods cannot be overridden; methods declared as final cannot be overridden; methods declared as static do not have overriding (only rewriting and polymorphic unions make sense); access rights (access modifiers) cannot be higher than the parent class Low ; overridden methods cannot throw wider exceptions
  8. Object-oriented three characteristics

    • Summarize:
      • Encapsulation: privatize resources, use the private keyword, hide everything that can be hidden, and only provide the simplest programming interface to the outside world. Improved data security, code reusability, and reduced coupling between programs
      • Inheritance: Occurs in two classes, one class inherits the properties and methods of the other with access rights, using the extends keyword, only single inheritance. Improves code reusability, and enables subclasses to extend and modify (rewrite) the parent class
      • Polymorphism: Polymorphism is based on inheritance. Inheritance can be polymorphic. Polymorphism means that different subclasses inherit the parent class and then rewrite and cover the methods of the parent class, so that they can be executed according to different objects. Method, and when the parent class reference points to the subclass object (upward transformation object ), it is called polymorphism. (inheritance, rewriting, parent class references pointing to subclass objects)
    • Replenish:
      • Encapsulation principle: member variable private, provide corresponding getXxx()/setXxx() methods
      • Inheritance access features: All constructors in subclasses will access the parameterless constructors in the parent class by default, because the first statement of each subclass constructor defaults to: super()
      • What should I do if there is no no-argument construction method in the parent class, but only a parameter construction method?
        • By using the super keyword to explicitly call the constructor with parameters of the parent class
        • Provide a parameterless constructor in the parent class
      • Type conversion between reference types
        • Upcasting (upcasting): the parent class reference points to the subclass object as upcasting;fatherClass obj = new sonClass();
        • Downcasting (upcasting): Contrary to upcasting, subclass references point to parent class objects; subtype object name = (subtype) parent class reference;sonClass obj = (sonClass) fatherClass;
      • Risk of transformation in polymorphism => ClassCastException; solution => instanceof
  9. Abstract class (abstract)

    • An abstract description of many things of a certain type in the real world. To put it bluntly, when analyzing things, if you find common content , you will extract it upwards . However, if the method function of the parent class is different from that of the subclass, then the subject of the method will not be extracted at this time. For example, [wolves, cats] belong to [animals]. , there is a eat()method, but wolves eat meat and cats are vegetarians. At this time [animals] can’t tell whether I eat meat or vegetarians. At this time, the subclass needs to define itself
    • Abstract classes and abstract methods must be decorated with the abstract keyword
    • Abstract classes do not necessarily have abstract methods, classes with abstract methods must be abstract classes
    • Abstract classes cannot be instantiated; why abstract classes cannot be instantiated
      • Because that's the rule. Abstract: It means not concrete. A class is a concrete description of an object, but an abstract class is not specific and has no method body (the members provided are not enough to generate a specific object), so an unspecific object cannot be generated. Just like, you can instantiate an apple, but you cannot instantiate a fruit (an object that exists in this reality).
    • Abstract classes can have constructors
    • subclass of abstract class
      • Either override all abstract methods in the abstract class
      • either an abstract class
  10. interface

    • An interface is a public specification standard, as long as it conforms to the specification standard, everyone can use it.
    • Two meanings of interface in Java
      • used to define specifications
      • for function expansion
    • The composition of the interface
      • Static constant: public static final
      • Abstract method: public abstract
      • Default method (Java8): default
        • The default method is not an abstract method, so it is not mandatory to be overridden . But it can be rewritten, remove the default keyword when rewriting
      • Static method (Java8): static
      • Private method (Java9): private or private static
    • The relationship between classes and interfaces
      • The relationship between classes and classes: Inheritance relationship, only single inheritance, but multi-layer inheritance
      • The relationship between classes and interfaces: the implementation relationship can be single-implemented or multi-implemented, and multiple interfaces can be implemented while inheriting a class
      • The relationship between interface and interface: inheritance relationship, single inheritance or multiple inheritance
    • interface cannot be instantiated => refer to abstract class
    • subclass of interface
      • Either override all abstract methods in the interface
      • Either the subclass is also an abstract class
    • The difference between abstract class and interface
      • All methods in an interface are implicitly abstract. An abstract class can contain both abstract and non-abstract methods.
      • A class can implement many interfaces, but can only inherit from one abstract class
      • If a class implements an interface, it must implement all the methods declared by the interface. However, a class may not implement all the methods declared by an abstract class. Of course, in this case, the class must also be declared as abstract.
      • An abstract class can implement an interface without providing an implementation of the interface's methods.
      • Variables declared in Java interfaces are final by default. Abstract classes can contain non-final variables.
      • Member functions in a Java interface are public by default. Member functions of abstract classes can be private, protected or public.
      • Neither interfaces nor abstract classes can be instantiated. But interfaces cannot have constructors, abstract classes can have constructors
  11. final keyword

    • final represents the final meaning, and can modify member methods, member variables, and classes
      • Fianl modified class: This class cannot be inherited (cannot have subclasses, but can have parent classes)
      • final modification method: this method cannot be overridden
      • Final modified variable: indicates that the variable is a constant and cannot be assigned again
        • Variables are basic types, and what cannot be changed is the value
        • The variable is a reference type, the address value cannot be changed, but the content in the address can be changed
  12. Code block: In Java, code enclosed in { } is called a code block

    • Local code blocks: shorten the life cycle of variables, release them early, and improve memory utilization; for example, solve the problem of duplicate names of switch variables
    • Static internal block: loaded with the loading of the class, and only executed once ; initialize the properties of the class, such as creating a database connection object that needs to be used all the time
    • Construction code block: located in the member position of the class, wrapped with "{}", each time before calling the constructor, the construction code block will be executed first, and the common code in multiple constructors can be put together to initialize the object
    • Synchronized internal blocks: Mutually exclusive execution in a multi-threaded environment
    • Priority : static code block > main > construction code block > construction method; there can be more than one code block, and if there are more than one, they will be executed sequentially.
  13. inner class

    • member inner class
    • static member inner class
    • local inner class
    • anonymous inner class
      • Premise: There is a class or interface, where the class can be a concrete class or an abstract class
      • Essence: It is an anonymous subclass , not an object that creates an interface
      • Format:new 接口名(){ 重写接口方法 }
      • Advanced usage: Lambda expression = "jdk8 new syntax, simplify the writing of anonymous inner classes, note: only simplify the writing of anonymous inner classes of functional interfaces
        • What are functional interfaces? It must be an interface and has only one abstract method . At the same time, a @FunctionalInterface annotation will be added to the interface to mark that the interface must satisfy the functional interface
        • Format:接口名 aa = (参数列表) -> { }

Common api classes

  • object

    • toString: Get the address value of the object
    • equals: Compare the address value of the object, but the actual use does not want to compare the address value of the object, but compares the attribute value of the object. At this time, the equals method needs to be rewritten, but the hashCode method must also be rewritten at the same time. Why? ?
      • hashCode is used to find the location, and equals is used to compare whether two objects are equal
      • What hashCode() does is get the hash code, also known as the hash code; it actually returns an int. The function of this hash code is to determine the index position of the object (such as hashSet) in the hash table.
        If two objects are equal, the hashcode must also be the same. But the hashcode is the same, but the class is not necessarily the same, so the hashCode must be rewritten when rewriting equals. It is
        like saying, I am looking for two identical clothes in the closet. The first step is to determine the box in the closet through the hash value. , the second part is to use equal to compare the same clothes
  • Objects

    • isNull: determine whether the object is empty
    • nonNull: determine whether the object is not empty
    • equals: Compare the address value of the object. It is recommended to use this comparison object, because it has a non-null judgment to avoid null pointer exceptions.
  • String/StringBuiler

    • String: All double-quoted strings in a Java program are objects of the String class. Immutable content after creation
      • equals,equalsIsIgnoreCase,toLowerCase,toUpperCase,subString,replace,split,charAt,indexOf,toCharArray
    • StringBuilder: the content is variable, generally used for splicing strings
      • append: add data and return the object itself , which can be chained directly
      • reverse: returns the reverse string sequence
  • Math

    • abs-absolute value; round-rounding; max-maximum value; min-minimum value, random-random number (0.0-1.0)
  • System

    • currentTimeMillis - get the current millisecond value; arraycopy - array copy
  • BigDecimal

    • Used for accurate calculation, such as amount related
    • It is best to use strings when creating BigDecimal, otherwise there will be precision problems;
      • BigDecimal bigDecimal1 = new BigDecimal(“0.1”);
      • BigDecimal bigDecimal2 = BigDecimal.valueOf(0.1); // Double's toString is performed internally
    • Commonly used methods: add-addition; subtract-subtraction; multiply-multiply; divide-division;
    • Divide attention: BigDecimal divide = bd1.divide (object involved in the operation, how many digits after the decimal point, rounding mode); the third parameter is as follows
      • BigDecimal.ROUND_UP forward method
      • BigDecimal.ROUND_FLOOR to tail method
      • BigDecimal.ROUND_HALF_UP round up
  • date and time

    • Usage scenario: get/set time; string to time, time to string = " and specify format conversion; then get a few days to get the time after a few months

    • Date

      • getTime- Gets the millisecond value of the date object from 00:00:00 on January 1, 1970 to the present, but generally usedSystem.currentTimeMillis()

      • setTime: set the time, in milliseconds; but generally used directly new Date(System.currentTimeMillis())

      • Example: Get the date one minute later

        • new Date(System.currentTimeMillis() + 1 * 1000 * 60)
          
    • SimpleDateFormat=>time formatting, thread unsafe

      • Time to string:
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss EEE a");
      String format = sdf.format(new Date()); // 2023年02月26日 22:43:38 星期日 下午
      
      • String conversion time:
      String str = "2020年11月11日 0:0:0";
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); // 格式必须和str一样
      Date parse = sdf.parse(str); // Wed Nov 11 00:00:00 CST 2020
      
    • Calendar: calendar, calendar is a variable date, once modified, the time and time represented by itself will change , you can get a few days, or a date after a few months

    • JDK8 time and date class: There are many methods, thread safe, the above thread is not safe, but in fact the most used one is the above

      • Common methods: Instant, LocalDateTime, LocalDate, LocalTime, DateTimeFormatter, Period, Duration
  • Packaging

    • basic data type Packaging
      byte Byte
      short Short
      int Integer
      long Long
      float Float
      double Double
      char Character
      boolean Boolean
  • Arrays

    • toString, sort=”number order, binarySearch=”binary search, asList
  • Regular expressions (English: Regular Expression, often abbreviated as regex in code).

    • boolean b = telNumber.matches("1[34857][0-9]{9}");
      str = str.replaceAll("[\\d]+", "#");    //#代替数字
      

abnormal

  • Overview: Abnormalities are different from normal situations, and errors occur. In java, the situation that blocks the current method or scope is called an exception
  • exception system
    • insert image description here

    • Exceptions are mainly divided into: errors, compile-time exceptions (controlled exceptions), runtime exceptions (uncontrolled exceptions)

      • Error: System level problem, which is an error that cannot be handled in the program
        • Virtual MachineError (virtual machine error)
        • NoClassDefFoundError (class definition error)
        • For example, when the jvm runs out of available memory, an OutOfMemoryError will occur
      • Exception: An exception that the program itself can catch and handle
        • Compile-time exception: An exception occurs during compilation, the exception must be handled, otherwise the compilation will not pass
          • IOException (exception that may occur when manipulating input and output streams)
          • ClassNotFoundException class not found exception
          • SQLException An exception that provides information about database access errors or other errors.
        • Runtime exceptions: exceptions that may occur during runtime, and do not require handling exceptions
          • NullPointerException null pointer exception
          • ArithmeticException Mathematical operation exception
          • NumberFormatException Number conversion exception
          • IndexOutOfBoundsException Array index out of bounds exception
          • ClassCastException (type conversion exception class)
          • IllegalArgumentException (Illegal parameter exception)
  • exception handling
    • Common methods: getMessage, printStackTract
    • 格式:try-catch-finally、throw、throws、try-with-resources
  • custom exception
    1. Inherit RuntinmeException or other exception classes
    2. Realize no-argument construction and argument construction
    3. Just use it directly
  • Log: If there is an exception, log records are required, which is also a specification
    • Specifications: log specifications are some interfaces, common specifications, apache's JCL (Jakarta Commons Logging), slf4j (Simple Logging Facade for Java)
    • Specific implementation technologies: Log4j, JUI, LogBack, log4j2
    • development path:
      1. Log4j: An open source project of Apache, which solves the problem that traditional logs System.out.println()cannot be customized, and the log granularity is not fine enough.
      2. JUI(java util logging): Java native log framework, pro-son, modeled on Log4J
      3. JCL (Jakarta Commons Logging): Develop log standards (just like jdbc), so that it can choose the appropriate log implementation class
      4. Slf4j (simple Logging Facade for java): The author of the original Log4J felt that Apache Commons Logging was not good enough, so he wanted to create a more elegant solution, so the slf4j log system was born. slf4j is actually a log facade interface. The role is similar to Commons Loggins. And he also provides a log implementation-logback for slf4j.
      5. LogBack: Another open source project by the father of Log4j
      6. log4j2: Since slf4j and its implementation logback came out, they quickly surpassed the original apache log4j system, so apache rewrote log4j in 2012 and established a new project Log4j2, which covers almost all the new features of logback
    • Log level: Used to control which log levels in the system can be output, and output log information not lower than the set level. The order of priority from low to high is: ALL < TRACE < DEBUG (logback default) < INFO < WARN < ERROR (log4j default) < FATAL < OFF, bold logos are common
      1. all [all]: All log levels, including custom levels.
      2. trace [Tracking/Tracking]: It is generally used to track the detailed program running flow, such as which method is run and which branch is entered during the running process of the program. Through the running process of the trace program, you can judge whether the program is running according to the expected logic.
      3. debug【Debugging】: This type of log is often used to judge whether there is a bug scene, and often records the detailed information of the code running, such as the parameter information passed in by the method call.
      4. info [Information]: It is used to record some key information about the running of the program. It does not record the entire process of running the program like trace, nor does it record detailed information for solving problems like debug. info records the operation information of the entire system, such as which stage the system has reached and which state it has reached.
      5. warn【Warning】: It is used to record some warning information. A warning message indicates that the program has entered a special state in which the program can continue to run, but it is not recommended to allow the program to enter this state because it may cause problems with the results.
      6. error [Error]: It is used to record the error information at runtime, indicating that there are problems that need to be solved during the running of the program, often some exceptions. When using the error log, the detailed reason for the exception will generally be recorded
      7. fatal [Fatal]: Indicates a very serious error event that may cause the application to terminate execution.
      8. off [closed]: the highest level, do not print logs.
    • print format note
      • The log should print out the input and output parameters of the method
      • It is recommended to use the parameter placeholder {} instead of splicing with +.
      • Exception information should include two types of information: crime scene information and exception stack information. If it is not processed, it will be thrown up through the keyword throws.
        Positive example: logger.error(various parameters or objects toString + “_” + e.getMessage(), e);
      • It is forbidden to enable debug in the online environment, because there are many debug logs in the general system, and a large number of debug logs are also used in various frameworks. After online debugging is enabled, the disk may fill up soon, affecting the normal operation of the business system.

gather

  • Data structure: The data structure is the way the underlying computer stores and organizes data. Refers to how the data are arranged together

    • Tree Evolution: Binary Tree - "Binary Search Tree -" Balanced Binary Tree - "Red Black Tree

  • Java collection system diagram

    • insert image description here
  • Summary of the characteristics of the java collection system

    • Collection is the top-level interface of a single-column collection : common member methods add, clear, remove, contains, isEmpty, size

      • List series collection: the added elements are ordered, repeatable, and indexed. Iterator can be used to achieve one-way traversal, and ListIterator can be used to achieve two-way traversal.

        • ArrayList: The underlying data structure is an array structure. The characteristics are: fast query, slow addition and deletion. Threads are not synchronized.

        • LinkedList: The bottom layer uses a doubly linked list data structure. The characteristics are: slow query, fast addition and deletion. Threads are not synchronized. It provides a lot of unique APIs that directly operate the first and last elements, such as addFirst, addLast, getFirst, getLast, removeFirst, removeLast

        • Vector: The bottom layer is an array data structure, thread-safe, low efficiency, JDK1.2 has been abandoned

      • Set series collection: the added elements are unordered, not repeated, and have no index. Only Iterator can be used to achieve single-item traversal. Threads are not synchronized. Set contains at most one null element

        • HashSet: The bottom layer is the hash table data structure, which is a structure with better performance for adding, deleting, modifying and querying data. It is characterized by unordered, non-repetitive, and non-indexed. The implementation of HashSet depends on HashMap, and the values ​​of HashSet are all stored in HashMap. In the constructor of HashSet, a HashMap object will be initialized, and HashSet does not allow repeated values. Therefore, the value of HashSet is stored in HashMap as the key of HashMap, and returns false when the stored value already exists. Determine the uniqueness of elements according to the hashCode and equals methods (judging whether the hashCode values ​​are the same, if they are the same, continue to judge equal)
        • LinkedHashSet: The underlying data structure is composed of a two-way linked list and a hash table, and the performance of adding, deleting, modifying and checking is better. The characteristics are orderly, non-repetitive, and index-free. It is a two-way linked list added to the hash table. The order of the elements is guaranteed by the linked list. The uniqueness of elements is guaranteed by the hash table.
        • TreeSet: The underlying data structure is a red-black tree. The characteristics are sortable, non-repeating, and index-free. You can sort the elements in the Set collection (default sorting - natural order ), or you can write a class yourself to implement the Comparable interface or customize the Comparator comparator object when creating a collection and pass it as a parameter to the constructor of TreeSet, which is also TreeSet The bottom layer guarantees the only principle.
    • Map: It is the top-level interface of the double-column collection . This collection stores key-value pairs, and the uniqueness of the key must be ensured. Common member methods include put, remove, clear, containsKey, containsValue, isEmpty, and size. The Key and Value can be extracted separately from the Map. The KeySet() method can extract all the keys into a Set, and the Values() method can extract all the values ​​in the map into a set.

      • HashTable: The bottom layer is a hash table (also called hash value) data structure, which cannot store null keys and null values. The collection thread is synchronous , and the efficiency is relatively low. Appeared in JDK1.0.

      • HashMap: The bottom layer is a hash table data structure, which can store null keys and null values. The threads are not synchronized and the efficiency is high. It replaced HashTable and appeared in JDK 1.2.

      • TreeMap: The bottom layer is a binary tree data structure. Null keys cannot be stored but null values ​​can be stored. Threads are not synchronized. The specific order can be determined by the specified Comparator, or judged according to the natural order of the keys.

  • Replenish

    • The underlying principle of the ArrayList collection:
      1. Use the collection created with empty parameters to create an array with a default length of 0 at the bottom
      2. When the first element is added , the underlying creates a new array of length 10
      3. When the storage is full, it will be expanded by 1.5 times, that is, 10*1.5=15
      4. If you add multiple elements at a time, 1.5 times is not enough, the length of the newly created is subject to actual; for example, if you add 100 elements, the length of the new array is 110
  • Java collection traversal method

    • traversal mode Array List Set Map
      for × ×
      enhanced for
      Iteration
      Stream
      Arrays × × ×
      print directly ×
  • Java additions and deletions

    • Flashback fori, Iteration
  • generic

    • 是JDK5中引入的特性,用于统一数据类型,可以在编译阶段约束操作的数据类型,并进行检查。
    • 注意java中的泛型是伪泛型,因为在class文件中是没有这个的
    • 泛型只支持使用引用数据类型。为什么?因为不写泛型默认是Object,而基础数据类型不能转化成Object
    • 分类
      • 泛型类 =》 类名< 类型 > => class Test<K,V>{},其中“K”,“V”可以理解为变量,但是不代表值,而是表示类型
      • 泛型方法 => public <T> testAdd(T key){}
      • 泛型接口 interface Test<K,V>{}
    • 常用类型:T (Type表示类型) 、 K V (分辨表示键值对中的key value)、E 代表Element、?表示不确定的类型
    • 泛型的继承和通配符
      • 泛型不具备继承性,但是数据具备继承性
      • 泛型的通配符:
        • ? extend E=》E或者是E的子类
        • ? super E=》E或者是E的父类
    • 使用场景
      • 类型不确定的时候可以定义泛型
      • 类型不确定但是指定是哪个继承体系中的,可以使用泛型的通配符
  • java可变参数:可变参数本质上就是一个数据,用于在形参中接受多个数据,比如int ...a

    • 形参列表中的可变参数只能有一个
    • 可变参数必须放在形参列表的最后面
  • stream流

    • 获取Stream流:创建一条流水线,并把数据放到流水线上准备进行操作
    • 中间方法:处理数据,操作完毕之后,还可以继续进行其他操作
      • filter,limit,skip,concat,distinct,map
    • 终结方法:一个Stream流只能有一个终结方法
      • forEach、count、collect

IO流

  • File定位文件:可以进行删除文件内容,读取文件信息等,但是不能读写文件内容

    • 操作File File常用方法
      增删 createNewFile、mkdir、mkdirs、delete
      判断和获取 isDirectory、isFile、exists、getAbsolutePath、getPath、getName、listFiles
  • 字符集:字节、字符

    • 我们是怎么把文字存储到计算机的?

      • 我们把文字转换成十进制的表现方式(比如“a”相当于97),然后转换成二进制,然后就可以存储到计算机。
    • 什么是字符集?什么叫字符编码

      • 字符集(Character set)是一个系统支持的所有字符的集合,包括各国家文字、标点符号、图形符号、数字等。计算机要准确的存储和识别各种字符集符号,就需要进行字符编码,一套字符集必然至少有一套字符编码。常见字符集有ASCII字符集、GBK字符集、Unicode字符集等
      • 字符集:规定了字符和字符码之间的对应关系。 可以将字符集理解成一个很大的表格,它列出了所有字符和二进制的对应关系,计算机显示文字或者存储文字,就是一个查表的过程。
      • 字符编码:规定了一个字符码在计算机中如何存储。
    • 常用字符集

      • ASCII字符集(American Standard Code for Information Interchange,美国信息交换标准代码)
        • 是最早产生的编码规范,包括数字、英文、符号
        • 一个字节存储一个字符,也就是8位,总共可以表示128个字符信息(2^8=256,不包括负数)
      • GBK(即“国标”“扩展”汉语拼音的第一个字母) 字符集:全称《汉字内码扩展规范》
        • window系统默认的码表。兼容ASCII码表,包括中日韩
        • 一个中文以两个字节存储,英文1个字节
      • Unicode字符集(又叫万国码、统一码):是计算机科学领域里的一项业界字符编码规范
        • Unicode包含了全世界所有的字符,兼容ASCII 。Unicode最多可以保存4个字节容量的字符。也就是说,要区分每个字符,每个字符的地址需要4个字节。这是十分浪费存储空间的,于是,程序员就设计了几种字符编码方式,比如:UTF-8,UTF-16,UTF-32。最广为程序员使用的就是UTF-8,UTF-8是一种变长字符编码,注意:UTF-8不是编码规范,而是编码方式。
          • utf-8:一个中文以3个字节存储,英文1个字节
      • 小结
        • 英文和数字在任何国家的字符集中都占一个字节(在任何国家的编码中都不会乱码)
        • GBK中一个中文字符2个字节
        • UTF-8中一个中文字符3个字节
        • 编码前的字符集和编码后的字符集必须一致,否则乱码
        • 中文的字节存储方式
          • 用字节流复制文本文件时,文本文件也会有中文,但是没有问题,原因是最终底层操作会自动进行字节拼接成中文,如何识别是中文的呢?
          • 汉字在存储的时候,无论选择哪种编码存储,第一个字节都是负数
      • 字符集的编码、解码操作
        • 编码:str.getBytes(“GBK”)
        • 解码:new String(gbks2,“GBK”)
  • 读写文件内容:IO流可以对硬盘中的文件进行读写

    • 什么叫io流

      • I/O是Input/Output的缩写, 用于处理设备之间的数据传输。如读/写文件,网络通讯等。

        流是一种抽象概念,它代表了数据的无结构化传递。

        Java程序中,对于数据的输入/输出操作以”流(stream)” 的方式进行,所以叫io流。java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据。常见的应用: 文件复制; 文件上传; 文件下载

    • 分类

      • 按照数据的流向(方向)
        • 输入流:读数据,是数据从硬盘文件读入到内存的过程 =》 硬盘->内容
        • 输出流:写数据,是内存程序的数据从内存写出到硬盘文件的过程=》内存->硬盘
      • 按照数据类型(单位)
        • 字节流:以字节为单位,可以读写所有数据
        • 字符流:以字符为单位
    • 使用场景

      • 如果操作的是纯文本,比如json文件,txt文件,优先使用字符流

        • 怎么判断是纯文本呢? 能用记事本打开并且能看懂的就是纯文本
      • 如果是图片、视频、音频等二进制文件,优先使用字节流

      • 如果不确认文件类型,优先使用字节流,字节流是万能的流

    • IO流快速入门

      1. 创建输入/输出流
      2. 读/写 操作
      3. 关闭输入/输出流
    • IO流体系结构图

      • IO流体系结构图

        字节流(byte) 字符流(char)
        分类 字节输入流 字节输出流 字符输入流 字符输出流
        抽象基类 InputStream OutputStream Reader Writer
        操作文件 FileInputStream FileOutputStream FileReader FileWriter
        操作数组 ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter
        缓冲流 BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter
        转换流 InputStreamReader OutputStreamWriter
        对象操作流 ObjectInputStream ObjectOutputStream
        打印流 PrintStream PrintWriter

        其中,转换流都是字节流转字符流。

        • OutputStreamWriter : 字节输出流 -> 字符输出流;
        • InputStreamReader : 字节输入流 -> 字符输入流

        对象操作流也叫序列化流

      • 读写常用方法:read、write、flush、close

      • 另外,字符缓冲流还有两个独特的方法:

        • BufferedWriter类newLine() :写入一个行分隔符。这个方法会自动适配所在系统的行分隔符。
        • BufferedReader类readLine() :读取一个文本行。

        注意:输出流必须刷新才能写入,当然也可以直接调用close() ,他里面包含了flush,但是使用close()关闭流后就不能在使用了

      • 对象操作流

        • 序列化:将对象的状态信息转换为可以存储或传输的形式的过程。程序通过序列化把Java对象转换成二进制字节流,然后就可以把二进制字节流写入网络或磁盘。
        • 反序列化:读取磁盘或网络中的二进制字节流数据,转化为Java对象
        • 序列化流注意事项
          • 一个对象要想被序列化,该对象所属的类必须必须实现Serializable 接口,Serializable是一个标记接口,实现该接口,不需要重写任何方法
          • 定义serialVersionUID:验证版本一致性 private static final long serialVersionUID = 42L;
        • 如果一个对象中的某个成员变量的值不想被序列化,给该成员变量加transient关键字修饰,该关键字标记的成员变量不参与序列化过程;private transient int age;
      • Properties作为Map集合的使用

        • Properties介绍
          • 不属于io流体系,
          • 是一个Map体系的集合类
          • Properties可以保存到流中或从流中加载
          • 属性列表中的每个键及其对应的值都是一个字符串
        • 常用方法:load、store

多线程

  • 多线程相关概念

    • 并发和并行
      • 并行:在同一时刻,有多个指令在多个CPU上同时执行
      • 并发:在同一时刻,有多个指令在单个CPU上交替执行
    • 进程和线程
      • 进程:是正在运行的程序
        • 独立性:进程是一个能独立运行的基本单位,同时也是系统分配资源和调度的独立单位
        • 动态性:进程的实质是程序的一次执行过程,进程是动态产生,动态消亡的
        • 并发性:任何进程都可以同其他进程一起并发执行
      • 线程:是进程中的单个顺序控制流,是一条执行路径
        • 单线程:一个进程如果只有一条执行路径,则称为单线程程序
        • 多线程:一个进程如果有多条执行路径,则称为多线程程序
  • 线程状态/线程生命周期

    • insert image description here
  • 多线程常用方法

    • 方法名 说明
      Thread(Runnable target) 分配一个新的Thread对象
      Thread(Runnable target, String name) 分配一个新的Thread对象,并设置线程名
      void run() 在线程开启后,此方法将被调用执行
      void start() 使此线程开始执行,Java虚拟机会调用run方法()
      String getName() 获取当前线程名称,默认线程名称时Thread-索引
      void setName() 设置线程名称
      public static Thread currentThread() 获取当前正在执行的线程对象
  • 创建多线程

    • 继承Thread类并重写run方法

    • 实现Runnable接口并重写run方法配合Thread构造方法

    • 实现Callable接口并重写call方法 配合FutureTask(是Runnable和Futrue的实现类)

  • 多线程创建线程三种实现方式的对比

    • 方式 优点 缺点
      继承Thread接口 编程比较简单,可以直接使用Thread类中的方法 可以扩展性较差,不能再继承其他的类
      实现Runnable接口 扩展性强,可以继续继承和实现其他的类 不能返回线程执行的结果
      实现Callable接口配合FutureTask 扩展性强,可以继续继承和实现其他的类。可以得到线程执行的结果 编程相对复杂
  • 线程安全=》线程同步

    • 线程安全:多个线程同时操作一个共享资源的时候可能会出现业务安全问题,称为线程安全问题

    • 线程同步:为了解决线程安全的问题

    • 线程同步的核心思想:加锁,把共享资源上锁,每次只能让一个线程进入访问,访问完毕之后解锁,然后其他线程才能进来

    • 实现线程同步的方式

      • 同步代码块synchronized(任意对象) { 多条语句操作共享数据的代码 }

      • 同步方法

        • 普通同步方法:修饰符 synchronized 返回值类型 方法名(方法参数) { 方法体;} => 锁对象是this
        • 静态同步方法:修饰符 static synchronized 返回值类型 方法名(方法参数) { 方法体;} => 锁对象是类名.class
      • 同步锁(lock锁)

        • 虽然我们可以理解同步代码块和同步方法的锁对象问题,但是我们并没有直接看到在哪里加上了锁,在哪里释放了锁,为了更清晰的表达如何加锁和释放锁,JDK5以后提供了一个新的锁对象Lock。Lock是接口不能直接实例化,这里采用它的实现类ReentrantLock来实例化

        • 常用方法:

          • 方法名 说明
            ReentrantLock() 创建一个ReentrantLock的实例
            void lock() 获得锁
            void unlock() 释放锁
      • 死锁

        • 线程死锁是指由于两个或者多个线程互相持有对方所需要的资源,导致这些线程处于等待状态,无法前往执行

        • 什么情况下会产生死锁

          • 资源有限

          • 同步嵌套

    • Synchronized与Lock的区别

      • Lock是一个接口,而Synchronized是关键字。

      • Synchronized会自动释放锁,而Lock必须手动释放锁

      • Lock可以让等待锁的线程响应中断,而Synchronized不会,线程会一直等待下去。

      • Synchronized能锁住类、方法和代码块,而Lock是块范围内的

      • 通过Lock可以知道线程有没有拿到锁,而Synchronized不能。

  • 常见场景

    • 场景 方法名 说明
      线程休眠 public static void sleep() 使当前正在执行的线程停留(暂停执行)指定的毫秒数
      线程优先级 final int getPriority() 返回此线程的优先级
      final void setPriority(int newPriority) 更改此线程的优先级线程默认优先级是5;线程优先级的范围是:1-10
      守护线程 void setDaemon(boolean on) 守护线程是指为其他线程服务的线程。
      与守护线程相对应就是用户线程,用户线程可以理解为我们平常创建的普通线程,而守护线程守护的就是用户线程。当用户线程全部执行完毕,守护线程会跟着结束。
      也就是说守护线程必须伴随着用户线程,如果一个应用内只存在一个守护线程,没有用户线程,那么守护线程自然会退出。
      礼让线程/出让线程 yield() 线程的礼让。让出cpu,让其他线程执行,但礼让的时间不确定,所以也不一定礼让成功。
      插队线程/插入线程 join() 线程的插队。插队的线程一旦插队成功,则肯定先执行完插入的线程的所有任务。
      生产者消费者-等待唤醒机制 void wait() 导致当前线程等待,直到另一个线程调用该对象的 notify()方法或 notifyAll()方法
      void notify() 唤醒正在等待对象监视器的单个线程
      void notifyAll() 唤醒正在等待对象监视器的所有线程
  • 阻塞队列实现等待唤醒机制

    • put(anObject): 将参数放入队列,如果放不进去会阻塞;take(): 取出第一个数据,取不到会阻塞

    • 阻塞队列继承结构图参考集合体系

      • 常见BlockingQueue:

        ArrayBlockingQueue: 底层是数组,有界

        LinkedBlockingQueue: 底层是链表,无界.但不是真正的无界,最大为int的最大值

  • 线程池

    • 创建线程池
      • 自带线程池
        • ExecutorService threadPool= Executors.newCachedThreadPool(); 创建一个默认的线程池
        • ExecutorService threadPool= Executors.newFixedThreadPool(10); 创建一个指定最多线程数量的线程池
      • 自定义线程池=》一般使用自带的线程池
        • ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor (number of core threads, maximum number of threads, maximum survival time of idle threads, task queue, thread factory creation, task rejection strategy);
    • Submit thread pool:threadPool.submit(new MyRunnable());
    • Destroy the thread pool: threadPool.shutdown();=> The server runs 24 hours and is generally not destroyed

Network programming = "Summary in javaweb

In fact, this chapter has been replaced in actual use, so there is no need to spend time

Annotation & Reflection & Unit Test = "Summary in Framework

The framework principle will use

Guess you like

Origin blog.csdn.net/weixin_44797182/article/details/130283349