"Java Core Volume 1" slowly chew! Read Chapters 3, 4 | 12th Edition

Please add a picture description

remind: The full text is about 6,000 words . It is a relatively simple study note. The knowledge points are basically listed in the form of entries . It should be quite good for checking for omissions and as a memo . If you find it useful, it is recommended to bookmark it. This article includes:

  • Basic programming structure of Java
  • object-oriented programming


Chapter 3 Basic Programming Structure of Java

1. Variables and operations

  • Standard naming : CamelCase naming method, the first letter of each word of the class name is capitalized, such as HelloWrold.

  • The carriage return is not the end of the statement, ;it is.

  • Static member function [p27]

  • Comments : //single-line comments, /* */multi-line comments

  • Basic types : 4 integers (int, short, long, byte), 2 floats (float, double), 1 Boolean (boolean)

  • Hexadecimal representation of floating-point literals [p30]

  • NaN is not a number

  • Floating point is not suitable for financial calculations where rounding errors cannot be tolerated, and the BigDecimal class can be used.

  • char\u0000~\uffff : The char value can be represented by an escape sequence , and \uthe escape sequence will be processed before parsing the code, which is equivalent to text replacement . Java deals with the Unicode character set, 2 code units. [p32] ?

  • boolean : cannot be converted to and from integers.

  • Variables : Java variable names are not limited to English letters [p33]; varthe variable type can be automatically inferred based on the initial value, but you need to pay attention to the java version when using it.

  • final : constant keyword, final int a = 5; public static fanal int a = 5equivalent to a global variable.

  • enumeration : enum Size {SMALL, MID, BIG};

  • Precision and Portability [p36]

  • println and sqrt : the former will handle System.outobjects; the latter is a static method that does not handle any objects.

  • Static import : import static java.lang.Math.*, I don't understand why.

  • Type conversion : legal conversion [p38], mandatory conversion [p39], decimal conversion to integer is truncated instead of rounded .

  • Assignment : It is an expression that can be nested, such as int y = x += 4.

  • Conditional expressions : such as x < y ? x : y; switchThere are also expression usages, which can provide multiple choices compared to the former which only provides two choices. [p41]

  • Bit operations : and (&), or (|), not (~); logical operators use short-circuit rules, but bit operations do not. Move left (<<), move right (>>).

    Note : >>>The upper bits are filled with 0s and >>the upper bits are filled with sign bits. Operator precedence see [p43]

2. String

  • Fetch substring : substring();
  • Splicing : 1) +(other types are automatically converted to string types); 2) concatenate with separators, ; String.join3) copy the same string repeat(x); [p45]
  • Immutable : Strings are immutable objects. To modify a string, you should extract substrings --> splicing. However, the compiler has optimizations for string sharing . However, only string literals can be shared.
  • Comparison : s.equals(t);[p46] Note that ==comparing two strings for equality cannot be used. Note that the empty string is nullnot the same as .
  • Code point : String is a sequence of char values ​​(code points), length()and charAt()all returned are code units , and some code points occupy two code units. char should be avoided [p48]
  • Build string : String builderclass, which can avoid creating a new string for each concatenation. [p53]
  • Text block : Use a pair of """brackets for multi-line strings, and the common indentation will be automatically removed.

3. Input and output

  • Read input : Use Scanneran object, then a in.next()method to extract the data.

    ReadPassword : Using Consolethe class, it will not be displayed in clear text when entered. [p57]

  • Formatted output : 1) C language style, System.out.printf();2) create format string, String.fromat();3) s.formatted();, in java15. [p60]

  • files : 1) input, Scanner(Path p, String encoding);2) output, PrintWriter(String filename, String encoding);[p61]

Question : How to control the read, write, append and other modes of file input?

4. Control process

  • switch , expression/statement, with/without passthrough; there are four combinations in total. [p73]
  • Interrupt control : breakand , both can be used for nested loopscontinue through labels .

Question : Does the switch state trigger multiple branches?

5. Big numbers

  • Big Integer : BigIntegerclass.
  • Large floating-point number : class, it is recommended to use string parametersBigDecimal when creating , because it is easy to produce rounding errors when passing in double parameters.

Both of these two large number classes can only perform four arithmetic operations by calling methods, but cannot use the +,-,*,/etc operator.

6. Array

  • Initialization : int[] a = new int[100]; usage of int[] aand int a[]are both possible.

    Arrays are allowed to have a length of 0, but are different from null, like an empty string.

    Anonymous array?

  • Traversal : for eachIt can be traversed by using a loop, and the traversed object should always have a class object of the Iterable interface.

  • Copy : Java's array is implemented on the heap , =and the assignment of the array will refer to the same array. Copy all values ​​should use Arrays.copyOf();[p83]

  • Command line parameters : the parameters of the main method String[] args, argswhich can receive parameters passed from the command line. For example java Message -g cruel world, args[0] is -g, args[1] is cruel, and args[2] is world.

  • Sort : Arrays.sort; is an optimized quick sort.

  • Multidimensional arrays :double a = new a[3][4];

    There is no actual multidimensional array in Java (unlike C++), but an array of arrays , so we can construct irregular arrays . [p89] That is, a multidimensional array is not a continuous memory block to store each element.

// for-each进行数组的循环遍历
for (int element : a){
    
    
    System.out.println(element);
}

Chapter 4 Object-Oriented Programming

An understanding of objects, object variables, and immutable objects is key.

1 Overview

Object orientation is better suited to larger scale problems than procedural orientation.

  • Class encapsulation : Do not allow other classes to directly access instances of this class, the purpose is to reduce the coupling between classes.
  • Class Inheritance : One class extends another class.
  • Relationship between classes : 1) uses-a; 2) has-a; 3) is-a;

2. Use predefined classes

  • Some classes only encapsulate functionality without having to hide data because there is no data at all. Such as Mathclass.

  • Why use a class intto represent dates instead of a built-in type like ? Because different regions may have different representations, using classes facilitates improvements and replacements .

  • toString()Method for generating a string description of a class.

  • Object, object variable : An object variable doesn't actually contain an object, it just references an object. The objects themselves are on the heap .

  • A story about the calendar : "Calendrical Calculations" [p99]

  • Static factory method : LocalDate.now()Generate an object through this form.

  • " Of course, the significance of encapsulation is that the internal representation is not important ." However, when people learn, they often say to read the source code.

  • Muter method : will change the state of the object.

    Accessor method : only accesses the object, does not change the state of the object.

3. Custom classes

  • Public class : There can only be one public class in a source file, but there can be multiple common classes.

  • Compile multiple classes at a time : 1) Use wildcards, such as javac Employee*.java; 2) Compile only one class, and the compiler will automatically search for other classes used. [p107]

  • Field : It is recommended that all fields of the class use private to maintain encapsulation.

  • Constructor : Its call is always newassociated with , and the constructor cannot be called on an existing object.

  • Naming : Local variables should not have the same name as instance fields, because the former will "shadow" the latter, sometimes leading to more subtle bugs .

  • Declaration : You can use varthe keyword to declare local variables (objects). But it is generally not used for numeric types, so as not to need to pay attention 0,0L,0.0to this distinction between. For parameters or instance fields, the type must be declared and cannot be used var.

  • Null handling : You can use the Objects class, such as name=Objects.requireNonNull(n, "The name can not be null"); there is a difference between strict and loose handling. [p110]

  • Implicit parameters : A class method, in addition to the parameters passed in by the parameter list, also has instance fields of the class as implicit parameters. You can use thiskeywords to indicate implicit parameters, and you don't have to write this keyword when there is no naming conflict.

  • inline method? [p111]

  • Field public --> accessor method : The advantage is that the internal implementation of the class can be changed without affecting the use of the class by other classes (similar to the effect of the three-level schema structure of the database). In addition, error checking can be done within methods by assigning values ​​to instance fields via mutator methods .

    Notice: Do not write accessor methods that return mutable object references, this will break class encapsulation.

  • A method of a class can directly access the private properties of all objects of that class.

  • Private methods : Some helper methods used internally should not be part of the public interface. [p114]

  • final keyword : often used to modify basic types, or immutable objects. Because final only guarantees that object variables remain unchanged (that is, a variable will not refer to other objects), but it cannot prevent changes to the object itself, that is, it is usually meaningless to modify variable objects.

    Some final modified variables can also be modified, for example System.out, because it is not written in java, thus bypassing the rules of java.

4. Static fields and static methods

  • Static fields : belong to the class, not to individual objects.
  • History of the term "static" . [p117]
  • Factory method : Get formatting objects of different styles from a class. [p117]
  • main method : You can add a piece of demo code to each class.

Question : I don't quite understand the factory method.

5. Method parameters

  • In C++, there are two method parameter passing methods: passing by value and passing by reference , while Java always passes by value , that is, the method will get a copy of all parameter values. Here you also need to pay attention to the difference between objects and object variables. You can modify the state of the object in the method, but you cannot change the value of the object variable (that is, you let an object variable point to another object in the method, but for the caller, This object variable still points to the original object).

6. Object construction

  • Overloading : Java allows overloading of any method, including constructors. But the return type of a method is not part of the method signature . [p126]
  • Default field initialization : in case of no constructor/empty constructor. For example, integers will be initialized to 0, and object variables will be initialized to null;
  • In the constructor, you can use this(...)to call another constructor (overloaded) of this class. So, can the public constructor code be needed only once ? [p129]
  • Initialize fields :
    1. Assign values ​​when declaring fields, such asprivate int i = 0;
    2. Assign a value in the constructor.
    3. Use initialization blocks . Wrap it in a pair of curly braces within the class.
  • Static initialization block : Add keywords in front of the initialization block static, it will be executed when the class is loaded for the first time, not every time an object is created.
public class A {
    
    
    private static int i;
    static {
    
    
        i = 0;
    }
}
  • Generate random numbers ? [p131]
  • Destruction : Garbage collection occurs automatically in Java (eg when an object becomes unreachable) without explicitly calling a destructor as in C++. But sometimes the program will use resources outside the memory, such as files, handles, etc., and it still needs to be actively released at this time. [p133]

Feeling : You may feel that assigning a value when declaring a field is so similar to using an initialization block. Why is there such a mechanism as an initialization block? In fact, I also feel a little strange. It may not be realized until the actual code exercise.

7. Record

Sometimes data is just data, and the data hiding provided by object-oriented programming gets in the way.

  • Records : State is immutable and publicly readable.
    • It is equivalent to a class automatically defined: 1) instance field (component); 2) constructor; 3) accessor; 4) three methods: , , toString; equals[ hashCodep135]
    • Non-static instance fields cannot be added. (Keep state immutable)
    • Features : more readable, efficient, and safer in concurrency (why?).
record Point(double x, double y) {
    
    
    ...
}
  • Constructor :
    1. Standard Constructor : Available by default, it can be used to set all instance fields.
    2. Custom constructor : You can set the parameter list to do more processing, and finally call the standard constructor.
    3. Concise constructor : no parameters, prelude processing of pure standard constructor.

8. Package

  • From the compiler's point of view, there is no relationship between nested packages.
  • The compiler locates classes in packages, and the generated bytecode always refers to other classes by their full package names.
  • Contrast : package, importsimilar to that in c++ namespace, using;
  • Put the class into the package : write the package name at the beginning of the source file of the class. And the source file must be placed in a path that matches the full package name .
// .../hello/world/A.java
package hello.world;
public class A {
    
    
    ...
}
  • Compilers work on files, and interpreters (virtual machines) work on classes.There are cases where compilation succeeds but fails to run. [p141]
  • class access :
    • public : This class can be used by any class.
    • Not specified, default : this class can be used by all classes in the same package (note that there is no relationship between nested packages).
    • private : only accessed internally by the class.
  • Static import of the package : You can use the static methods and static fields of the class without prefixing the class name. [p140]
import static java.lang.System.*;
out.println("hello"); // 而不再需要加System前缀
  • Compile the class from the base directory : the compiler processes the file, using /; the interpreter loads the class, using .;
javac com/mycompany/PayrollApp.java // 编译
java com.mycompany.PayrollApp // 运行
  • classpath : A collection of paths containing all class files. Need to include: 1) base directory? 2) current directory; 3) jar file.

    Set classpath : 1) java -classpath2) Set CLASSPATHenvironment variable.

9. JAR file

Package the application, turning the directory structure of folders into a compressed file in zip format.

  • jar command-line program options, see [p147]

  • Manifest file : describes the special characteristics of the archive file (jar package), in META-INF/MANIFEST.MF;

  • Execution : 1) Pack and specify the entry point of the program [p148]; 2) Start java -jar Myprogram.jar.

    In windows, double-clicking the jar file starts the associated javaw -jarcommand, it does not open the shell window.

  • Wrapper : Used to turn a jar file into a platform executable, such as an exe. [p149]

  • Multi-version jar file : A program/library based on a specific java version can run with different versions of jdk.

Feeling : This section also seems to be relatively abstract, and I will slowly understand it when I have a chance in the future.

10. Documentation comments

Having code and comments in one place allows for better consistency. The JDK includes a tool called javadoc that can generate an html document from a source file. Java's online API documentation is generated by running javadoc on the source code of the standard Java class library.

Used by documentation comments /**...*/, containing markup followed by free-form text . Tags @begin with , and html tags can be used in free-form text.

  • Commonly used comments : You can comment on classes, methods, fields, etc., just write the comments directly in front of the code.

  • Package comments : If you want to generate package comments, you need to add a separate file in each package directory, including two types: 1) package-info.javajava files; 2) package.htmlfiles.

  • Comment Extraction : Extract documentation from comments in code. [p155]

Problem : I don't understand the usage of annotation extraction.

11. Class design skills

  1. Be sure to keep your data private . The representation of data is likely to change, but the way they are used does not change very often.
  2. Be sure to initialize the data . It is best not to rely on system defaults, but to initialize all variables explicitly.
  3. Don't use too many primitive types in a class . If there are multiple related primitive types, they can be encapsulated into an object. This makes the class easier to understand.
  4. Break down classes that have too many responsibilities .
  5. Class names and method names should better reflect their responsibilities .
  6. Prefer immutable classes . Methods like plusDays do not modify the object, but return a new object with the modified state. Sharing objects between multiple threads is safer against concurrent changes .

Guess you like

Origin blog.csdn.net/m0_63238256/article/details/131403736