• 1. System. Out. Print/printIn difference printIn a newline
  • 2. Classes and objects

1. The parent class is abstract, and the child class is concrete. The child class automatically obtains the parent class method. It is also possible to override (subclasses redefine inherited methods to change or extend the method behavior).

2. Class: instance variable + method

3. Classes are not objects. Classes are models used to create objects

  • 1. There are two types of variables: Primitive primary datatype and reference.

    There are 8 primary data types for primitive: Byte 8 bits (-128 to 127), short 16 bits, INT 32 bits, long 64 bits (a group of four)—– and float 32 bits, double 64 bits —— and Boolean and CHAR 16 bits (0-65535)

    3. Short B =1; Int a = b). Int b=1; Short a=b A small cup cannot hold a large cup. A large cup can hold the contents of a small cup, but will lose precision. Float can be converted to double —– double cannot be converted to String to float example: new BigDecimal(String.valueof (double a)).floatValue() Example: int a=1; long x=a; (compiled) Example: long a=1; int x=a; Int x=(int) a; The compiler cuts the value to an int

    4. There are actually no object variables, only variables that refer to objects. It’s like a pointer. Dog myDog=new Dog(); The virtual machine allocates space to the myDog reference variable and sets the type to Dog. Use this reference variable to control the Dog object on the heap. Equals is the concatenation of reference variables and objects. —- so myDog is just a pointer (reference) not an actual object

5. If the object is not referenced, it is recycled on the heap. Dog myDog=new Dog(); MyDog = null; — New Dog() is recycled

6. Array –Dog[] pets=new Dog[7]; pets[0]=new Dog(); pets[1]=new Dog(); —— See the following figure for each relationship.

  • Methods and instance variables

    1. Instance variables are variables declared in a class (global variables) (with default values), and local variables are variables in a method (with no default values).
    2. Instance variables always have default values. Int char, etc. is 0, booleans is false, and object references are null. Null represents an object that has no operation. Null is a reference, not an object.
    3. == and equals (). == is used to determine whether an object is being referenced. Equals () determines whether two objects are equal in meaning. The primary data type is simply ==.
    4. X++ and ++X X++ is the first thing to do, plus plus X is the first thing to do. x=0; z=x++; z=0,x=1;
    5. HashCode () and equals (). HashCode is used to reduce the cost of finding, equals is the truth, etc. HashCode is equal if two objects are equal. HashCode equivalent is not necessarily equal.
  • 5. Java API

    1. ArrayList is not an array but a class in the Java function library, and List is an interface that implements it. Remove (Object elem) Returns true if it matches the Object parameter. //indexOf (Object elem) Returns the Object parameter index or -1, and whether the element position//isEmpty () has a value
    2. ArrayList and array. ① The array must be initialized to a specified size. New String[2]②ArrayList specifies the type List
  • 1. Inheritance: Subclasses inherit instance variables and methods from their parent class public (not privite). A subclass can override a parent class method.

    2. Inheritance significance: ① avoid duplicate program code ② define a common protocol (inheritance ensures that all classes under a parent class have all methods held by the parent class).

    3. Polymorphism: The reference type can be a parent of the actual object class.

    Animal a=new Dog(); Animal[] animal=new Animal[2]; animal[0]=new Dog(); animal[1]=new Cat(); animal[0].eat(); animal[1].eat(); Call cat eat and dog eat respectively. privite void chi(Animal animal){ animal.eat(); }Copy the code

    chi(cat); chi(dog); It can be executed, as long as it is a subclass, calling cat eat and dog eat respectively.

    4. Inheritance hierarchy, there is no limit, generally not very deep, about 2 layers, less inheritance tree is reasonable.

    5. Class is not inherited: ① access control, class only public or not declared. Undeclared class A{} can only be inherited by the same package. ②final, final means that it is the end of the inheritance tree and cannot be inherited. ③ Let the class have only privite constructors

    6. The finial tag class indicates that the class cannot be inherited (all methods cannot be overridden), and the tag method indicates that the method cannot be overridden.

    7. Overwrite rules: ① The parameters must be the same and the return values are compatible. (return the same value or subclass) ② Cannot lower the access privileges of the method (public privite)

    8. Method overload: same method name, different parameter. The return type can be different depending on the parameter. The access permission can be changed by public privite. ③ It has nothing to do with inheritance polymorphism and so on.

    9. Abstract. Abstract classes cannot be new (initialized), cannot create instances of the class, but can be inherited. Abstract classes have no purpose, no value, and no purpose except to be inherited. —- Why abstract? New Animal (); We don’t know what Animal looks like, we only have some common effects, so we have to keep Animal from being created, we have to abstract it, we have to subclass it into a concrete class.

    10. Abstraction versus concreteness. Classes that are not abstract are concrete classes. An inherited tree, animals, mammals, primates should be declared as abstract humans, and golden monkeys as concrete.

    11. Abstract methods. Abstract methods mean that the class must be inherited and subclasses must be overridden (all abstract methods must be implemented). An abstract method must also be an abstract class. BaseActivity: public abstract void initView(); ★ No specific method, only declare a name directly used;

    12. The benefits of abstraction: Polymorphism. The nice thing about polymorphism is that all subclasses have those abstract methods. You want to use a parent class as a method parameter, return type, or array type.

    13. An abstract method has no content. It simply flags the presence of polymorphism. This means that the first concrete class in the inheritance tree must implement all the abstract methods. In other words, if you declare abstract, you don’t need to implement the parent class’s abstract methods, and let the subclasses implement the parent class’s abstract methods together.

    14. The Object. ① Equals (Object O)②getClass() initializes what Object – what type ③hashCode() returns a unique hash ID④toString().

    15. The compiler does not care about the type of the object. When you put Dog on Object, it becomes Object instead of Dog. Object o=new Dog(); O cannot execute Dog’s methods. If you want to turn Dog back, you have to turn hard. Dog d=(Dog)o; ★★★ Determine the type of instanceof before strong transfer. if(o instanceof Dog) Dog d=(Dog)o;

    16. The interface interface. — All methods are public and abstract. Bring their own public + the abstract.

    17 interface is a higher level of abstraction of the attributes and behavior of things, closed to modify, to expand development.

    18. Super calls the superclass method.

  • 7. Constructors and garbage collectors 1. Programmers care about an area of memory: the stack. Heap: Holds all objects. Stack: Methods and local variables. Dog a=new Dog(); a.getA(111); A reference, getA() method, 111 local variables are all on the stack (in stack blocks). The new Dog () object is on the heap.

    2. Local variables are on the stack. What about instance variables? Instance variables are on the heap. Instance variables are on the object that they’re on, and the object is on the heap. So the instance variable is on his object’s heap.

    Constructor. The only way to call the constructor is to create a new class, new. Dog a=new Dog(); It calls the Dog constructor (which has no arguments). By default, the Dog constructor comes with no arguments. The arguments to the constructor must be different (of type and order) as long as one of them is different.

    4. The constructor name must have the same name as the class and have no return type. When a new object is created, all inherited constructors are executed – all constructors of the parent class are executed. Because subclasses might call super or inherit methods based on the state of the parent class.

    5. The first thing a constructor does when it executes is execute the constructor of its parent class all the way up to the topmost Object. This process is called a constructor chain. — A child has to be born after its father.

    6. Super () calls the parent constructor and this () calls its own constructor. This () can only be in the constructor and must be the first sentence. You can only choose between this() and super().

    7. The life cycle of an object depends on its references, and objects without references become recyclable. Possible cases: references to other objects; = null; The reference is out of scope.

  • 1. Static static keywords can mark methods that do not require an instance. —–> No object/cannot new/ cannot initialize self understand: static, static state. Global is shared with all other classes and is not affected by variables or anything else. Like tools, most tools and methods are static.

    2. Static functions: math.min (1,100); The math.min () method, which only compares the size of two values passed in, has nothing to do with any other Math method or instance variable in the Math class, so it can be static. Math.min() can be called directly to math.min () instead of new Math, which wastes space by creating Math objects. —— so in some tool classes, tool methods can be static, such as fetching time, converting dp, px, etc.

    3. Static methods are not intended to be initialized. Abstract classes cannot be instantiated. So how can a non-abstract class not be initialized? The —- constructor is declared as a private privite. Math’s constructors are private, so Math cannot create instances.

    4. Static classes: In general, you should not use static to modify classes. Unless it’s an inner class (a class built inside a class).

    5. Static methods cannot call non-static variables. Static methods are class-independent methods that cannot call instance variables in a class.

    6. Static methods cannot also call non-static methods. —— can call static methods.

    7. Static variables: They can change, but their value is the same and shared across all instances. True global variables. For example, when class A calls the static variable AAA, the value is set to 2. When class B calls aaa, the value also changes to 2.

    8. Static variables are initialized before any static methods of the class are executed.

    9. Final: A variable marked final means that it will not change after initialization. Constant.

    10. Static final variables are constants. Public static final PI = 3.14; – public: global | | static don’t have to be new directly with | | final can’t change.

    11. Constant names are generally capitalized.

    12.★★★ Final variables cannot be changed, final methods cannot be overwritten, and final classes cannot be inherited

    A constant marks a variable as static and final at the same time.

    Math.random() generates a random number 0-1– math.abs () absolute value — math.round () –min, Max, etc

    15. Wrapper around the Primitive primary data type. If you want to treat main data types as objects, use their wrapper (uppercase + full name). Boolean/Integer, Float, etc. List< Integer> a=new ArrayList();

    String. Format (“%,d”,1000); %: indicates that the following parameters are put here; “, “stands for” separated “. D stands for decimal integer. Format (“I have %.2f bug”,12345.6789) > I have 12345.68 bug ==%: indicates that the following argument is put here –. ——%d decimal int; % f float; %x byte/short/int/long/BigInteger; %c=%x-BigInteger;

    17. Dates: Use Date to get the current Date and Calendar for the rest. Because Date is a lot of deprecated.

    18.Calendar a=new Calendar(); Calendar is abstract class can’t new can only inherit. To get Calendar, calendar.getInstance (); Call this method to get his subclass.

    The top layer of the inheritance tree is all abstract classes, and the bottom layer is called concrete classes. Abstract classes cannot be created by new, only inherited. BaseActivity: public abstract void initView(); BaseActivity: public abstract void initView(); Interface – public+abstract—- Interface is a higher level of abstraction of attributes and behaviors of things. It is closed to modification and extended development. The interface comes with an abstract, so methods declared in the interface must be overridden and used. The end. void onSuccess(); ★ Static classes: You can’t use static to modify a class. Unless it’s an inner class. ★ Static methods: Mark methods that do not need instances. -> No object/can’t new/ can’t initialize can call its method directly without new a whole class, tool method usually use static mark ★ static variable: ★ Final: variables cannot be changed, methods cannot be overridden, and classes cannot be inherited

  • Exception Handling 1. An Exception is an Exception object. Try {// dangerous action}catch (Exception ex) {// try to recover}

    2. Methods that throw exceptions must declare throws Exception. Methods can catch exceptions thrown by other methods and throw them to the caller.

    Throw new Fileaaaa(); throw new Fileaaaa(); So try first, if that’s okay, try then finally, if you have a problem, then you’re done with that line and you just run catch and then finally.

    try{  
        aaa();  
      }catch(BakingException ex){  
       ex.printStackTrace();  
     }finally{  
       bbb();  
     }  
    Copy the code

    4. Catch can have more than one, throw more than one exception, will see which exception is thrown specific execution where. Exceptions are objects, so they are polymorphic, and can be handled either by throwing a superclass or by throwing subclasses, depending on the situation. You have to go from small to large when you have multiple catches

    5. You can duck exceptions if you don’t want to handle them, but exceptions must be handled. laundry.doLaundry();

  • Serialization and file input \ out

1. Serialization If only your Own Java program needs this data, you can write the serialized object to a file. This is easier to recover and more secure than plain text files. 2. Serialization: Convert an object into a byte stream composed of 01.

FileOutputStream fileOutputStream=new FileOutputStream("MyGame.ser"); ObjectOutputStream OS =new ObjectOutputStream(FileOutputStream); // ObjectOutputStream OS =new ObjectOutputStream(FileOutputStream); // Connect the file to the written object os.writeObject(aaa); // Serialize the object and write os.close(); 3. The serialization interface. Mark interfaces. Purpose: Declare that the class can be serialized. For a class to be serialized, all of its related subclasses must be serializable and inherit from Serializable. 4. In serialized objects, if an instance variable does not need to be serialized, it can be marked transient. (transient String userId;) Purpose: Some variables can only be used during execution, but cannot be stored. FileInputStream fileOutputStream=new FileInputStream(" mygame.ser "); ObjectInputStream OS =new ObjectInputStream(FileOutputStream); Object o=os.readObject(); // Each call reads an object from the OS, order = save order. AAA aaa=(AAA)o; // Convert Object to AAA os.close(); 6. Write String directly to TXT. Just change FileOutputStream to FileWrite. FileWrite fileWrite=new FileWrite("MyGame.txt"); Filewrite. write("aaaaaa"); // write aaa filewrite.close (); 7. Buffered: Instead of writing to the buffer at a time, you can store several items in the buffer and write to it at once. BufferedWriter writer=new BufferedWriter(new FileWrite("MyGame.txt")); writer.write("aaaaaa"); // write to aaa writer.write(" BBB "); writer.write("ccc"); writer.flush(); ** File File =new File(" mygame.txt "); FileRead fileRead=new FileRead(file); BufferedRead read=new BufferedRead(fileRead); // Use the buffer to read while(read.readline ()! =null){ String a= read.readLine(); // loop read a=aaa; a=bbb; a=ccc; } read.close(); String: String a[]=aaa. Split (","); // divide aaa into a listCopy the code
  • Network and Threads 1. A Socket is an object (java.net.Socket) that represents the network connection between two machines. Socket Socket = new Socket (” 196.164.1.102 “, “8080”); // To establish a Socket connection, you must know the IP address and port number.

    2. An address has 65536 ports. 0-1023 is for the system 1024-65535 is available.

    3. Read data (via BufferedRead) :

    Socket Socket = new Socket (" 196.164.1.102 ", "8080"); InputStreamReader stream=new InputStreamReader(socket.getinputSteam ()); BufferedRead read=new BufferedRead(stream); // Use the buffer to read while(read.readline ()! =null){ String a= read.readLine(); // loop read a=aaa; a=bbb; a=ccc; } read.close();Copy the code

    4. Write data to BufferedWriter or PrintWriter (one String at a time)

    Socket Socket = new Socket (" 196.164.1.102 ", "8080"); PrintWriter PrintWriter =new PrintWriter(socket.getOutputSteam()); PrintWriter PrintWriter. Print ("aaa"); // Write dataCopy the code

    5. Threads Threads. Multithreaded, the Java virtual machine quickly switches back and forth between the main thread and other threads until execution is complete. It looks like it’s all happening at the same time.

    6. Each Thread needs a Runnable task to execute. Runnable Runnable Runnable =new MyRunnable(); Thread_runnable =new thread (Runnable); Thread.start (); Which is the normal way to write it:

    Thread thread=new Thread(new Runnable() {
     @Override
      public void run() {
       
      }
      });
     thread.start();
    Copy the code

    7. Thread three states: new Thread → executable (t.start() after the normal state: Thread start will be in the executable and execution of the back and forth switch another situation: blocked state. — Sleep () or the thread scheduler is locked.

    8. The thread scheduler determines the state of a thread and cannot be controlled by code.

    9. The best way to ensure that each thread has a chance to execute (to be more predictable) is to have them periodically sleep (); The sleep method may throw an InterruptedExption exception, so it must be wrapped in a try.

    10. Thread locks: synchronized Use synchronized keywords to decorate methods so that they can only be accessed by a single thread at a time. The next thread can only execute after one thread has finished. This ensures that the data is not cluttered (concurrency) and that the data is 100 when thread A finishes executing. B starts at 100 and performs a change of 200 (parallelism).

    11. Locks are applied to objects, not methods. The object has two methods. Once locked, two threads cannot enter the object (same or different methods) at the same time.

    12. A deadlock. Two threads wait for each other to hold something. It’s stuck. Java has no mechanism for dealing with deadlocks, or even knowing they are deadlocked.

  • Collections versus generics

1. Collection: ArrayList, TreeSet(ordered and not repeated), HashMap (key-value pair storage), LinkedList(frequently added and deleted), HashSet (not repeated, quick lookup), LinkedHashMap (key-value pair storage, can remember insertion order and sort)

1.1 List Repeatable Set Non-repeatable Map key value pair. The key is non-repeatable and the value can be 2. Generics. Generics mean better security. The main purpose of generics is to make collections safer. --T-E (element), etc. Example: List Dog, List Cat, etc. You can use any string, but it is customary to use a single letter, and generally use T except for E for sets. 3. public static<T extends Comparble<? Super T>> void sort(List<T> List) //sort extends Comparble<? Super T> ----T is Comparble<? Super T> (T must implement Comparble) -- Compare the size of Java classes by Comparble. -- -- -? = Multipurpose characters. <? 1. Public static<T extends Comparble<? Super T>> void sort(List<T> List) with 2. Public static<T extends Comparble<T>> void sort(List<T> List) 1. 1. Public <T extends Animal> void sort(List<T> List) 2. Public void sort(List<T> List) Extends Animal> list) These two are the sameCopy the code