current position:Home>Java SE

Java SE

2022-01-27 04:12:04 IService

1. Java Three major versions

  • JavaSE: The standard version , Mainly used in desktop applications 、 Console development ...
  • JavaME: Embedded development , Mainly used in mobile phones 、 small home appliances ..., But there are not many applications now
  • JavaEE: Enterprise development , Mainly used in Web End 、 Server development ...

2. JDK、JRE、JVM

  • JDK:Java Development Kit,Java Developer tools
    • contain JRE and JVM
  • JRE:Java Runtime Environment,Java Runtime environment
    • contain JVM, If only to run Java Program , Just install JRE that will do
  • JVM:JAVA Virtual Machine,Java virtual machine
    • function Java The virtual machine of bytecode ,JVM There are specific implementations for different systems (Windows、Linux、MacOS), The purpose is to use the same bytecode to give the same results in different operating systems
      JDK、JRE、JVM

3. Java Development environment construction

  • JDK Download and install
    • download JDK 8
    • install JDK
  • Configure environment variables
    • Add system environment variable JAVA_HOME:C:\Program Files\Java\jdk1.8.0_202
    • Add system environment variable Path:%JAVA_HOME%\bin、%JAVA_HOME%\jre\bin
  • JDK catalogue
    • bin:Java Executable program
    • include:C&C++ The header file
    • jre:Java Runtime environment
    • lib:libary,java Class library files for
    • src: Resource file , Source code

4. Java Program operation mechanism

  • A compiled : Compile and then execute
    • Read the whole book after translation , If the content of the book changes, it needs to be translated again
    • Compile the code into something that the computer can recognize
    • Fast execution
  • interpreted : Run over compile
    • The translator translates and reads again and again , If the content of the book changes, even if the translation
    • Run over and compile into computer recognizable
    • The execution speed is not as fast as that of compiled type
  • Java It's compiled + Interpretive language
    • First compile it into class file , Then explain through the interpreter class The file becomes a computer recognizable language
       Operation process
    • What needs special attention is .class-> The machine code step . In this step JVM Class loader first loads the bytecode file , Then the interpreter interprets the execution line by line , The execution speed of this method will be relatively slow . and , Some methods and code blocks are often called ( That's hot code ), So the introduction of JIT(just-in-time compilation) compiler , and JIT Belongs to runtime compilation . When JIT After the compiler completes the first compilation , It will save the machine code corresponding to bytecode , You can use it directly next time . And we know that , The operation efficiency of machine code must be higher than Java Of the interpreter . It also explains why we often say Java It's a language where compilation and interpretation coexist

5. Java Basic grammar

  • notes

    • Single-line comments
      // Program entrance 
      public static void main(String[] args){
      
      }
      
    • Multiline comment
      /*
      *  Program entrance 
      * */
      public static void main(String[] args){
      
      }
      
    • Documentation Comments
      /**
       * @author lvfneg
       * @version jdk1.8
       */
      public static void main(String[] args){
      
      }
      
  • identifier

    • keyword : Cannot use system keywords
    • All identifiers should be in letters 、 Dollar symbol 、 Underline start
    • The first letter can be followed by a letter 、 Dollar symbol 、 Underline 、 Numbers or any combination of characters
    • Cannot use keyword as variable or method name
    • Identifier case sensitive
    • It can be named in Chinese , But not recommended , Pinyin is not recommended
  • data type

    • Strong type language : The use of variables is strictly required , All variables must be defined before they can be used
    • Weak type language
    • Java There are two major types of data
      • Basic types (primitive type)
        • value type
          • Integer types
            • byte: Occupy 1 Bytes , Range -128 To 127
            • short: Occupy 2 Bytes , Range -3278 To 32767
            • int: Occupy 4 Bytes , Range -21474838 To 214748367
            • long: Occupy 8 Bytes , Range -9223372036854775808 To 9223372036854775807
            //long Type should be added after the number L
            long number = 127L; 
            
             Integer extension 
            1、 Binary system :0B start 
            2、 octal :0 start 
            3、 Decimal system : Arabic numerals 
            4、 Hexadecimal :0x start 
            
          • Floating point type
            • float: Occupy 4 Bytes
            • double: Occupy 8 Bytes
            //float Type should be followed by F
            float number = 50.1F;
            
             Floating point expansion 
            1、float: Co., LTD. 、 discrete , There is rounding error , The actual result is about or close to but not equal to 
            
          • Character type :char Occupy 2 Bytes
            • All characters are numbers in essence , adopt Unicode Encoding ,Unicode Represents the association between numbers and characters
            • Escape character
              • \t: Space
              • \n: Line break
        • boolean type : Occupy 1 Bytes , Only true and false
          bollean isTrue = true;
          
      • Reference type (reference type)
        • class
        • Interface
        • Array
      • What are bytes
        • position (bit): The smallest unit of data storage in a computer ,11001100 It's an eight bit binary
        • byte (byte): The basic unit of data processing in a computer , It's customary to use capital letters B To express
        1B(byte, byte ):8bit( position )
        
        • character : Refers to the letters used in computers 、 Numbers 、 Words and symbols
        1bit Express 1 position 
        1Byte Represents a byte 1B=8b
        1024B=1KB
        1024KB=1M
        1024M=1G
        
  • Type conversion

    • because Java It's a strongly typed language , So when it comes to some calculations , Type conversion is needed
       low ------------------------------------> high 
      1、 Sort from low to high according to the storage length 
      2、long Than float and double All long , But after that , Because decimals are better than integers 
      byte,short,char->int->long->float->double
      
    • Operation , Different types of data are converted to the same type first , Then calculate
    • Cast
      • Changing from high to low requires a forced conversion , The problem of memory overflow is easy to occur when converting from high to low ( Memory overflow occurs when the length of high-level storage exceeds that of low-level storage )
    • Automatic type conversion
      • Automatic type conversion from low to high

    Be careful :
    1、 Not right boolean Value
    2、 You cannot convert an object type to an unrelated type
    3、 When converting a high level to a low level , Make a cast
    4、 There may be memory overflow or accuracy problems during conversion
    5、 When operating large numbers , Pay attention to overflow problem int money=10_0000_0000

  • Java Writing specifications

    • Class member variable : Lowercase and hump principle , Except for the first word , The following words are capitalized
    • local variable : Lowercase and hump principle
    • Constant : All capitals , Underline can be added
    • Class name : Capital letters and hump principle
    • Method name : Lowercase and hump principle
  • Operator

    • Arithmetic operator :+、-、*、/、%、++、--
      • Unary operator
        • ++、--
        int a = 10;
        //++ After , Assign first and then calculate 
        int b = a++;
        //++ Before again , Operation before assignment 
        int c = ++a;
        
    • Assignment operator :=
    • Relational operator :>、<、>=、<=、==、!=
    • Logical operators :&&、||、!
    • An operator :&、|、^、~、>>、<<、>>>
      • Very efficient , Use binary directly , No conversion to binary is required
      A = 0011 1100
      B = 0000 1101
      // And operators ,A and B Compare , If both corresponding bits are 1 The result is 1, Instead of 0
      A&B:0000 1100
      
      // Or operator ,A and B Compare , If both corresponding bits are 0 The result is 0, Instead of 1
      A|B:0011 1101
      
      // Exclusive or operator ,A and B Compare , If the corresponding bits are the same, the result is 0, Instead of 1
      A^B:0011 0001
      
      // Negation operator 
      ~B:1111 0010
      
      // Move left 、 Move right 
      0000 0000:0
      0000 0001:1
      0000 0010:2
      0000 0011:3
      0000 0100:4
      0000 0101:5
      0000 0110:6
      0000 0111:7
      0000 1000:8
      <<: current value *2 Or move forward  
      >>:  current value /2 Or step back 
      
    • Conditional operator :?:
    • Extended assignment operators :+=、-=、*=、/=
  • Packet mechanism

    • In order to better organize the class ,Java Package mechanism is provided , Used to distinguish between class names and namespaces
    • Syntax format of package statement
      package pkg1[. pkg2[. pkg3...]]
      
    • Generally, the inversion of company domain name is used as package name :com.iservice.www,com.iservice.dbhelper
    • In order to be able to use members of a package , Need to be in Java The program explicitly imports the package , Use "import" sentence
      //* Import all classes in the package 
      import pkg1[. pkg2...].(classname|*)
      
  • JavaDoc

    • javadoc The command is used to generate API Document
    • parameter information
      • @author: The author's name
      • @version: Version number
      • @since: Indicate the earliest use of jdk edition
      • @param: Parameter name
      • @return: Return value
      • @throws: Exception throw
      // Generate doc grammar , Command line mode 
      javadoc -encoding UTF-8 -charset UTF-8 Hello.java
      

6. Java Process control

  • User interaction Scanner

    • adopt Scanner Tool class , You can get user input
      // Basic grammar 
      public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println(" Use next Mode reception :");
        // Determine whether the user enters a string 
        if(scanner.hasNext()){
            String userInput = scanner.next();
            System.out.println(" Input content :" + userInput);
        }
        scanner.close();
      }
      
    • adopt Scanner Class next() And nextLine() Method to get the input string , Before reading again, we usually need to use hasNext() And hasNextLine() Determine whether there is any input data
      • next()
        • You must read valid characters before you can end the input
        • Whitespace encountered before entering valid characters for ,next() Method will automatically remove it
        • Only after entering valid characters can the blank space entered later be used as the separator or Terminator
        • next() Cannot get string with space
      • nextLine()
        • With Enter End of character , in other words nextLine() Method returns all the characters before enter
        • You can get spaces
  • Sequential structure

    • JAVA The basic structure of the system is the order structure , Unless otherwise specified , Otherwise, it will be executed sentence by sentence in order
    • Sequence structure is the simplest algorithm structure
    • Between statements , Boxes are executed from top to bottom , It is composed of several processing steps executed in turn , It is a basic algorithm structure that any algorithm can't do without
  • Selection structure

    • if Single choice structure
    • if Double choice structure
    • if Multiple choice structure
    • Nested if structure
    • switch Multiple choice structure
      • switch The variable type in a statement can be
        • byte、short、int perhaps char
        • from Java SE7 Start ,switch Support string String type
        • meanwhile case Label must be a string constant or literal
  • Loop structure

    • while
    • do...while
    • for
      // Dead cycle 
      for(;;){
      
      }
      
    • stay Java5 An enhanced form for arrays is introduced in for loop
      • Java enhance for The circular syntax format is as follows
        int[] numbers = {1,2,3,4,5,6};
        for(int x:numbers){
          System.out.println(x);
        }
        
      • Statement statement : Declare new local variables , The type of the variable must match the type of the array element , Its scope is limited to the loop statement block , Its value is equal to the value of the data element at this time
      • expression : Expression is the name of the array to be accessed , Or a method that returns an array
  • break & continue

    • break: In the body of any loop statement , All available break Control the flow of the cycle ,break Used to force out of the loop , Do not execute the remaining statements in the loop
    • continue: Used in the body of a circular statement , Used to terminate a cycle process , That is to skip the statement that has not been executed in the loop body , Then, the next decision on whether to execute the loop
    • About goto keyword
      • goto Keywords often appear in programming languages , Even though goto Is still Java A reserved word of , When not formally used in language ,Java No, goto, However, in break and continue These two keywords can still see some goto Shadow , That is, labeled break and continue
      • label : An identifier followed by a colon , for example :lable:
      • Yes Java For example, the only place to use a tag is before the loop statement , And the only reason to set the label before the loop is , We want to nest another loop in it , because break and continue Keywords usually break only the current loop , But if used with a label , They will interrupt to the place where the label exists
        int count = 0;
        outer:for(int i=101;i<150;i++){
          for(int j=2;j<i/2;j++){
            if(i%j==0){
              continue outer;
            }
          }
        }
        

7. Methods,

  • What is method

    • Java Method is a set of statements , Together they perform a function
      • A method is an ordered combination of steps to solve a class of problems
      • Methods are contained in classes or objects
      • Method is created in the program , Quoted elsewhere
    • Principles of design methods : The purpose of method is function block , It's a collection of statement blocks that implement a function , When we design methods , It's best to keep the atomicity of the method ( A method can only accomplish one function , This is good for later expansion )
  • Method overloading

    • Overloading is in a class , Have the same function name , But functions with different parameters
    • Overloaded rules
      • The method name must be the same
      • Parameter list must be different ( The number is different. 、 Different types 、 The parameters are arranged in different order )
      • The return types of methods can be the same or different
      • It's not enough to be an overload of a method just because the return type is different
    • Theory of realization
      • Same method name , The compiler will call the method according to the number of arguments 、 Type and so on to match one by one , To choose the corresponding method , If the match fails, the compiler will report an error
  • Command line arguments

    • A message passed to a program when it runs , This depends on passing command line arguments to main() Function implementation
  • Variable parameters

    • JDK5 Start ,Java Support passing variable parameters of the same type to a method
    • In the method declaration , Add an ellipsis after the specified parameter type (...)
    • Only one variable parameter can be specified in a method , It must be the last parameter of the method , Any ordinary parameter must be declared before it
  • Method call

    • Static methods
    • Non static methods
    • Formal parameters and actual parameters
    • Value passing and reference passing
    • this keyword

8. Array

  • Array Overview

    • An ordered set of data of the same type
    • Arrays describe several data of the same type , Arrange and combine in a certain order
    • among , Each data is called an array element , Each array element can be accessed by a subscript
  • Array declaration & establish

    • Default initialization of arrays : An array is a reference type , Its elements are equivalent to instance variables of a class , So once the array is allocated space , Each of these elements is also implicitly initialized in the same way as instance variables
    // Statement 
    int[] numbers;
    int numbers[];
    // establish 
    int[] numbers = new int[10];
    int[] numbers = new int[]{1,2,3,4,5};
    // Get array length 
    int count = numbers.length;
    
    • The four basic properties of an array are special
      • Determine the length , Once created, the size cannot be changed
      • Its elements must be of the same type
      • The elements in an array can be of any data type , Including basic types and reference types
      • Array variables are of reference type , An array can be seen as an object , Each element in the array is equivalent to the member variable of the object
      • An array itself is an object ,Java The object is in the heap , So arrays hold the original type or other object types , The array object itself is in the heap
  • Memory analysis

    • Java Memory analysis
      • Pile up
        • Deposit new Objects and arrays of
        • It can be shared by all threads , No other object references will be stored
      • Stack
        • Store basic variable types ( Contains the specific values of this basic type )
        • Variables that refer to objects ( Will store the specific address of this reference in the heap )
      • Method area
        • It can be shared by all threads
        • It contains all of class and static Variable
  • Using an array

    • for loop
    • For-Each
      int[] numbers = {1,2,3,4,5};
      for(int i : numbers){
        System.out.println(i);
      }
      
    • Array as method input parameter
    • Array as return value
  • Multidimensional arrays

    • Multidimensional arrays can be called arrays of arrays , For example, a two-dimensional array is a special one-dimensional array , Each of its elements is a one-dimensional array
    • Two dimensional array
      // Array a You can think of it as an array of two rows and five columns 
      int a[][] = new int[2][5];
      // Array b It can be regarded as an array of two rows and three columns 
      int b[][] = {{1,2},{3,4},{5,6}};
      
  • Arrays class

    • Array help class
  • Sparse array

    • Definition
      • When most of the elements in an array are 0 Or an array of the same value , You can use a sparse array to hold the array
    • How to deal with sparse arrays
      • A record array consists of several rows and columns , How many different values
      • Record elements, rows, columns and values with different values in a small array , To reduce the size of the program
    • Here's the picture , On the left is the original array , On the right is a sparse array
       Sparse array

9. object-oriented programming -OOP

  • Initial object orientation

    • A class is an abstraction of a transaction , Object is a concrete instance
  • Three characteristics of object-oriented

    • encapsulation
      • Programming requires high cohesion 、 Low coupling , High cohesion means that the internal data operation details of a class are completed by themselves , External interference is not allowed , Low coupling is exposing only a few methods for external use
      • advantage
        • Improve the security of the program , Protection data
        • Hide the implementation details of the code
        • Unified interface
        • Improve the maintainability of the system
    • Inherit
      • The essence of integration is the abstraction of a certain batch of classes , In order to achieve better modeling of the real world
      • extends It means ” Expand “, A subclass is an extension of a parent
      • JAVA There is only single inheritance , No more inheritance
      • Inheritance is a relationship between classes , besides , There are also dependencies between classes 、 Combine 、 Polymerization, etc.
      • Two classes of inheritance relationship , One is a subclass ( Derived class ), One is the parent class ( Base class ), Subclass inherits parent , Use keywords extends To express
      • Between the child and the parent , In a sense, it should have "is a" The relationship between
      • object: The parent of all classes
      • By final Modified classes cannot be inherited
        /*
          Ctrl+H  You can view the inheritance relationship of the class 
          Alt+Insert  Quickly create construction 、 Attribute method 
          Ctrl+Alt+ The click of a mouse   Jump to implementation 
        */
        public class Person{
          public void say(){
            System.out.println("Hello World")
          }
        }
        
        public class Chinese extends Person{
        
        }
        
        public static void main(String[] args){
          new Chinese().save();
        }
        
      • super/this
        • Call this class & The constructor of the parent class , Must be on the first line
        public class Person(){
          protected String name="parent";
        }
        public class Chinese extends Person{
          private String name="lvfeng";
          public void test(string name){
            // Method parameters 
            System.out.println(name)
            // The field of the current class 
            System.out.println(this.name)
            // Fields of the parent class 
            System.out.println(super.name)
          }
        }
        
      • Method rewriting
        • You can only override non static public Method
        public class Person(){
          public void say(){
            System.out.println("Hello World")
          }
        }
        public class Chinese extends Person{
          @override
          public void say(){
            System.out.println("Hello World")
          }
        }
        
    • polymorphic
    • instanceof
      • Reference type conversion
      if(chinese instanceof person){
        return " Father and son ";
      }
      
  • Code block

    {
      /*
         Anonymous code block : Execute after static code block and before constructor 
      */
    }
    
    static {
      /*
         Static code block : Constructor is executed before and only once 
      */
    }
    
    // Static import package 
    import static java.lang.Math.random;
    public static void main(String[] args){
      System.out.println(random());
    }
    
  • abstract class

    • abstract Modifiers can be used to modify methods or classes , If you modify a method, the method is an abstract method , If the modifier class is an abstract class
    • There can be no abstract methods in an abstract class , But a class with abstract methods must be declared as an abstract class
    • Abstract classes cannot use new Keyword to create it , It is used to let subclasses inherit
    • Abstract methods only have the declaration of methods , There is no way to achieve , It uses subclasses to implement
    • Subclass inherits abstract class , You must implement abstract methods that the abstract class does not implement , Otherwise, the subclass should also be declared as an abstract class
      public abstract class Action{
        public abstract void go();
      }
      
      public class Child extends Action{
        @override
        public void go(){
      
        }
      }
      
      public abstract class Child2 extends Action{
        public abstract void go();
        public void run(){
          System.out.println("Hello World");
        }
      }
      
      public static void main(String[] agrs){
        Action action = new Child();
        action.go();
      }
      
  • Interface

    • Interface is specification , It defines a set of rules or constraints
    • The essence of an interface is a contract , Like the law , It's worked out and everyone will abide by it
    • OO The essence of , It's the abstraction of objects , The best way to do this is through interfaces
    • All definitions in the interface are actually abstract public abstract
    • The class that implements the interface , All methods in the interface must be implemented
      public interface IAction{
        // static const :public static final
        int AGE=99;
        void go();
      }
      
      public interface IAction1{
        void run();
      }
      public class Action implements IAction,IAction1 {
        @override
        public void go(){
          System.out.println("Hello World");
        }
      
        @override
        public void run(){
          System.out.println("Hello World");
        }
      }
      

10. abnormal

  • Exception Architecture

    • Checking abnormality : Exceptions caused by user errors or problems , The program cannot foresee , For example, open a file that doesn't exist
    • Runtime exception : Runtime exceptions are exceptions that may be avoided by programmers , Contrary to inspection abnormality , Runtime exceptions can be ignored at compile time
    • error : Mistakes are not exceptions , It's a problem of getting out of program control , Errors are often ignored in code , For example, when the stack overflows, an error occurs , They can't be checked when compiling
    • Java Treat exceptions as objects , And defined a base class java.lang.Throwable As the base class for all exceptions
    • stay Java Many exception classes have been defined in , These anomaly classes are divided into two categories , error Error And exceptions Exception
      • Error
        • Error Class object by Java The virtual machine generates and throws , Most of the errors have nothing to do with what the coder is doing
        • Java Virtual machine running error (Virtual MachineError), When JVM Does not appear when there are memory resources needed to continue the operation OutOfmemoryError, When these exceptions occur ,Java Virtual machines usually choose thread termination
        • And it happens when a virtual machine tries to execute an application , If the class definition is wrong (NoClassDefFoundError)、 link error (LinkageError), These errors are not traceable , Because they're outside the control and processing power of the application , And most of the situations that are not allowed when the program is running
      • Exception
        • stay Exception There is an important subclass in the branch RuntimeException( Runtime exception )
        • These exceptions are usually caused by program logic errors
      • Error and Exception
        • Error Usually a catastrophic fatal mistake , It's something the program can't control and handle , When these exceptions occur ,Java Virtual machines generally choose to terminate threads
        • Exception Usually it can be processed by the program , And in the program should try to deal with these exceptions
  • Java Exception handling mechanism

    • Throw an exception
    • Grab exception
  • Handling exceptions

    • Five keywords of exception handling
    • try catch finally throw throws
      • throw: Actively throw an exception
      public void scal(){
        int a = 10
        int b = 0;
        if(b==0){
          throw new ArithmeticException();
        }
      }
      
      • throws: Running up is abnormal , Handle exceptions in the upper layer
      public void scal() throws ArithmeticException{
        int a = 10;
        int b = 0;
        int c = a / b;
      }
      
    • Catch multiple exceptions , To write catch It needs to be written from an early age
    • Ctrl+Alt+T Quickly generate exception capture blocks
  • Custom exception

    • Java The built-in exception class describes most of the exceptions that occur during programming , besides , Users can also customize exceptions , User defined exception , Just inherit Exception The class can
    • Use custom exceptions in programs , It can be divided into the following steps
      • Create a custom exception class
      • Pass in the method throw Keyword throws an exception object
      • If the exception is handled in the method that currently throws the exception , have access to try-catch Statement to capture and process , Otherwise, pass... At the declaration of the method throws Keyword indicates the exception to be thrown to the method caller , Proceed to the next step
      • Catch and handle exceptions in the caller of the exception method
    public class MyException extends Exception{
      private int _numbers;
      public MyException(int numbers){
        _numbers = numbers;
      }
      @override
      public String toString(){
        return "MyException{"+_numbers+"}";
      }
    }
    

11. Java Common classes

  • Inner class

    • Definition
      • Define a complete class inside a class
      • One Java There can be more than one class of the same level class class , But only one public class
    • characteristic
      • Independent bytecode files can be generated after compilation
      • The inner class has direct access to the private members of the outer class
      • It can provide necessary internal functional components for external classes
    • Member inner class
      • Definition : Then the internal definition of the class , And instance variables 、 Method same level
      • A real column part of an external class
      • When the external class and internal class properties have the same name , Give priority to the properties of the inner class
      • Member inner classes cannot define static members
      • Member inner classes can contain static constants final
        public class Outer{
          private String name;
          private int age;
        
          class Inner{
            private String name;
            private String address;
            private String phone;
            public void show(){
              // Print the of the inner class name, If the inner class does not have an outer class that this member directly accesses 
              System.out.println(name);
              // When duplicate names appear , Use the following method to call the properties of the external class 
              System.out.println(Outer.this.name);
            }
          }
        }
        
        public static void main(String[] args){
          Outer outer = new Outer();
          Inner inner = outer.new Inner();
          Inner inner = new Outer().new Inner();
          inner.show();
        }
        
    • Static inner class
      • Definition :
        • Independent of external class objects , It can be created directly or accessed through the class name , Declarable static members , Equivalent to an external class , Its level is the same as the external class
        • Static inner classes cannot directly use the properties of outer classes , Only through New Or set the properties of the external class to static , Because static inner classes are created earlier than non static properties of outer classes , So the static inner class can't get
        public class Outer{
          private String name;
          private int age;
        
          static class Inner{
            private String address;
            private String phone;
            private static int count;
            public void show(){
              Outer outer = new Outer();
              System.out.println(outer.name);
        
              // Accessing non static members of static inner classes 
              System.out.println(phone);
              // Access static members of static inner classes 
              System.out.println(Inner.count);
            }
          }
        }
        
        public static void main(String[] args){
          Outer.Inner inner = new Outer.Inner();
          inner.show();
        }
        
    • Local inner classes
      • Definition : Defined in the method of the external class , The scope of scope and the scope of creating objects are limited to the current method
      • Local inner classes cannot use access modifiers
      • Local inner classes cannot use static properties , But you can use static constants final static
      • When a local inner class accesses a local variable in an external class method , Because there is no guarantee that the life cycle of a variable is the same as itself , The variable must be decorated with final, But in jdk1.8 There is no need to add final Modifier , because jdk1.8 Default added
        public class Outer{
          private String name;
          private int age;
          public void show(){
            String address;
        
            // Define local inner classes 
            class Inner{
              private String phone;
              private String email;
              public void show2(){
                // Access external class properties 
                System.out.println(name);
                // Access internal class properties 
                System.out.println(phone);
                // Access the properties of external methods ,jdk1.7 The variable must be a constant ,jdk1.8 Automatic addition final
                System.out.println(address);
              }
            }
        
            Inner inner = new Inner();
            inner.show();
          }
        }
        public static void main(String[] args){
          new Outer().show();
        }
        
    • Anonymous inner class
      • Definition : Local inner classes without class names ( All features are the same as local inner classes )
      • You must inherit a parent class or implement an interface
      • Defining classes 、 Implementation class 、 Create a syntax merge of objects , Only one class object can be created
      • advantage : Reduce the amount of code
      • shortcoming : Poor readability
        public interface IOuter{
          void service();
        }
        public static void main(String[] args){
          // Local inner classes 
          class Inner implements IOuter{
            @override
            public void service(){
              System.out.println("Hello World");
            }
          }
          IOuter outer = new Inner();
          outer.service();
        
          // Anonymous inner class 
          IOuter outer = new IOuter(){
            @override
            public void service(){
              System.out.println("Hello World");
            }
          }
          outer.service();
        }
        
  • Object

    • Definition
      • Superclass 、 Base class , The direct or indirect parent of all classes , At the top of the inheritance tree
      • Any class , If not written extends Show inheriting a class , They all default to direct inheritance object, Otherwise, it is indirect inheritance
      • Object Methods defined in class , It's a method that all objects have
      • Object Type can store any object
        • As a parameter , Can receive any object
        • As return value , Can return any object
    • Common methods
      • getClass
        • return :Class
        • Definition : Returns the actual object type stored in the reference
        • application : It is usually used to judge whether the objects actually stored in two references are consistent
        public class Student{
          public String name;
          public int age;
        }
        public static void main(String[] args){
          Student stu1 = new Student();
          Student stu2 = new Student();
          // Judge stu1 and stu2 Are they of the same type 
          Class c1 = stu1.getClass();
          Class c2 = stu2.getClass();
          if(c1 == c2){
            return true;
          }else{
            return false;
          }
        }
        
      • hashCode
        • return :int
        • Definition
          • Returns the hash code value of the object
          • The hash value is used according to the address or string or number of the object hash The algorithm works out int Type value
        • Generally, the same object returns the same hash code
        • application : Determine whether the memory address of the object is the same
        public class Student{
          public String name;
          public int age;
        }
        public static void main(String[] args){
          Student stu1 = new Student();
          Student stu2 = new Student();
          int stu1 = stu1.hashCode();
          int stu2 = stu2.hashCode();
          if(stu1 == stu2){
            return true;
          }else{
            return false;
          }
        }
        
      • toString
        • return :String
        • Definition
          • Returns the string representation of the object ( form )
          • Methods can be covered according to program requirements , Such as : Display the value of each attribute of the object
        public class Student{
          private String name;
        
          // rewrite Object Of toString()
          @override
          public String toString(){
            return "Hello World";
          }
        }
        public static void main(String[] args){
          // Returns the full name of the object [email protected]+hashCode(16 Base number )
          String stu1 = stu1.toString();
          String stu2 = stu2.toString();
        }
        
      • equals
        • return :boolean
        • Definition
          • Compare the addresses of two objects
          • Can be rewritten , Compare the contents of two objects
        • equals and == The difference between
          • Basic data type :== It's worth
          • Reference data type :== Compare the memory address of the object
          • because Java Only value passing , about == Come on , Whether comparing basic data types or reference data types , The essence of comparison is value , Only the value of the reference type variable is the address of the object
          • equals Variables that cannot be used to determine the basic data type , You can only judge whether two objects are equal
        public class Student{
          private String name;
        
          @override
          public boolean equals(Object obj){
            if(this == obj){
              return true;
            }
            if(obj == null){
              return false;
            }
            // Determine whether the types of objects are the same 
            <!-- if(this.getClass() == obj.getClass()){
              return true;
            } -->
            if(obj instanceof Student){
              Student stu = (Student)obj;
              if(this.name == stu.name){
                return true;
              }
            }
            return false;
          }
        }
        public static void main(String[] args){
          Student stu1 = new Student();
          Student stu2 = new Student();
          System.out.println(stu1.equals(stu2));
        }
        
      • finalize
        • When the object is determined to be a garbage object , from JVM Call this method automatically , To mark junk objects , Enter the recycle queue
        • Garbage object : When no valid reference points to this object
        • Garbage collection : from GC Destroy garbage objects , Free up data storage space
        • Automatic recycling mechanism :JVM Out of memory , Recycle all objects at once
        • Manual recycling mechanism : Use System.gc() notice JVM Carry out garbage collection
        public class Hello{
          @override
          protected void finalize() throws Throwable{
            System.out.println(" Object heap GC Recycled ");
          }
        }
        public static void main(String[] args){
          Hello hello = new Hello();
          // Garbage collection , Executing this statement does not execute the of the object finalize
          System.gc();
          
          new Hello();
          // Garbage collection , Executing this statement executes the of the object finalize
          System.gc();
        }
        
  • Packaging

    • Definition
      • The reference data type corresponding to the basic data type
      • Basic data types can only operate on operators , No, Object Corresponding method , The wrapper class is the reference data type corresponding to the basic data type , You can make basic data types use Object Corresponding method
      • The complete definition is to wrap the basic data type into an object , Make it a reference type , When storing data, it will also be stored from the stack to the heap
    • Object Can unify all data , The default value for wrapper classes is null
    • Reference type corresponding to basic data type
      • byte:Byte
      • short:Short
      • int:Integer
      • long:Long
      • float:Float
      • double:Double
      • boolean:Boolean
      • char:Char
  • Type conversion and Boxing 、 Unpacking

    • Basic data type : Store in a stack
    • Reference data type : Store in a pile
    • Packing : Convert basic data type to reference data type , The data is stored in the heap by the stack
    • Unpacking : Convert reference data type to basic data type , The data is stored on the stack by the heap
      /*
        JDK1.5 Before 
      */
      // Packing 
      int num = 18;
      Integer i1 = new Integer(num);
      Integer i2 = Integer.valueOf(num);
      // Unpacking 
      num = i1.intValue();
      
      /*
        JDK1.5 after , Provide automatic packing and unpacking 
      */
      // Packing 
      Integer i1 = num;
      // Unpacking 
      num = i1;
      
  • Integer buffer

    • Java The budget created 256 A commonly used integer wrapper type object
    • in application , Edit the created object
    • Integer buffer range -128——127
      Integer i1 = new Integer(100);
      Integer i2 = new Integer(100);
      // The current result returns false, because Integer Is a reference type ,i1 and i2 Different memory references 
      System.out.println(i1 == i2);
      
      Integer i1 = 100; //  Equate to  Integer i1 = Integer.valueOf(100);
      Integer i2 = 100;
      
      // The current result returns true, Because the above code performs automatic boxing (valueOf) The operation of ,valueOf Will read from the cache -127 To 128 The numerical , Because it has been instantiated before , therefore i1 and i2 The memory points to the same 
      System.out.println(i1 == i2);
      
      Integer i1 = 200;
      Integer i2 = 200;
      // The current result returns false, Even walking is valueOf Method , but 200 The integer buffer has been exceeded , So it will execute new Integer() Re create a new object 
      System.out.println(i1 == i2);
      
  • String class

    • Strings are constants , It cannot be changed after creation
    • String literals are stored in string pools , Can be Shared , The string is in the method area
      • Java Memory storage area type
        • Pile up : Store reference types
        • Stack : Basic storage type
        • Method area : class 、 Method 、 Static variables + Constant 、 String pool
      /*
         Produce an object , String pool 
         Create a process : First open up space in the stack , Then judge whether there is... In the string pool Hello, If there is a return memory address , Otherwise, the address will be returned after creation 
      */
      String str = "Hello";
      
      /*
         Produce two objects , Pile up 、 Each pool stores one 
         Create a process : First open up space in the stack , Then judge whether there is... In the string pool Hello, If yes, do nothing , On the contrary, it opens up space , Finally, open up space in the heap to create an empty object , But the memory address in the heap is the address in the string , Then return the address in the heap 
      */
      String str = new String("Hello");
      
    • Variable string
      • StringBuffer: Variable length string ,JDK1.0 Provide , Slow operation efficiency , Thread safety
      • StringBuilder: Variable length string ,JDK5.0 Provide , It's very efficient , Thread unsafe
      • And String The difference between
        • Efficient than String high
        • Than String Save memory
      StringBuffer sb = new StringBuffer();
      sb.append(" Append string ");
      System.out.println(sb.toString());
      
      StringBuilder sb = new StringBuilder();
      sb.append(" Append string ");
      System.out.println(sb.toString());
      
      // verification StringBuilder Efficiency is higher than StringBuffer
      long start = System.CurrentTimeMillis();
      String string="";
      for(int i=0;i<99999;i++){
        string+=i;
      }
      long end = System.CurrentTimeMillis();
      System.out.println(" when :"+(end-start));
      
      long start = System.CurrentTimeMillis();
      StringBuffer string = new StringBuffer();
      for(int i=0;i<99999;i++){
        string.append(i);
      }
      long end = System.CurrentTimeMillis();
      System.out.println(" when :"+(end-start));
      
      long start = System.CurrentTimeMillis();
      StringBuilder string = new StringBuilder();
      for(int i=0;i<99999;i++){
        string.append(i);
      }
      long end = System.CurrentTimeMillis();
      System.out.println(" when :"+(end-start));
      
  • BigDecimal class

    • double and float: Approximate value storage , There will be deviation in the operation
    • When accuracy is required, it is necessary to use BigDecimal
      //double and float Stored in memory is an approximate value , So the calculated result will have deviation 
      double d1 = 1.0;
      double d2 = 0.9;
      //d3 Is not the same as 0.1, It is 0.999999998
      double d3 = d1 - d2;
      
      BigDecimal n1 = new BigDecimal("1.0");
      BigDecimal n2 = new BigDecimal("0.9");
      // Perform subtraction 
      BigDecimal n3 = n1.subtract(n2);
      /*
         Add :add
         Multiplication :multiply
         division :devide
      */
      
  • Date

    • Date Represents a specific moment , Accurate to milliseconds .Date Most of the methods in the class have been Calendar Class
  • Calendar

    • Provides methods to get and set various calendar fields
    • Construction method :protected Calendar(): Because the modifier is protected, So you can't create the object directly
      // Create objects 
      Calendar calendar = Calendar.getInstance();
      
  • SimpleDateFormart

    • SimpleDateFormart It's a concrete class that formats and parses dates in a locale related way
    • format ( Date to text ), analysis ( Text to date )
      SimpleDateFormart sdf = new SimpleDateFormart("yyyy-MM-dd HH:mm:ss");
      Date date = new Date();
      String d = sdf.formart(date);
      
  • System

    • System class , It is mainly used to obtain system attribute data and other operations , Constructor private

12. Collections framework

  • Concept

    • Object's container , It defines the common operation methods of multiple objects , The function of array can be realized
    • The difference with arrays
      • Array length is fixed , The set length is not fixed
      • Arrays can store basic types and reference types , A collection can only store reference types
      • If you add a basic data type to the collection , Packing will be done automatically , Generate the corresponding wrapper class of the basic type
  • Collection A collection of systems

    Collection
    • characteristic
      • Hierarchical interface
      • Represents a set of objects of any type , disorder 、 No subscript 、 Can't repeat
    • Common methods
      • add: Add an object to the collection
      • addAll: Add all objects of a collection to this collection
      • clear: Empty all objects in the collection
      • contains: Check whether the collection contains objects
      • equals: Compares whether the collection is equal to the specified object
      • isEmpty: Determines if the set is empty
      • remove: Removes the specified object from the collection
      • size: Returns the number of elements in the collection
      • toArray: Convert a collection to an array
      • iterator: Returns the iterator that iterates over the elements of this collection
      Collection collection = new ArrayList();
      
      collection.add("Hello");
      collection.remove("Hello");
      collection.clear();
      collection.size();
      
      for(Object obj : collection){
        System.out.println(obj);
      }
      // It is not allowed to use... During iteration Collection Removal method 
      Iterator item = collection.iterator();
      while(item.hasNext()){
        item.remove();
        System.out.println(item.next());
      }
      
      collection.contains("Hello");
      
  • List

    • characteristic : Orderly 、 With subscript 、 Elements can be repeated
    • Inherit Collection All iterators , however List Has its own iterator ListIterator
      • ListIterator: List iterator , Allows programmers to traverse the list in any direction , You can add... During the iteration 、 modify 、 Remove elements
      List list = new ArrayList();
      list.add("Hello");
      ListIterator iterator = list.listIterator();
      // Before and after 
      while(iterator.hasNext()){
        int index = iterator.nextIndex();
        Object item = iterator.next();
      }
      
      // From back to front 
      while(iterator.hasNext()){
        int index = iterator.previousIndex();
        Object item = iterator.previous();
      }
      
    • List Implementation class
      • ArrayList
        • Array structure implementation , Quick query 、 Add or delete slowly
        • JDK1.2 edition , It's very efficient , Thread unsafe
        • characteristic
          • After adding elements to the collection, the default capacity is 10, No element was added to the collection. The default capacity is 0
          • elmentData: An array of elements
          • add:
        ArrayList arrayList = new ArrayList();
        Iterator iterator = arrayList.iterator();
        while(iterator.hasNext()){
          System.out.println(iterator.next());
        }
        
        ListIterator iterator = arrayList.listIterator();
        while(iterator.hasNext()){
          System.out.println(iterator.next());
        }
        while(iterator.hasPrevious()){
          System.out.println(iterator.previous());
        }
        
      • Vector
        • Array structure implementation , Quick query 、 Add or delete slowly
        • JDK1.0 edition , Slow operation efficiency 、 Thread safety
      • LinkedList
        • Linked list structure implementation , Additions and deletions quickly 、 Slow query
  • Generic

    • Concept
    • Generic classes
    • Generic interface
    • Generic methods
    • Method set
  • Set

  • HashSet

  • TreeSet

  • Map

  • HashMap

  • TreeMap

  • Collection Tool class

13. I/O

14. Multithreading

15. Network programming

16. GUI Programming

17. Annotation and reflection

18. JUC Concurrent programming

19. JVM Into research

copyright notice
author[IService],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270411418068.html

Random recommended