web123456

Java SE Complete Notes

Java SE

1. Java Overview

1.1 Background on the Java language (understanding)

Language: Expressions of human interaction and communication

Computer language: a special language for the exchange of information and communication between humans and computers.

Java is a computer language introduced by Sun (Stanford University Network) in 1995.

Father of Java: JamesGaussianJames Gosling

In 2009, Sun was acquired by Oracle, so we now visit theoracleThe official website is available:

Three versions of the java language:

JavaSE: the (standard) version of the Java language for desktop application development, which is the basis for the other two versions

JavaME: A (small version) of the Java language for embedded consumer electronics devices

JavaEE: Java Language (Enterprise Edition) for Web OrientationWeb Development

1.2 Java language cross-platform principles (understanding)

Java programs are not run directly; the Java compiler compiles the Java source program into platform-independent bytecode files (class files), which are then used by the Javavirtual machine(JVM) on the byte code file interpretation and execution. So in different operating systems, just install a different Java virtual machine can realize the cross-platform java program.

1.3 JRE and JDK (memorization)

JVM (Java Virtual Machine), Java Virtual Machine

JRE (Java Runtime Environment), the Java Runtime Environment, contains the JVM and Java's core class libraries (Java API)

JDK (Java Development Kit) called Java Development Tools, contains the JRE and development tools

To summarize: we just need to install the JDK, which contains the java runtime environment and virtual machine.

1.4 JDK download and installation (application)

1.4.1 Downloading

Getting the JDK through the official website

take note of: For different operating systems, you need to download the corresponding version of the JDK.

1.4.2 Installation

Foolproof installation, the next step can be. However, the default installation path is under C:\Program Files, for the convenience of unified management is recommended to modify the installation path, and development-related software are installed to a directory, for example: E:\develop.

take note of: The installation path should not contain special characters such as Chinese or spaces (use a plain English directory).

1.4.3 Introduction to the JDK installation directory
Catalog Name clarification
bin This path holds the various tool commands for the JDK. javac and java are placed in this directory.
conf This path holds the relevant configuration files for the JDK.
include This path holds a number of platform-specific header files.
jmods This path holds the various modules of the JDK.
legal This path holds the license documentation for each JDK module.
lib This path holds some supplemental JAR packages for the JDK tools.

2. First demonstration program

2.1 Common DOS commands (applications)

Before touching the integrated development environment, we need to use the command line window to compile and run the java program, so you need to know some common DOS commands.

1, the way to open the command line window: win + r to open the run window, type cmd, enter.

2. Common commands and their roles

manipulate clarification
Disk Name. The disk letter is switched.E:Enter, indicating that it is switched to the E drive.
dir View the contents under the current path.
cd Catalog Go to the single-level catalog. cdithuipu
cd … Fall back to the previous level of the directory.
cd Catalog 1\ Catalog 2... Enter the multi-level catalog. cdithuipu\JavaSE
cd \ Fall back to the disk directory.
cls Clear screen.
exit Exit the Command Prompt window.

2.2 Configuration of Path environment variables (application)

2.2.1 Why Configure Environment Variables

Development of Java programs, you need to use the development tools provided by the JDK (such as, and other commands), and these tools in the installation directory of the JDK bin directory, if you do not configure the environment variable, then these commands can only be executed in that directory. We can not put all the java files into the JDK bin directory, so the role of configuring environment variables is to enable the bin directory of java-related commands can be used in any directory.

2.3 HelloWorld case (application)

The HelloWorld case refers to the output of the line "HelloWorld" on the computer screen.

Various computer languages are accustomed to using this case as the first demonstration case.

2.3.1 Java program development runtime process

To develop a Java program, there are three steps: writing the program, compiling it, and running it.

2.3.2 Writing the HelloWorld Case

1, a new text document file, modify the name.

2, use notepad to open the file, lose write program content.

public class HelloWorld {
	public static void main(String[] args) {
		System.out.println("HelloWorld");
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
2.3.3 Compiling and Running the HelloWorld Case

Save the file, open a command line window, switch the directory to the directory where the java file is located, compile the java file to generate the class file, run the class file.

Compile: javac filename.java

Example: javac

Execution: java class name

Example: java HelloWorld

2.4 HelloWorld case details (understanding)

[External link image dump failed, the source site may have anti-piracy chain mechanism, it is recommended to save the image and upload it directly (img-cR44cqHy-1683971924370)(img\image)]

2.5 HelloWorld Case FAQ (Understanding)

2.5.1 BUG

Some undiscovered flaws or problems hidden in a computer system or program are collectively called bugs (vulnerabilities).

2.5.2 Bug resolution

1, with the ability to identify bugs: see more

2, with the ability to analyze the BUG: more thinking, check more information

3, with the ability to solve bugs: try more, more summarized

2.5.3 HelloWorld Case Frequently Asked Questions

1. illegal character problem. symbols in Java are in English format.

2, case issues. the Java language is case-sensitive (case-sensitive).

3. Show the file extension in the system to avoid the file.

4, after compiling the command java file name needs to be with the file suffix .java

5, run the command after the class file name (class name) without file extension

3. Data types

3.1. Notes

  • Single-line comments: //
  • Multi-line comments: /* */
  • Documentation note: /** */
class Demo{ //class represents a class
	public void static main(String[] args) { The //main function is the entry point to java, the introductory program
        System.out.println("Hello World"); // printout, what is written in parentheses - is outputted
    }
}
/*
This is an introductory program for Java
This is a multi-line comment
*/
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

3.2. Keywords

Java fields with special meanings

Features:

  1. All lowercase class public void main is not a keyword, but it is more important than a keyword.
  2. In Advanced Notepad, keywords are highlighted
  3. Names must be named to avoid keyword conflicts (class names, variable names, method names)

3.3. Constants

Definition: a program whose value does not change during its operation

Classification of constants in Java:

  • String constants (String): anything enclosed in double quotes is a string constant. "Hello World" "1234"
  • Integer constants (int): 1, 123, 2134
  • Fractional constants (float): 1.2, 3.14
  • Character constants (chat): '10' is not allowed 'Li', 'Hua', '0': is allowed
  • Boolean constants: where there is only true and false.
  • Empty constant: null, a special value that can't be exported individually
class Demo{
    public void static main(){
        System.out.println("Hello World!"); //String constant values
        System.out.println(1);// Integer constants
        System.out.println(1.1);// Fractional constants
        System.out.println('3');//character constants
        System.out.println(true);// Boolean constants
        System.out.println("null");//null
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

3.4. Variables

Definition: the value of which can change during the course of a program (storing data in memory).

Essence: Storing data in memory

Definition format for variables:

Data Type Variable Name = Variable Value int num = 10;

  • Name change: come up with a name (it's best to see the name and know what it means)
  • Variable value: the value assigned to a variable
  • Data types: add a limit to the data in the village genus in memory (different data types take up different amounts of space)

3.5. Data types

Computers can be used to store data, but whether it is memory or hard disk, the smallest information unit of a computer storage device is called a "bit", also known as a bit, usually represented by a lowercase b. The most basic storage unit in a hot computer is called a "byte", usually represented by an uppercase B. A byte is made up of eight bits. The most basic storage unit in a hot computer is called a "byte" (byte), usually with a capital B. A byte is composed of eight bits:

1B(byte) = 8bit

1kb = 1024B

1MB = 1024KB

1GB = 1024MB

1TB = 1024GB

  • Bit
  • Byte B 8 bytes
  • Java is a strongly typed programming language, where a variable must be declared with one of its data types.
3.5.1 Basic data types (four categories and eight types)
  • Integer type: (The default data type isint

    • integer type memory footprint range of values
      byte 1 byte -128 ~ 127
      short 2 bytes -32768 ~ 32787
      int 4 bytes -2147483648 ~ 2147483647
      long 8 bytes -2 to the 63rd power of 2 to the 63rd power of 2-1
    • Summary:

      1. The default integer type is int.
      2. If the integer type exceeds the int type, use long (it is recommended to add an uppercase L to conform to the java specification).
    class Demo{
        public void static main(String[] args) {
            // 1. Define integer type variables
            int i = 10;
            System.out.println("i = " + i);
            System.out.println("sout = " + 10);
            // 2. Define a variable of type long
            long m = 25; 
            /* 25 is an integer type (int) m long will not report an error it will have a type conversion (implicit conversion) can be added with an upper case L */
            long l = 100L;
            System.out.println("l = " + l);
            System.out.println("m = " + m);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
  • Floating point numbers: (the default data type isdouble

    • Floating point numbers (decimals) memory footprint range of values
      float (single precision) 4 bytes ……
      double (double precision) 8 bytes ……
      class Demo{
          public void static main(String[] args) {
              System.out.println("Constants = " + 12.4);
              // Define double
              String piStr = 4.14;
              System.out.println("double = " + pi);
              // Define float
              float piFat = 3.14F;
              System.out.println("float = " + pifat);
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
    • summarize

      1. The default type for decimals (floating point) is double.
      2. Just add (f | F) when defining a decimal of type float
  • Character type: (char)

    • character type nibbles Range of values (corresponding to Unicode table)
      char 2 bytes 0 ~ 65535
      class Demo {
       	public void static main(String[] args) {
              // Define characters
              char c = '1';
              System.out.println(c);
          }   
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
  • Boolean type: (boolean)

    • Boolean type nibbles range of values
      boolean 1 true、false
      class Demo {
       	public void static main(String[] args) {
              // Defining Boolean Types
              boolean b = true;
              (b);
          }   
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
  • References data types:

    • Classes, interfaces, arrays ......

3.6 Application of variables

// 1. The life of a variable: data type Variable name = Variable value.
	int num = 10; // Declare and assign values
// 2. Declare then assign
	double money;
	money = 10.3;
// 3. Expansion
	int a = 10,b = 20;
	int o,p;
	//o = 10,p = 10;
	0 = 10;
	p = 20;
// 4. Modification of variables
	int sum = 10;
	sum = 20; // will overwrite the original value in the memory address
/*
5. Notes
1. Within the same method, the variable name can not be repeated
2. Variables must be initialized before use (they must be assigned values)
3. the definition of long type can be added to the value of L (it is recommended that the upper case, lower case like 1 is not very clear)
4. Define float type of decimal when you must add F | f (otherwise it will compile an error, the default decimal type is double, tell jvm this is a float type)
*/
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
3.6.1. Keyboard input (Secanner):

Getting the keyboard input object:

  1. Import package: import ;
  2. Create the object: Scanner myScanner = new Scanner();
  3. Receive data: int num = (); // means assign data to num
import java.utli.Scanner;

class MyScannerTest{
	public void static main(String[] args) {
		Scanner myScanner = new Scanner(Syatem.in);
        System.out.println("Please enter an integer:");
        int num = myScanner.nextInt();
        System.out.println(num);
    }	
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

3.7. Identifiers

Identifiers: are the names given to variables, methods, classes.

Composition specification for identifiers in Java:

  1. Consisting of numbers, letters, underscore _, dollar sign $] also cannot begin with a number
  2. Strictly case sensitive int Num = 10; int num = 10;
  3. Keywords and reserved words cannot be used in Java

Naming conventions for identifiers in Java:

  1. camelid nomenclature
    1. Small humps (two or more words, the first word is all lowercase, the first letter from the second onwards is all uppercase): method names, variable names
    2. Big Hump (all word initials capitalized): class name
    3. Names must have meaning (see name for meaning): userName, passWord, etc.

4. Basic Grammar

4.1 Type conversion

Java development, the data type of the data can be converted to each other. There are two types

  • Automatic type conversion (implicit conversion)
  • forced type conversion
int i = 10;
double sum = i + 12.9;
  • 1
  • 2

implicit conversion

Definition: to assign a number or variable with a small range of values to a variable with a large range of values: implicit conversion from small to large

class Demo{
    public void static main(String[] args) {
        // Define variables of type int
        int m = 10;
        // Assignment
        double d = m; //int --> double
        System.out.println(d); //10.0
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Details of the implicit conversion:

  1. Basic data types: byte -> shoat -> int -> long -float -> double
  2. If a small type is involved in an operation on a large type, the small type is automatically promoted to the large type and then involved in the operation.
  3. byte shoat char If these three types are involved in the operation, it will be automatically promoted to int type.

Optimization mechanism for constants

Definition: At compile time, integer constants are automatically calculated to see if they are in the range of the corresponding data type.

Case in point:

byte a = 3;
byte b = 4;
byte c = (byte) (a + b);
byte d = 3 + 4;
  • 1
  • 2
  • 3
  • 4

4.2. Forced type conversion

Definition: a number (variable) with a large range of values, assigned to a variable with a small range of values: from largest to smallest

Format of forced type conversion: target's datatype variable name = (target datatype) value or variable

// Define a large type
double m = 10.5;
// forced conversion -- target data type variable name = (target data type) value or variable
int i = (int) m;
System.out.println(i);//10
  • 1
  • 2
  • 3
  • 4
  • 5

4. Operators

4.1 Type conversion

Java development, the data type of the data can be converted to each other. There are two types

  • Automatic type conversion (implicit conversion)
  • forced type conversion
int i = 10;
double sum = i + 12.9;
  • 1
  • 2

implicit conversion

Definition: to assign a number or variable with a small range of values to a variable with a large range of values: implicit conversion from small to large

class Demo{
    public void static main(String[] args) {
        // Define variables of type int
        int m = 10;
        // Assignment
        double d = m; //int --> double
        System.out.println(d); //10.0
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Details of the implicit conversion:

  1. Basic data types: byte -> shoat -> int -> long -float -> double
  2. If a small type is involved in an operation on a large type, the small type is automatically promoted to the large type and then involved in the operation.
  3. byte shoat char If these three types are involved in the operation, they will be automatically promoted to int type.

Optimization mechanism for constants

Definition: At compile time, integer constants are automatically calculated to see if they fall within the range of values for the corresponding data type.

Case in point:

byte a = 3;
byte b = 4;
byte c = (byte) (a + b);
byte d = 3 + 4;
  • 1
  • 2
  • 3
  • 4

4.2. Forced type conversion

Definition: a number (variable) with a large range of values, assigned to a variable with a small range of values: from largest to smallest

Format of forced type conversion: target's datatype variable name = (target datatype) value or variable

// Define a large type
double m = 10.5;
// forced conversion -- target data type variable name = (target data type) value or variable
int i = (int) m;
System.out.println(i);//10
  • 1
  • 2
  • 3
  • 4
  • 5

4.3. Operators

4.3.1 Operators and expressions

Operators: symbols for manipulating constants and variables = + - &

Expression: a formula spliced with a constant and a variable operator int a = 10 (= is the operator) int b = 30; int c = a + b +10;

4.3.2. Arithmetic operators (applications)
notation corresponds English -ity, -ism, -ization
+ plus
- diminish
* multiply (mathematics)
/ get rid of
% take a remainder
class Demo {
    public void static main(Stringp[] args) {
        /*
        Arithmetic operators + - * / %
(1 + 1);
(10 - 3).
*/
		// Define variables
         int a = 10;
         int b = 30;
         int c0 = a + b; //40 
         int c1 = a - b; //-20
         int c2 = a * b; //300
         int c3 = a / b; //0
         int c4 = a % b; //3
         System.out.println(c0);        
         System.out.println(c1);
         System.out.println(c2);
		System.out.println(c3);
         System.out.println(c4); 
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
// Keyboard a three-digit number to get the first, second, and third digits of the number.
/*
Idea analysis
1, create a keyboard input object
2, enter an arbitrary three-digit number
Single digit --- % 10
Tens --- / 10 % 10
Hundred --- / 100 % 10
Thousand --- / 1000 % 10
*/
import	java.util.Scanner;
class ScannerDemo01 {
    public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
        System.out.println("Show into an arbitrary three-digit number:");
        int num = sc.nextInt();
    	int ge = num % 10;
        int shi = num / 10 % 10;
        int bai = num /100 % 10;
        System.out.println("digit = " + ge);
        System.out.println("Ten = " + shi);
        System.out.println("Hundreds = " + bai);
    } 
    
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
4.3.3 Self-increasing and self-reducing

Self-increment (+ +), Self-decrement (- -) need to be combined with variables, self-increment (add one at a time),, self-decrement (subtract one at a time)

Separate use of self-increment and self-decrement

Used alone, + + | - -, there is no difference between putting it before and after the variable

Self-incrementing and self-decrementing can be placed before or after a variable.

(math.) self-increasing is involved in the same operation as self-decreasing

++ | - -, participating in the operation

++ or - - before the variable, to participate in the operation: first self-increment (self-decrement), then participate in the operation;

++ | - - After the variables, participate in the operation: first operation in (self-increment) (self-decrement)

Case in point:
int a = 10; //11 -> 12
int b = 5;//6 -> 5
int sum = ++b + ++a + b-- + a++ + b++; //11+6+6+11+5
System.out.println("a = " + a);//12
System.out.println("b = " + b);//6
System.out.println("sum = " + sum); //39
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

4.4. Assignment operators

The assignment operator is assigning a value to a variable, assigning the value to the right of = to the left of the equal sign

Example: = += -= *= /= %=

int a = 10;

a += 10; // a = a + 10; (you can't just write the expression this way) (a += 10; implies a strong transfer of the data type)

class Demo{
    public static void main(String[] args){
        int a = 10;
        a += 10;// Equivalent to a = a + 10;
        System.out.println("a += 10 :" + a);
        a *= 10;// Equivalent to a = a* 10;
        System.out.println("a *= 10 : " + a);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

4.5 Relational operators

>= <= ! = > < == (equivalent to full equality in JS)

class Demo{
    public void static main(String[] args) {
        int a = 10;
        int b = 11;
        System.out.println(a > b); //f
        System.out.println(a < b); //t
        System.out.println(a != b); //t
        System.out.println(a <= b); //t
        System.out.println(a >= b); //f
        System.out.println(a == b); //f
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

4.6. Logical operators

Logical operators:

&: with

|: or

! : Non

^: Iso-or

Purpose: To concatenate multiple comparison expressions -> and finally return a boolean result.

In math 1 < m < 10 is correctly written this way, but it is not allowed in Java.

m > 1 & m < 10 (m must be greater than > 1 and & < less than 10)

class Demo{
    public void static main(String[] args) {
        int a = 10;
        int b = 20;
        // &: (and) concatenate multiple relational expressions and the conditions must hold.
        System.out.println(a > b & a < b); //f : t = f
        System.out.println(a > b & a > b); //f : f = f
        System.out.println(a < b & a < b); //t : t = t
        System.out.println(a > b & a > b); //t : f = f
        // |: (or) only one of the two sides needs to hold and if one is t it is t
        System.out.println(a > b | a < b); //f : t = f
        System.out.println(a > b | a > b); //f : f = f
        System.out.println(a < b | a < b); //t : t = t
        System.out.println(a > b | a > b); //t : f = f
        // ! : (non) t for f; f for t
        System.out.println("-------------\n" + !true);
        System.out.println(!!true);
        // ^: (different or) same f; different t
        System.out.println(a > b ^ a < b); //f : t = t
        System.out.println(a > b ^ a > b); //f : f = f
        System.out.println(a < b ^ a < b); //t : t = f
        System.out.println(a > b ^ a > b); //t : f = r
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

4.7. Logical operations of short-circuit and

&&: short-circuit vs: false jump out directly

||: short-circuit or : true is skipped directly, the expression is true.

Function: Same as & and |; however, && and || have the effect of a short circuit!

class Demo{
    public void static main(String[] args){
        int a = 10;
        int b = 20;
        boolean b1 = (a > 11) & (++b >10);
        boolean b2 = (a > 11) && (++b >10);
        System.out.println(b);
    } 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

4.7. Ternary operators

Format: relational expression ? Expression 1 : Expression 2

Execute the process:

first determine the result of the relational expression (true | false); if true return the value of expression 1, if false return the value of expression 2

Ternary operators must ultimately return a value, which must be received by a variable.

class Demo{
    public void static main(String[] args) {
        int a = 10;
        int b = 20;
        // Output maximum value
        int flag = a > b ? a : b;
        System.out.println("The maximum value is:" + flog);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

5. Circulation

5.1 Process control statements

Controlling the flow of program execution

Purpose: to get the results we want

  • sequential structure
  • Branching structure: (if,switch)
  • Loop structure: (for,while,do...while)

5.2 Branching structure-if

#### Syntax of Branching Structures 1:

/*
if (relational expression) {
Body of code; }
}
*/
//Case: Determining age for internet access (>18)
// Define age
int age = 10;
if(age >= age){
    System.out.println("Internet access!");
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Execute the process:

  1. Judgment The result of the relational expression
  2. If true-enters the loop body and executes the
  3. If false, do not enter the loop body.
Branching structure if grammatical structure 2:

if(relational expression){

Loop statement 1

}else{

Loop statement 1

}

Execute the process:

  1. The result of the judgmental discriminant expression: t | f
  2. If it is t, execute the loop statement 1
  3. If f, execute loop statement 2
int age = 10;
if(age >= age){
    System.out.println("Internet access!");
} else{
    System.out.println("No internet access!");
}
// Judge parity % == 0
//1. Define a variable
int num = 100;
//2. Judgement
if(num % 2 == 0){
    System.out.println(num + "Yes oh number.");
} else {
 	System.out.println(num + "Not even.");   
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
Branching structure if grammatical structure 3:

multiconditional judgment

if(conditional expression1){
    code fast1;
}else if(conditional expression2){
    code block2;
}
...
else{
    code block3;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Case Need: Categorizing Class Achievement

90 — 100 :A

70 - 90 (excluding 90): B

60 - 70 (excluding 70): C

60 Below: D

import java.util.Scanner;

class Demo{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a grade (0 ~ 100):");
        int score = sc.nextInt();
        if(score >= 0 && score <=100){
            if(score >= 90 && score <= 100){
                System.out.println("A");
            } else if(score >= 70 && score < 90) {
                System.out.println("B");
            } else if(score >= 60 && score < 70) {
                System.out.println("C");
            } else {
                System.out.println("D");
            }
        } else {
            System.out.println("Please enter a valid grade~~~");
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

Execute the process:

  1. First determine the conditional expression 1: if the result is t execute code fast 1; then directly end the if branch structure
  2. If false in the judgment of the conditional expression 2, if the result is t to execute the code fast 2; if f to judge the conditional expression 3....
  3. If none of the above conditions are sufficient, directly execute the code block in else

5.3 Branching structure - switch

Grammatical structure;

switch(conditional expression|variable){

case value 1.

Code Blocks.

​ break;

case value 2.

Code Blocks.

​ break;

​ …

​ default:

Code Blocks.

​ break;

}

Formatting Instructions:

  1. Expression | Variable byte, short, char, int, enum, string
  2. case: the value that follows needs to be matched with the value that follows switch
  3. break: ends the switch statement
  4. default: If none of the above values are matched, default is executed, similar to else in if.

Execute the process:

  1. Get the value after the switch first
  2. Match the value following the case;
    • A successful match executes the following block, and then break is executed, ending the switch loop.
  3. If none of the matches are successful the contents of the default statement block are executed;
/*
Requirement:Keyboard entry of week number to show today's weight loss activity
Weight loss program:
Monday: running
Tuesday: Swimming
Wednesday: Jogging
Thursday: cycling
Friday: Boxing
Saturday: Hiking
Sunday: eat a good meal!!!
*/

import java.util.Scanner;
class Demo{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the day of the week:");
        int week = 0;
        switch(week){
                case 1:
                	System.out.println("Monday: running.");
                	break;
                case 2:
                	System.out.println("Tuesday: Swimming");
                	break;
            	case 3:
                	System.out.println("Wednesday: slow walk.");
                	break;
            	case 4:
                	System.out.println("Thursdays: Motion Cycling.");
                	break;
            	case 5:
                	System.out.println("Friday: Boxing");
                	break;
            	case 6:
                	System.out.println("Saturday: Climbing.");
                	break;
            	case 7:
                	System.out.println("Sunday: a good meal!!!");
                	break;
                default :
                	System.out.println("Please enter the correct day of the week:");
                	return;
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

A switch-case passthrough removes the break in the case, then the program will not end and will continue down the line, knowing that default

5.4. Loop-for

Loops: doing something over and over again; for loops, do...while loops, while loops

5.4.1. for loop

Format:

for(initialization statement; conditional judgment; control condition) {

Circulators;

}

Flowchart of for loop execution:

[External link image transfer failure, the source site may have anti-piracy chain mechanism, it is recommended to save the image directly uploaded (img-4iQ4Uo0U-1684429487403) (C:\Users\Administrator\AppData\Roaming\)Typora\typora-user-images\)]

Splitting of for

  1. Initialization statement: initial condition of the for loop,int i = 1;
  2. Conditional Judgment Statements: Execution and End Conditions for Loops
  3. Loop body: doing something repeatedly;
  4. Control conditions: control the number of executions!!!!

The execution flow of the for loop:

  1. The initialization statement is executed first, and only once.
  2. Execute conditional judgment statement: boolean
    • If the condition is: false-> the loop just ends.
    • If the condition is: true -> then it will enter the loop body and execute the loop body.
  3. Execute control conditions ++ | - -
class Demo{
    public static void main(String[] args){
        for(int i = 0;i < 5:i++){
            System.out.println("HelloWord!!!");
        }
        
        //Case: Finding the sum of 1-5
        int sum = 0;
        for(int i = 0;i < 5:i++){
            sum += i;
        }
        System.out.println(sum);
    
        sum = 0;
    	for(int i = 1;i <= 100;i++){
            if(i % 2 == 0){
                sum += i;
            }
        }
        System.out.println(sum);
        
        //Optimization
        for(int i = 0;i <= 100;i+=2) {
            sum += i;
        }
        System.out.println(sum);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
5.4.2. The case of the for loop (getting the number of daffodils)
/*
The so-called daffodil: 1. three-digit number 2. the cubic sum of the digit ten hundred is equal to itself
Ri: 153 = 1*1*1 = 5*5*5 + 3*3*3
Requirement:Print the number of all daffodils
Idea Analysis:
1, extract all three digits in the natural numbers
for(int i = 100; i < 1000;i++){
Determine the cube of the first digit + the cube of the tenth digit + the cube of the hundredth digit = itself
}
2, take the remainder of each digit
3、Output
*/
class TheNumberOfDaffodilsDemo{
    public static void main(String[] args) {
        for(int i = 100;i < 1000) {
            int sum = 0;
            int best = i /100 % 10;
            int ten = i / 10 % 10;
            int num = i % 10;
            if((best * best * best + ten * ten * ten + num * num * num) == i) {
                System.out.println("The daffodil count has:" + i);
                sum += i;
            }
        }
        System.out.println("In total." + sum + "A daffodil.");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
5.4.3. for loop summary
  • Write for loops in general: declare the end condition (i < 100)
  • See Summation or Statistics ....
  • 1. Define summation variable | statistics variable outside the loop // output outside the loop

##5.5. Loop-while

Format:

Initial conditions;

while(conditional judgment){

Circulators;

Control conditions;

}

Execute the process:

  1. Load initial conditions
  2. Get conditional judgment result (true | false)
  3. If and if false loop ends
  4. If the result is true, the contents of the loop body are executed.
  5. Execution of control variables; - Continuation of conditional judgment

To summarize: the execution process is 1,2,3,4,5 -> 2,3,4,5 -> 2,3,4,5...

//case: use while loop to output five helloworld

class demo{
    public static void main(String[] args){
        int i = 1;//Initial conditions
        while(i <= 5){//Judgment
            System.out.println("HelloWorld");// Loop body
            i++;// Control variables
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

####5.5.1, the case for while:

Requirements: The highest peak in the world is Mount Everest (8844.43 meters = 8844430 mm), if I have a piece of paper that is large enough, it is 0.1 mm thick, ask me how many times this can be folded to the height of Mount Everest.

/*
Case Study:
1, define an initial condition: double paper = 0.1; statistics variable int count = 0;
2, the termination condition of the loop (paper < = 8844430) { loop body; count + + +; control statement paper * = 2; }
3, sout output
*/

double paper = 0.1;
int count = 0;
while(paper <= 8844430) {
    count++;
    paper *= 2;
}

System.out.println(count + "Subequal to the height of Mount Everest;");
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

5.6. do...while loop

Structure:

  1. Initial conditions do{
  2. Circulators;
  3. control variable
  4. }while(conditional judgment).

Execute the process:

  1. Enforcing initialization conditions
  2. executing loop body
  3. Implementation Control Variables
  4. Conditional judgment (true | false)
  5. True returns to 2 and continues; false exits the loop.
//Use do.... . while outputs HelloWorld 5 times.
int i = 1;
do{
    System.out.println("HelloWorld");
    i++;
} while(i <= 4);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

6、Method(method)

6.1 Overview of the methodology

Methods: It is a set of codes with independent functions that are quickly composed into a whole so that it has a special function.

Methods: Code blocks with independent functions

Purpose: Improve code reusability

Methods need to be defined before they can be called

6.2 Definition and invocation of methods

6.2.1 Definition of Methods without Return Value

A common format for defining methods:

Modifier Return value type Method name (parameter list) {

Method body.

return Return Value.

}

6.2.2 Parameter-less and return-value-less methods
// Format
/*
modifier void method-name(){
method body; }
}
*/
public static void printArray(){
    methodology;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  1. public static void fixed write
  2. Method name - identifier (see name)
  3. Method Body - Code Block

The method is defined and needs to be called before it will output the

Calling method names directly with the static keyword

public static void main(String[] args) {
        testStudy();
    }

    // Define a learning methodology
    public static void testStudy(){
        System.out.println("I'm studying, please don't disturb.");
        testEct();
    }

    // Define a method for eating
    public static void testEct(){
        System.out.println("I'm eating and urging you to be kind.");
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  1. The main method has a hierarchical relationship with custom methods, so methods cannot be nested.
  2. The main method is the main entry point of the program, so we call the other methods in the main method

Methodology Exercise:

Case in point: determining parity

public class Exercise01 {
    public static void main(String[] args) {
        testEventNumber(22);
    }

    public static void testEventNumber(int num){
        System.out.println(num % 2 == 0 ? "Even." : "Odd numbers.");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
6.2.3 Method Definition and Invocation with Parameters
public static void method name (parameter 1) {
Method body; }
}
public static void method name (parameter 1, parameter 2, parameter 3...) {
method body; }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Parameter list:

  1. Type of parameter
  2. Number of parameters
  3. Order of parameters
public static void print(int a,boolean b) {
    methodology;
}
// Calling methods with parameters
method name(parameters);
print(10,true)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
6.2.4. Shape and participation in real parameters

Formal Parameters: Parameters passed by the method definition - Formal Parameters

real parameter: the parameter passed to the method call - real parameter (10, a (must be a variable that has been assigned a value))

//print all odd numbers between x - y
/*
    1, according to the format of the definition of the method, the method name printOddNumber
    2, define the formal parameters of the method (parameter list) two int x y
    3, method body for -- x --y
    4, judgment on ! (2 % == 0) Odd number
    5, in the main method to call this method
 */
public class MethodTest002 {
    public static void main(String[] args) {
        printOddNumber(1 ,100);
    }

    public static void printOddNumber(int x,int y){
        for (int i = x; i < y; i++) {
            if (!(i % 2 == 0)) {
                System.out.print(i + " ");
                if (i % 9 == 0) {
                    System.out.println();
                }
            }
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

####6.2.5, Definition of methods with return values

Define the format:

public static Data type of return value Method name (formal parameter) {

Methodology Body;

return The return value;

}

  1. The data type of the return value: that is, the data type of the data pair printed after the return (implicit conversion)
  2. Formal parameters: 1. parameters according to the data type, 2. number of parameters, 3. parameters according to the order of precedence
  3. return: keyword used to return the result of the method and also to end the method
// Example:
public static int getSum(int a,int b){
    int sum = a + b;
    return sum;
}
    getSum(20,40);// No substantive significance
//Methods with return values are recommended to be received using variables.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
/*
Getting the maximum of two numbers (method)

Idea Analysis:
1, define a method and with a return value int to find the maximum value testMax ()
2, define the formal parameters int num1, int num2
3, if the comparison to get the maximum value
4, the main method call

 */
public class Exercise02 {
    public static void main(String[] args) {
        System.out.println("Please enter a number.");
        int num1 = new Scanner(System.in).nextInt();
        System.out.println("Please enter a number.");
        int num2 = new Scanner(System.in).nextInt();
        int max = testMax(num1, num2);
        System.out.println(max);
    }

    public static int testMax(int num1, int num2) {
        /*if (num1 > num2) {
            return num1;
        } else {
            return num2;
        }*/
        int max = num1 > num2 ? num1 : num2;
        return max;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
6.2.6, method (method) details
  1. Common Format for Methods

    • public static Return value type Method name (parameter list) {

      Method body.

      return The return value;

      }

      1. The public static keyword, which serves to modify the access scope of the
      2. Return Value Type
        • method has a return value, you need to define the return value type
        • A method with no return value is void
      3. Method names (identifiers): the names should be seen and understood, following the little hump getNum() getName()
      4. Parameter list:
        1. Data type of the parameter
        2. Number of parameters
        3. Position of the parameter
      5. Method body: the block of code that accomplishes the function
      6. return: used to return the result of the method
  2. The method of definition requires two clear

    1. Clarify the data type of the return value
      • Write the corresponding data type if you have it, or viod if you don't.
      • You must write return if you have a return value.
    2. Clarify the parameter list (formal parameter) of the method
      • Data type of the parameter
      • Number of parameters
      • Position of the parameter
  3. invoke a method

    1. Methods with no return value (void) -> directly the method name ().
    2. Methods with Return Values -> Define variables to receive the results of the method's return
  4. Methods cannot be nested

    • The main method is a method, and the self-defined method is also a method, a hierarchical relationship
    • The main method is the main entry point of the program, and you need to call other methods in the main method.
  5. return

    • Must write return if there is a return value (compilation error)
    • No return value, not mandatory to write return, (generally not written)
    • Uninstalling code after return is generally considered invalid
6.2.7 Overloading of methods

Method Overloading:

  1. in the same class
  2. Existence of methods with the same name
  3. The parameter list is different

Advantage of method overloading: no need to memorize large, cumbersome method names

/*
    Requirement: Use method overloading to design methods that compare two integers to see if they are the same, mitigating oh that full integer type (byte,short,int,long)

    Ideas to analyze:
        1, determine the return value type boolean
        2, the list of parameters two different data types
 */
public class ExerciseMethod01 {
    public static void main(String[] args) {
        System.out.println(testCompare((byte) 10, (byte) 10));
        System.out.println(testCompare((short) 10, (short) 10));
        System.out.println(testCompare(10, 10));
        System.out.println(testCompare(10L, 10L));
    }

    public static boolean testCompare(byte b1,byte b2){
        System.out.println("---byte---");
        return b1 == b2;
    }
    public static boolean testCompare(short s1,short s2){
        System.out.println("---short---");
        return s1 == s2;
    }
    public static boolean testCompare(int i1, int i2){
        System.out.println("---int---");
        return i1 == i2;
    }
    public static boolean testCompare(long l1,long l2){
        System.out.println("---long---");
        return l1 == l2;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
6.2.8 Passing method parameters

Recap:

  1. Defined methods: formal parameter
    • Basic data type: does not change the actual parameter result.
      • Reason: each method has a separate stack, which is recycled when the method runs out
    • Reference data types: reference data types -> will change the actual parameters according to the results.
      • Reason: the reference data type of the passing parameter, passed in the address value, the memory will cause the effect of two references pointing to the same memory, so even if the method pops the stack, the data in the heap memory is already the result of the modification.
  2. Calling a method: real parameters are the parameters passed when calling the method (1, constants 2, variables after initialization)
6.4.9. Variable-length parameters of methods

Elicitation of variable length parameters

Define a sum of 2 numbers; define a sum of 3 numbers; define a sum of 4 numbers; define a sum of 5 numbers ...

Parameter list is too cumbersome. Not good for code robustness

Putting a (int...arr) variable-length parameter directly in the parameter list ... greatly reduces the redundancy of the code

public static int testSum(int...arr){
    //1. Definition of summation
    int sum = 0;
    //2. Iterating through arrays
    for(int i = 0;i < arr.length;i++) {
        sum += arr[i];
    }
    //3. Sum of returns
    return sum;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  1. Variable-length parameters, can be written without parameters or with more than one
  2. It can also be used as a method overload
  3. Variable parameters are consistent with the method's set of formal parameters and cannot be declared at the same time; a variable parameter is essentially an array of
  4. Only one variable parameter can be declared as a formal parameter of a method.
  5. As a formal parameter of a method, the variable parameter must be placed in the last position of the formal parameter

7.3 Summary of methodology

  1. methodologies

    • Code blocks with independent functions {}, purpose: to improve reusability
  2. Define the method:

    • public static Return Value Type Method Name(parameter list|formal parameter){
          methodology;
          return return value;
      } 
      
      • 1
      • 2
      • 3
      • 4
  3. Usage

    • Methods with no return value (void) - use the method name directly
    • Methods with a return value - typically received using a variable
  4. Methodological details

    • Methods are hierarchical and cannot be nested.
    • If you have a return value, write the return value type; if you don't have a return value, just use void.
    • There is a return value must be used return, no return value is generally not written;
  5. method's formal and real parameters

    • Formal parameters of a method: when defining a method, it is written as a formal parameter (formal parameter list) - 1, accepting the passed real parameters 2, constraining data types
    • Real parameters of a method: parameters passed when calling the method, (1, constants 2, variables after initialization)
  6. Overloading of methods (conditions)

    • Must be in the same class
    • Consistent method names
    • The list of formal parameters is different
      • Different data types
      • The location of the data is different
      • Number of parameters
    • Advantage: no need to memorize tons of method names
  7. parameter passing

    • Formal parameters are basic data types, modifying a formal parameter will not affect a real parameter.
    • Formal parameters are used for data of type used, modifying a formal parameter will change the real parameter.