Java learning notes

Posted by taya on Sat, 05 Mar 2022 06:38:53 +0100

**[JAVA] learning notes * * (12.04)

Code execution process

  • The development cycle of Java program includes compilation, download, interpretation and execution.

    1. Write java code first.

    2. Compile and compile Java code into bytecode (. class file).

    3. Bytecode is loaded into memory.

    4. Entering the virtual machine is executed by the interpreter or selectively converted into machine code by the real-time code generator

How to open CMD

  • 1. Start + system + command prompt

  • 2.Win + R input cmd to open the console

  • 3. Under any folder, press and hold shift + right click to open the command window here

  • 4. Add cmd path in front of the address bar of the resource manager

Running in administrator mode has the highest authority

Common DOS commands

<span style="background-color:#f8f8f8"><span style="color:#333333"><span style="color:#aa5500">#Drive letter command</span>
disc <span style="color:#981a1a">+</span> <span style="color:#Aa1111 "> ':' < / span > for example: D:
​
<span style="color:#aa5500">#View all files in the current disk</span>
dir
​
<span style="color:#aa5500">#Switch directory</span>
<span style="color:#3300aa">cd</span>(change directory) R
<span style="color:#3300aa "> CD < / span >.. return to the previous level
<span style="color:#3300aa "> CD < / span > / D specific path
​
<span style="color:#aa5500">#Clear screen</span>
cls
​
<span style="color:#aa5500">#Exit terminal</span>
<span style="color:#770088">exit</span>
​
<span style="color:#aa5500">#View computer ip</span>
ipconfig
​
<span style="color:#aa5500">#Open app</span>
    calc
    mspaint
    notepad
    
<span style="color:#aa5500">#ping command</span>
    <span style="color:#3300aa">ping</span> www.baidu.com
    
<span style="color:#aa5500">#Create folder</span>
md file name
​
<span style="color:#aa5500">#Create file</span>
<span style="color:#3300aa "> CD < / span > > file name. Suffix
​
<span style="color:#aa5500">#Remove file</span>
rd file name
​</span></span>

JVM,JDK,JRE

  • JVM is the abbreviation of Java Virtual Machine. It is realized by simulating various computer functions on an actual computer. It consists of a set of bytecode instruction sets, a set of registers, a stack, a garbage collection heap and a storage method field. The JVM shields the information related to the operating system platform, so that Java programs only need to generate the object code (bytecode) running on the Java Virtual Machine, and can run on a variety of platforms without modification. This is also the reason why Java can "compile once and run everywhere".

    JRE (Java Runtime Environment) is a Java platform. All programs can run only under JRE. Including JVM and Java core class libraries and supporting files.

    JDK (Java Development Kit) is a development kit used to compile and debug Java programs. Including java tools (javac/java/jdb, etc.) and Java based class libraries (Java APIs).

  • JDK > JVM > JRE

Features and three versions of Java

  • Simplicity, object-oriented, portability, high performance, distributed, dynamic, multithreading, security and robustness

  • JavaSE: Standard Edition (desktop program, console development...)

    JavaME: embedded development (mobile phones, small appliances...)—— Dead

    Java EE: E enterprise development (web side, server development...)

Process of uninstalling JDK

  • 1. Delete the installation directory of java

    2. Delete JAVA_HOME

    3. Delete the Java directory under path

    4. Open cmd and enter java -version

JDK installation process

  • 1. Search JDK8 and find the download address

    2. Consent agreement

    3. Download the corresponding version of the computer

    4. Double click to install

    5. Remember the installation path

    6. Configure environment variables

    1. My computer -- > right click -- > Properties

    2. Environment variable -- > java_ HOME

    3. Configure the path variable

    7. Test whether JDK is installed successfully

    1. Open CDM

    2. Enter java -version

What are the files in the JDK directory

  • There are some executable files (exe files) in the bin directory

  • include directory. Since JDK is written in C and C + +, it refers to the header file of C language

  • jre contains the java runtime environment

  • lib is the abbreviation of library, which contains java class library files

  • src puts a lot of java classes and packages

HelloWorld issues needing attention

  • There should be no problem with the size of each word. java is case sensitive

  • Try to use English

  • The file name and class name must be consistent and capitalized

  • The symbols are in Chinese

Java program running mechanism

  • Compiled type

    Convert high-level compiled language into machine language through compiler

    Compiled language: compile before running the program

  • Interpretive language: it is translated only when the program is running, and an interpreter is needed

  • Compiled languages are not as cross platform as interpreted languages

Java Foundation

  • Comments: single line comments, multi line comments, document comments

    Single line comment: / / + comment content

    Multiline comment: / * comment content*/

    Document comments: / * * comment content*/

  • identifier

    • All identifiers should be in letters (a - z or a - z), dollar sign ($), underscore () start

    • The first character can be any combination of characters, except for some special symbols

    • Keywords cannot be used as identifiers

    • Identifiers are case sensitive

  • data type

    • Strongly typed language: all variables must be defined before use (they are always a type without conversion)

    There are two categories of data types in Java

    • Basic type

    • reference type

  • Try to avoid floating point numbers

The storage structures of float and double are as follows:

float: 32 bits

double: 64 bit

The floating-point type in java is double by default. All floating-point numbers must be converted into binary storage in the computer, so it involves the problem of precision. Take 1.10 as an example:

Decimal part: 0.1, 0.12 = 0.2 takes integer part 0, base = 0.2, 0.22 = 0.4 takes integer part 0, base = 0.4, 0.42 = 0.8 takes integer part 0, base = 0.8, 0.82 = 1.6 takes integer part 1, base = 1.6-1 = 0.6, 0.62 = 1.2 takes integer part 1, base = 1.2-1 = 0.2, 0.22 = 0.4 takes integer part 0, base = 0.4 Until the cardinality is 0. 1.1 expressed in binary: 1.000110 xxxx.... (omitted later) 0.1 = 02 ^ (- 1) + 02 (- 2) + 0 * 2 (- 3) + 1 * 2 ^ (- 4) + The double type indicates that the decimal part has only 52 digits. When the base number is not 0 after 52 digits are calculated backward, the latter part can only be discarded. It can be seen from here that float and double cannot accurately represent each decimal place, and some decimals can only trend to it indefinitely. In fact, the addition, subtraction and division operations in the computer are finally converted into binary addition operations in the computer

  • Type conversion

Cast: (type) variable name high -- > low

Automatic conversion: low -- > High

Note: 1 Boolean values cannot be converted

2. Object types cannot be converted to irrelevant types

3. Use force conversion when converting high capacity to low capacity

4. There may be memory overflow or accuracy problems during conversion

tips: JDK7 has a feature that can be used between numbers__‘ But not output

  • Variable, constant, scope

    • Variable: the quantity that can be changed. Java variable is the most basic storage unit in the program, and its elements include variable name, variable type and scope

      Method of declaring variables: data type, variable name = value; You can declare multiple variables of the same type separated by commas (not recommended, pay attention to program readability)

    • Variable scope: class variable (static variable), instance variable, local variable,

      Class variable: keyword static, subordinate to class

      Instance variable: subordinate to the object, in which String is not initialized and null by default, int is not initialized and 0 by default, and Boolean value is false by default. All other variables except basic type are null

      Local variables: must be declared and initialized

      How to use instance variables in methods:

      <span style="background-color:#f8f8f8"><span style="color:#Aa5500 "> / / variable type - demo08 variable name - demo08 = value - New demo08()</span>
      <span style="color:#000000">Demo08</span> <span style="color:#000000">demo08</span> <span style="color:#981a1a">=</span> <span style="color:#770088">new</span> <span style="color:#000000">Demo08</span>();</span>
    • Constant: a value that cannot be changed after initialization

      <span style="background-color:#f8f8f8"><span style="color:#770088">final</span> <span style="color:#770088">static</span> <span style="color:#008855">double</span> <span style="color:#000000">pi</span> <span style="color:#981a1a">=</span> <span style="color:#116644">3.14</span>;
      <span style="color:#Aa5500 "> / / final static is a modifier, and there is no order of precedence</span></span>
    • Naming conventions for variables

      • All variables, methods and class names: see the meaning of the name

      • Class member variables: lowercase initial and hump principle (except for the first word, the following words are capitalized)

      • Local variables: ditto

      • Constants: uppercase letters and underscores

      • Class name: initial capitalization and hump principle

      • Method name: initial lowercase and hump principle

  • operator

    Priority: single calculation, shift and, exclusive or logic assignment

    The bracket level is the highest and the comma level is the lowest. Single item > arithmetic > displacement > relationship > Logic > three items > assignment.

  • Package mechanism

  • Java Doc

    The javcadoc command is used to generate its own API documentation (file comments)

    parameter information

    /**

    @Author author name

    @Version version number

    @since indicates that the earliest version of jdk is required

    @param parameter name

    @Return return value

    @throws exception thrown

    */

Java process control

  • Scanner

    java.util.Scanner is a new feature of Java 5. You can get user input through the scanner class

    <span style="background-color:#f8f8f8"><span style="color:#000000">Scanner</span> <span style="color:#000000">scanner</span> <span style="color:#981a1a">=</span> <span style="color:#770088">new</span> <span style="color:#000000">Scanner</span>(<span style="color:#000000">System</span>.<span style="color:#000000">in</span>);</span>

    Note: it must be closed after reading data with scanner

    <span style="background-color:#f8f8f8"><span style="color:#000000">scanner</span>.<span style="color:#000000">close</span>();</span>

    next()

    • next stops when it encounters whitespace (including carriage return and space) after reading the first valid character

    • next cannot read a string with spaces

    • Use hasnext() to judge whether there are new unaccepted characters. If there are, it will return 0 and if not, it will return 0

    Use next() to pass the input data into the parameter

    <span style="background-color:#f8f8f8"><span style="color:#008855">int</span> <span style="color:#000000">a</span> <span style="color:#981a1a">=</span> <span style="color:#000000">scanner</span>.<span style="color:#000000">next</span>();</span>

    hasNext()

    • You can use this function to check whether there is any input

    nextLine()

    • Strings with spaces are acceptable

    • Only enter enter will stop accepting characters

    <span style="background-color:#f8f8f8"><span style="color:#008855">int</span> <span style="color:#000000">a</span> <span style="color:#981a1a">=</span> <span style="color:#000000">scnner</span>.<span style="color:#000000">nextLine</span>()</span>

    hasNextLine()

    • You can use this function to check whether there is any character input other than carriage return

    scanner has many other functions, e.g. nextInt(), hasNextInt(), nextFloat(), hasNextFloat()

  • Format output

    <span style="background-color:#f8f8f8"><span style="color:#Aa5500 "> / / general shortcut: South output line feed</span>
    <span style="color:#000000">System</span>.<span style="color:#000000">out</span>.<span style="color:#000000">println</span>(<span style="color:#aa1111">"x = "</span> <span style="color:#981a1a">+</span> <span style="color:#000000">x</span> <span style="color:#981a1a">+</span> <span style="color:#aa1111">", y = "</span> <span style="color:#981a1a">+</span> <span style="color:#000000">y</span>);
    <span style="color:#Aa5500 "> / / printf() mode s</span>
    <span style="color:#000000">System</span>.<span style="color:#000000">out</span>.<span style="color:#000000">printf</span>(<span style="color:#aa1111">"x = %d, y = %f\n"</span>, <span style="color:#000000">x</span>, <span style="color:#000000">y</span>);
    <span style="color:#Aa5500 "> / / format() mode</span>
    <span style="color:#000000">System</span>.<span style="color:#000000">out</span>.<span style="color:#000000">format</span>(<span style="color:#aa1111">"x = %d, y = %f\n"</span>, <span style="color:#000000">x</span>, <span style="color:#000000">y</span>);</span>

Sequential structure

  • if single choice structure

    <span style="background-color:#F8f8f8 "> if (judgment statement){
    	Statement is TRUE implement
    }Or jump out
      </span>
  • if double selection structure

    <span style="background-color:#f8f8f8">if(){
    
    }else{
    
    }</span>
  • if multiple selection structure

    <span style="background-color:#f8f8f8">if( ){
    
    }else if( ){
    
    }else{
    
    }</span>
  • switch

    The variable statement type can be

    • byte, short, int or char

    • Starting from JDK7, switch supports String type

    • At the same time, the case tag must be a string constant or literal

    case penetration: when the variable statement finds the first match, it will be executed in sequence. Add break to skip

Cyclic structure

  • while loop, do while loop and for loop

  • An enhanced for loop mainly used for arrays is added to JDK5

  • For loop shortcut key {num.for

Enhanced for loop

<span style="background-color:#f8f8f8"><span style="color:#333333 "> int [] numbers = {10, 20, 30, 40}; / / defines an array named numbers


		/*
        * Ordinary loop traversal
        * */
        for(int i = 0;i < numbers.length; i++){
            System.out.println(numbers[i]);
        }


        /*
        * Enhanced for loop
        * */
        for(int x:numbers){
            System.out.println(x);
        }</span></span>

Goto

  • Goto is a reserved word in java, but it is not officially used; java has no goto. But the labeled break and continue can play the role of goto

  • label refers to the identifier followed by a colon, for example: label:

  • For java, the only place where tags are used is before loop statements. If the tag is nested in the same place as the current tag, the only reason they want to break the loop is to use the break tag in the same place as the current tag

Java Procedure

  • Java methods are similar to functions in other languages. They are code fragments used to complete specific functions. Generally, defining a method includes the following syntax:

    • Method contains a method header and a method body. All parts of the method are as follows:

      • Modifier: optional, tells the compiler how to call the method. Defines the access type of the method

      • Return value type: the method may return a value. returnValueType is the data type of the return value of the method. Some methods perform the required operation but do not return a value. In this case, returnValueType is the keyword viod

      • Method name: it is the actual name of the method. The method name and parameter table together constitute the method signature (the first letter of "Hump naming rules" shall be lowercase and the last letter shall be uppercase)

      • Parameter type: the parameter is like a placeholder. When the method is called, the value is passed to the parameter. This value is called an argument or variable. Parameter list refers to the parameter type, order and number of parameters of a method. Parameters can be selected, and methods can not contain any parameters.

        Formal parameter: used to receive external input data when the method is called

        Argument: the data actually passed to the method when the method is called

      • Method body: the method body contains specific statements that define the function of the method

      • java methods must have return values, so all cases should be considered

  • Overloading of methods

    • Overloading is a function with the same function name but different formal parameters in a class

    • Overload rules for methods

      • Method names must be the same

      • The parameter list must be different (different number, different types, different order of parameters, etc.)

      • The return types of methods can be the same or different

      • Just different return types are not enough to overload methods

    • Realization theory:

      • If the method names are the same, the compiler will match one by one according to the number of parameters and parameter types of the calling method to select the corresponding method. If the matching fails, the compiler will report an error.

  • Command line parameters

    • Some functions can be executed with parameters. For example, the parameter of the main function is String[] args. You can pass the string parameter to the main function before execution

    <span style="background-color:#f8f8f8">package com.whd.method;
    
    public class Demo03 {
        public static void main(String[] args) {
    
            //args.length array length
            for (int i = 0; i < args.length; i++) {
                System.out.println("args["+ i +"]:" + args[i]);
            }
        }
    }
    </span>
    • Parameters can be passed through the command line. The specific steps are as follows:

      • First use the cmd window to enter the command javac file name java for compilation

      • Command javac file name java string can realize command line parameter passing

  • Variable parameter

    • JDK1. Starting from 5, java supports passing variable parameters of the same type

    • In the method declaration, add an ellipsis (...) after specifying the 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

  • recursion

    • Method A calls method A

    • The recursive structure consists of two parts:

      • Recursive header: when not to call its own method. If there is no head, it will fall into a dead cycle

      • Recursive body: when do I need to call my own method

  • Static methods and classes are loaded together. The time slice is the same, while non static methods are loaded only when instantiated

  • Static methods can call static methods, non static methods can call static methods, and non static methods can call non static methods

array

  • Array overview

    • An array is an ordered collection of data of the same type

    • It describes several data of the same type, which are arranged and combined in a certain order

    • Each element is called an array element, and each array element can be accessed through a subscript

  • Array declaration creation

    • Array variables must be declared before they can be used in programs

    • <span style="background-color:#F8f8f8f8 "> / / declare method
      dataType[] arrayRefVar;
      dataType arrayRefVar[];</span>
    • Use the new operator to create an array

      <span style="background-color:#f8f8f8">dataType[] arrayRefVar = new dataType[arraySize];</span>
    • Array elements are accessed by index, and the subscript starts from 0

    • Array length: arraytype length;

  • Array usage

  • Multidimensional array

  • Arrays class

  • Sparse array

  • for each loop

    <span style="background-color:#f8f8f8">for(int array : arrays){
    
    }</span>

  • Memory analysis

    • heap

      • new objects and arrays

      • It can be shared by all threads and will not store other object references

    • Stack

    • Method area

object-oriented programming

Java Decompilation

  • Disassembly refers to the process of converting object code into assembly code, that is, from machine language to assembly language code

  • Java disassembly is to convert the class file (bytecode) compiled by java compiler into a more readable form, including local variable table, exception table, code line offset mapping table, assembly instructions, etc

class file is a precise definition of the binary file format of java program. (bytecode)

Steps to open a class file (view decompiled code)

1.class files are garbled when opened with text, but can be opened with IDEA

2. Open from the file level and find the class file path in project struct

3. Import jav file

Differences among queue, heap, stack and stack

Stack: the stack is automatically allocated and released by the operating system. It is used to store the parameter values and local variables of the function. Its operation mode is similar to the stack in the data structure.

  • The life cycle of the data stored in the stack ends with the execution of the function

  • <span style="background-color:#f8f8f8">int main() {
    	int b;				//Stack
    	char s[] = "abc"; 	//Stack
    	char *p2;			//Stack
    }
    </span>
  • The local variables defined in the function are pushed into the stack in the order they are defined successively, that is, there will be no other variables between the addresses of adjacent variables. The memory address of the stack grows in the opposite direction of the heap, from high to bottom, so the variable address defined later is lower than the variable defined earlier. For example, in the above code, the address of variable s is less than the address of variable b, and the address of p2 is less than the address of variable s. The life cycle of the data stored in the stack ends with the execution of the function.

Heap: it is allocated and released by the developer. If the developer does not release it, it will be recycled by the OS at the end of the program. The allocation method is similar to the linked list.

  • <span style="background-color:#f8f8f8">int main() {
    	// Application with malloc() function in C
    	char* p1 = (char *)malloc(10);
    	cout<<(int*)p1<<endl;		//Output: 00000000003BA0C0
    	
    	// Release with free() function
    	free(p1);
       
    	// new in C + + application operator
    	char* p2 = new char[10];
    	cout << (int*)p2 << endl;		//Output: 00000000003BA0C0
    	
    	// Release with delete operator
    	delete[] p2;
    }
    </span>
  • The memory address growth direction of the heap is opposite to that of the stack, from low to high. However, it should be noted that the memory space applied later is not necessarily behind the memory space applied earlier, that is, the address pointed to by p2 is not necessarily greater than the memory address pointed to by p1. The reason is that once the memory space applied first is released, the memory space applied later will use the memory previously released, As a result, there is no sequential relationship between the successively allocated memory space and the address. If the data stored in the heap is not released, its life cycle is equal to the life cycle of the program.

  • With regard to the allocation process of memory space on the heap, we should first know that the operating system has a linked list recording the free memory address. When the system receives the application of the program, it will traverse the linked list to find the first heap node whose space is greater than the applied space, then delete the node from the linked list of free nodes, and allocate the space of the node to the program. In addition, for most systems, the size of this allocation will be recorded at the first address in this memory space, so that the delete statement in the code can correctly free this memory space. Since the size of the found heap node is not necessarily equal to the size of the application, the system will automatically put the excess part back into the free linked list.

problem

  • What is final?

  • The role of new. What is the purpose of a new class?

 

Topics: Java