Java Basics (unfinished to be updated)

1, java overview

1.1 Java Language Overview

Java is not only a high-level programming language, but also an object-oriented programming language. Java language is a high-level programming language launched by Sun Corporation (Stanford University Network) in 1995. James Gosling, one of the co founders of the Java language, is known as the father of Java. Java language version: 1.0-1.4, 5.0... 8.0... 16.0. The jdk version used in this note is 8.0.

1.2 Java language platform version

JavaSE(Java Platform Standard Edition) Standard Edition

It is a solution for developing ordinary desktop and business applications
The technical system is the basis for others to complete the development of some desktop applications

JavaME(Java Platform Micro Edition) Mini Edition

It is a solution for the development of consumer electronics products and embedded devices, which has been supported by Android IOS

Java EE (Java Platform Enterprise Edition) Enterprise Edition

It is a set of solutions for developing applications in enterprise environment

1.3 characteristics of Java language

Simplicityobject-orientedDistributed
Cross platformMultithreadingDynamics
RobustnessSecurity

1.4 cross platform implementation principle of Java language

(1) JVM: Java virtual machine, which is specially used to run Java programs.
(2) Platform: refers to the operating system, such as Windows, linux, MacOS, etc.
(3) Cross platform: a Java program we write can run on multiple operating systems, compile once and run everywhere.

1.5 composition and function of JDK, JRE and JVM

1.JVM: Java virtual machine, which is specially used to run Java programs, but cannot be installed separately.
2.JRE: Java runtime environment, including JVM(Java virtual machine, which is specially used to run Java programs) and core class library.
3.JDK: Java development kit, including JRE and development tools.

Three relationships: JDK > JRE > JVM

2, Construction of development environment

2.1 JDK installation

matters needing attention:

1. Note that the operating systems are Windows, linux and MacOS
2. Note whether the number of bits of the operating system is 32 bits or 64 bits
3. When installing java related software: Chinese and spaces are not allowed in the installation path (any development software should not be installed in the Chinese path)


The default path installation is the next step. The only thing to note is that version 8 installation will install jdk and jre. If the custom path needs to be created and saved separately

2.2 use of common DOS commands

How to open the command line window:

  • win + r open the run window, enter cmd and press enter.

Common dos commands

operationexplain
Drive letter name:E: Press enter to switch to disk E.
dirView the contents of the current path.
cdThe directory enters a single level directory. cd JavaSE
cd...Go back to the previous directory.
cd directory 1 \ directory 2Enter the multi-level directory. cd JavaSE\baiyunshan
cd\Go back to the drive letter directory.
clsClear the screen.
exitExit the command prompt window.

2.3 configuration steps

First, right click this computer - > select properties - > Click advanced system settings on the left - > Click environment variables - > click New in system variables below

The new variable name is [JAVA_HOME]. For the variable value, click [browse directory] and select the jdk installation path and jdk folder
Then click OK

Find path to write% JAVA_HOME%\bin; , Put it at the front and don't forget to add a semicolon in English

jdk environment configuration

JAVA_HOME: used to configure the jdk installation path and provide third-party software support

Classpath: the default configuration after JDK1.5 does not need to be configured (if the configuration is correct), and the generation location after source code compilation is configured

PATH: enables the bin tool to be used in any PATH

Note: after modifying the environment variable, you need to reopen the cmd window

2.4 test development environment

Verified by javac and java commands
Note: if you are prompted that < javac is not an internal or external command >, the reason is that the path is incorrectly configured, just re configure it according to the steps in the previous step!
Avoid all files with names beginning with java in C:\WINDOWS\system32. If any, delete them;
Note: the jdk should not be installed in the path with Chinese characters, and it is better to install in the English path without space characters;


3, HelloWorld starter

3.1 procedure development

1. Source code:
A program written by a programmer;
Programmers can see and understand the program;
Procedures: letters, numbers and other symbols;
The source program is written by the programmer. The programmer can see and understand that the program is essentially a text file, but the extension is not. txt, but. java.
2. Generate bytecode (. class) files that can be executed by the JVM
JVM: called Java virtual machine, it is specially used to run Java programs. However, the JVM is a binary and can only recognize 0 and 1. The files storing 0 and 1 are called bytecode files (. class files)
How to translate the source file (program) into a bytecode file (program) that the JVM can execute? Use javac command (compile command) and format: javac file name. Java. For example, compile HelloWorld.java source file: javac HelloWorld.java to generate a bytecode file: HelloWorld.class
3. Submit the bytecode file to the JVM for execution
Whether the source file (program) or bytecode file (program) is stored in the hard disk? It will not be executed automatically. How to hand over the bytecode file to the JVM for execution? Use the java command (run the command). Use format: java file name example: java HelloWorld

3.2 writing HelloWorld program

1. Prepare source documents. Create a text file named HelloWorld.txt, change the extension to. Java, open the HelloWorld.java source file, enter the following content, and save (ctrl+s).

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

2. Compile: javac command. Produce the corresponding. class file (bytecode file) according to the. Java source file. Use the format of javac command: javac file name. Java. javac HelloWorld.java.
be careful:
Ensure that the javac command in the current path can be used.
Ensure that there are source (. java) files to be compiled in the current path.
When compiling javac commands, the extension. java must be written after the file name.

3. Run: java command. Give the bytecode (. class) file to the jvm for execution. Use the format of java command: java file name, java HelloWorld. Also note:
Ensure that java commands in the current path can be used.
Ensure that there is a bytecode (. class) file to run in the current path.
When using the java command, the extension. class cannot be written after the file name.

3.3HelloWorld FAQs

1. Case. The Java language is case sensitive (case sensitive)
2. Illegal characters. Symbols in Java are in English format
3. Display the file extension in the system to avoid HelloWorld.java.txt file
4. The java file name after compiling the command needs to have the file suffix. Java
5. The class file name (class name) after running the command does not have the file suffix. Class

4, java basic syntax

4.1 notes

4.1.1 concept

Add written explanation and explanation text in the process of code writing

4.1.2 features

Adding comments to the code can improve the readability of the code. Comments contain information about the program, which can help programmers better read and understand the program. Comments can be added anywhere in the Java source program file, and the java compiler does not compile comments in the code, that is, comments in the code do not have any impact on the program. Therefore, developers can not only write code description text and designer's personal information in comments, but also use comments to shield some unwanted code.

4.1.3 classification

  • Single-Line Comments

The format of a single line comment is / / and the text from / / to the end of the line will be used as the comment text

// This is single line annotation text
  • multiline comment

The format of a multiline comment is to enclose a long comment with / * and * /

/*
This is multiline annotation text
 This is multiline annotation text
 This is multiline annotation text
*/
// Note: multiline comments cannot be nested.
  • Documentation Comments

Document comments start with / * * and end with * /. When document comments appear before declarations (such as class declaration, class member variable declaration, class member method declaration, etc.), they will be read by Javadoc document tool as Javadoc document content. The format of a document comment is the same as that of a multiline comment. For beginners, document comments are not very important. Just understand them.

/**
   This is the content of the document comment
*/

Note: be sure to develop good coding habits. The software coding specification mentions readability first and efficiency second, so programmers must add appropriate comments to the program to improve the readability and maintainability of the program. It is suggested that the total amount of comments in the program should account for 20% ~ 50% of the total amount of program code.

4.2 keywords

4.2.1 concept

Keywords are words that have been given special meaning in java

4.2.2 features

All letters of the keyword are lowercase
Single word
Common code editors highlight keywords

4.2.3 keyword list

Common keywords 51 keywords + 2 reserved words
2 reserved words conest goto

4.3 identifier

4.3.1 concept

Identifier can be simply understood as a name, which is used to identify the valid character sequence of class name, variable name, method name, array name, etc.
It can also be understood that all that we name during java code writing can be called identifiers

4.3.2 naming rules

It is composed of letters, numbers, underscore "" and dollar sign "$". The first character cannot be a number.
Keywords in java cannot be used as identifiers.
Identifiers are case sensitive (case sensitive).

4.3.3 naming conventions

See the meaning of the name: know the corresponding function of the identifier according to the name
Hump naming method: if the identifier consists of multiple words, the first letters of other words are capitalized except the first letter of the first word passWord

With the development of java, java programmers have defined default specifications (Jianghu rules) for different identifiers on the basis of following the existing specifications

Class name: usually a noun is used. The first word must be capitalized and the first letter of subsequent words must be capitalized. (large hump type)
Method name: usually use verbs. The first word is lowercase and the subsequent words are capitalized. (small hump type)
Package name: usually the domain name inverted by the company, such as: con.baidu. Department name. Function name
Variable: the first word is lowercase and the subsequent words are uppercase. (small hump type)
Constant: all letters are capitalized.
Word splicing: usually use userLastName to splice words instead of user_last_name.

4.4 constants

4.4.1 concept

The amount that cannot be changed during program execution is called a constant

4.4.2 classification

4.4.2.1 classification by data type

string constant

Multiple characters enclosed in double quotation marks (can contain 0, one or more characters), such as "a", "abc", "China", etc

integer constant

Integer, for example: - 10, 0, 88, etc

Decimal constant

Decimals, such as: - 5.5, 1.0, 88.88, etc

character constants

A character enclosed in single quotation marks, such as' a ',' 5 ',' B ',' medium ', etc

Boolean Literals

Boolean value, indicating true and false. There are only two values: true and false

Null constant

A special value, null, null

4.4.2.2 classification according to writing method

Default constant

In the process of program writing, there is no need to define constants that can be used directly. The above constants can be regarded as default constants

Custom constant

Constants defined using the keyword final are defined through code definition

4.5 data type

4.5.1 concept

Java is a strongly typed language, which specifies the scope of each kind of data. Its data type must be specified when writing code to store data

4.5.2 classification

java data types are divided into two categories: basic data types and reference data classes
Basic data types are divided into four categories and eight types
Reference types are mainly classes in object-oriented

4.5.3 value range

For the actual range of value range in java, you only need to know the common range
Integer type value range: - 2-digit power - 1 ~ 2-digit power - 1 - 1 (digits are memory occupation * 8)
The value range of character type is 0 ~ 65535 (i.e. 0 ~ 231)

4.6 variables

4.6.1 concept

The quantity that can be changed during the running of the program is called a variable. Similar to x in mathematics, it can be saved in the form of declared variables in java according to the calculation results

4.6.2 format of variable definition

  • Format I

The declaration and assignment of variables are carried out together
Data type variable name (identifier) = value;
int x=1;

  • Format II

Write the declaration and assignment of variables separately
Declaration: data type variable name (identifier);
Assignment: declared variable name = value;
Note: variables can be declared without assignment, but if variables are used, they must be assigned before use
int x;
x=1;

  • Format III

Declare to create multiple variables of the same type and assign values at the same time (you can also declare only without assigning values)
Data type: variable name = value, variable name = value;
int a=1,b=2,c=3;

4.6.3 precautions

  1. Variable names cannot be repeated in the same pair of curly braces.
  2. Variables must be initialized (assigned) before they can be used.
  3. When defining a variable of type long, you need to add L after the integer (both case and uppercase are recommended). Because integers are of type int by default, integers that are too large may exceed the int range.
  4. When defining a variable of float type, you need to add F after the decimal (both case and uppercase are recommended). Because the default type of floating point number is double, and the value range of double is greater than float, the types are incompatible.
  5. Variables actually store the address of data and modify the address

4.7 data type conversion

4.7.1 concept

java is a strongly typed language. When declaring variables to save data, you need to declare the type of data to save, so that the jvm can open up a corresponding data space for data storage. However, sometimes the data type used in the declaration does not match the final type (often between integers and decimals of the same type). At this time, you need to use type conversion, Convert the data type to the type we need

4.7.2 classification

  • Automatic type conversion (implicit conversion)

Assign a value or variable representing a small data range to another variable representing a large data range. This conversion method is automatic and can be written directly without special grammatical format

Example

double num1 = 5.5;
int num2 = (int) num1; // Cast num1 of type double to type int
System.out.println(num2); // Output 5 (decimal places are discarded directly)
  • Cast (explicit)

Assign a value or variable representing a large data range to another variable representing a small data range. Because the data type stores the upper limit of data, this type conversion may cause data overflow, so additional syntax needs to be defined for writing


Cast considerations

The conversion of char type data to int type is calculated according to the corresponding int value in the code table. For example, in the ASCII code table, 'a' corresponds to 97.

int a = 'a';
System.out.println(a); // Output 97

Integers are of type int by default. byte, short and char data will be automatically converted to type int.

byte b1 = 10;
byte b2 = 20;
byte b3 = b1 + b2; 
// The third line of code will report an error, b1 and b2 will be automatically converted to int type, and the calculation result is int. the assignment of int to byte requires forced type conversion.
// Amend to read:
int num = b1 + b2;
// Or:
byte b3 = (byte) (b1 + b2);

boolean type cannot be converted to other basic data types.

4.8 operators

4.8.1 concept

  • operator

A symbol that operates on a constant or variable

  • expression

Using operators to connect constants or variables, formulas that conform to java syntax can be called expressions. Expressions connected by different operators represent different types of expressions.

4.8.2 classification

4.8.2.1 arithmetic operators

Symboleffectexplain
+plusAdd data type variables. If it is a string, it becomes a connector
-reduceSubtract data type variables
*rideMultiply data type variables
/exceptDivide data type variables
%SurplusGet the remainder of the division of two data

matters needing attention
/Difference between% and%: divide the two data, / take the quotient of the result, and% take the remainder of the result.
Integer operation can only get integers. To get decimals, floating-point numbers must be involved in the operation.

Example

int a = 10;
int b = 3;
System.out.println(a / b); // Output result 3
System.out.println(a % b); // Output result 1
  • Character "+" operation

The char type participates in arithmetic operations

The decimal value corresponding to the bottom of the computer is used. We need to remember the values corresponding to three characters

  • 'a' – 97 a-z are continuous, so the corresponding value of 'b' is 98 and 'c' is 99, which are added successively
  • 'a' – 65 A-Z are continuous, so the corresponding value of 'B' is 66 and 'C' is 67, which are added successively
  • '0' – 48 0-9 are continuous, so the corresponding value of '1' is 49 and '2' is 50, which are added successively
// You can use characters and integers to do arithmetic operations to get the value corresponding to characters
char ch1 = 'a';
System.out.println(ch1 + 1); // Output 98, 97 + 1 = 98

char ch2 = 'A';
System.out.println(ch2 + 1); // Output 66, 65 + 1 = 66

char ch3 = '0';
System.out.println(ch3 + 1); // Output 49, 48 + 1 = 49
  • Arithmetic expression

When an arithmetic expression contains values of different basic data types, the type of the entire arithmetic expression will be automatically promoted.

Promotion rules

byte Type, short Type and char Type will be promoted to int Type, regardless of whether other types participate in the operation.
The type of the entire expression is automatically promoted to the same type as the highest level operand in the expression

Rank order: byte,short,char --> int --> long --> float --> double

Example

byte b1 = 10;
byte b2 = 20;
// byte b3 = b1 + b2; //  An error is reported in this line because byte type participates in arithmetic operation and will be automatically prompted as int. assigning int to byte may lose precision
int i3 = b1 + b2; // int reception should be used
byte b3 = (byte) (b1 + b2); // Or cast the result to byte type
-------------------------------
int num1 = 10;
double num2 = 20.0;
double num3 = num1 + num2; // Use double to receive because num1 is automatically promoted to double type

Because of the above reasons, we rarely use byte or short types to define integers in program development. Char type is rarely used to define characters, but string type is used, and char type is not used for arithmetic operations.

  • "+" operation of string

When a string appears in the "+" operation, the "+" is a string connector, not an arithmetic operation.

System.out.println("Amour Love empty"+ 666); // Output: Amour love empty 666

In the "+" operation, if a string appears, it is a connection operator, otherwise it is an arithmetic operation. When the "+" operation is performed continuously, it is performed one by one from left to right.

System.out.println(1 + 99 + "Amour Love empty"); // Output: 100Amour
System.out.println(1 + 2 + "Amour Love empty" + 3 + 4); // Output: 3Amour love empty 34
// You can use parentheses to change the priority of an operation 
System.out.println(1 + 2 + "yunhe" + (3 + 4)); // Output: 3Amour love empty 7

4.8.2.2 assignment operator

SymboleffectExampleequivalence
+=The addition result is assigned to the lefta += b;a = a + b;
-=The subtraction result is given to the lefta -= b;a = a - b;
*=The multiplication result is given to the lefta *= b;a = a * b;
/=The division result is assigned to the lefta /= b;a = a / b;
%=The remainder result is given to the lefta %= b;a = a % b;
&=And the results are given to the lefta &= b;a = a & b;
|=Or the result is given to the lefta |= b;a = a
^=The XOR result is assigned to the lefta ^= b;a = a ^ b;
<<=Move left results in lefta <<= b;a = a << b;
>>=Shift right results in lefta >>= b;a = a >> b;
>>>=Unsigned shift right results in lefta >>>= b;a = a >>> b;

be careful
The extended assignment operator implies a cast.

Example

short s = 10;
s = s + 10; // This line of code is reported because s is promoted to int type in the operation, and the assignment of int to short may lose precision
s += 10; // There is no problem with this line of code, which implies forced type conversion, which is equivalent to s = (short) (s + 10);

4.8.2.3 self increasing and self decreasing operators

Self increasing and self decreasing operators are monocular operators, which can be placed before or after variables. The function of self increasing and self decreasing operators is to increase or decrease the value of a variable by 1.

Symboleffectexplain
++Self increasingAdd 1 to the value of the variable
Self subtractionThe value of the variable minus 1

matters needing attention

++And -- can be placed either behind the variable or in front of the variable.
When used alone, + + and -- whether placed before or after variables, the result is the same.
When participating in the operation, if it is placed behind the variable, take the variable to participate in the operation first, and then take the variable as + + or –.
When participating in the operation, if it is placed in front of the variable, take the variable as + + or –, and then take the variable to participate in the operation.
The most common usage: use alone.

The following are used in the operation:

Example

int i = 10;
i++; // Use alone
System.out.println("i:" + i); // i:11

int j = 10;
++j; // Use alone
System.out.println("j:" + j); // j:11

int x = 10;
int y = x++; // In the assignment operation, + + is behind, so the original value of x is used to assign to y, and x itself increases by 1
System.out.println("x:" + x + ", y:" + y); // x:11,y:10

int m = 10;
int n = ++m; // The assignment operation, + + is in the front, so the value of m increases automatically is assigned to n, and m itself increases by 1
System.out.println("m:" + m + ", m:" + m); // m:11,m:11

4.8.2.4 relational operators

There are six kinds of relational operators: less than, less than or equal to, greater than, equal to, greater than or equal to, and not equal to.

Symbolexplain
==a==b, judge whether the values of a and b are equal, true or false
!=a!=b. Judge whether the values of a and B are not equal. If true, it is false
>a> b. judge whether a is greater than b, true or false
>=a> = b, judge whether a is greater than or equal to b, true or false
<If a < b, judge whether a is less than b, true or false
<=A < = b, judge whether a is less than or equal to b, true or false

matters needing attention

The results of relational operators are boolean, either true or false.
Never mistakenly write "= =" as "=", "= =" is the relationship to judge whether it is equal, and "=" is the assignment.

int a = 10;
int b = 20;
System.out.println(a == b); // false
System.out.println(a != b); // true
System.out.println(a > b); // false
System.out.println(a >= b); // false
System.out.println(a < b); // true
System.out.println(a <= b); // true

// The result of relational operation must be of boolean type, so the operation result can also be assigned to a variable of boolean type
boolean flag = a > b;
System.out.println(flag); // Output false

4.8.2.5 logical operators

Logical operators connect the relational expressions of various operations to form a complex logical expression to judge whether the expression in the program is true or false.

Symboleffectexplain
&Logic andA & b, a and b are true, and the result is true, otherwise it is false
|Logical ora|b, a and B are false, and the result is false, otherwise it is true
^Logical XORa^b, the results of a and b are different and true, and the same is false
!Logical non! a. The result is opposite to that of A

Example

//Define variables
int i = 10;
int j = 20;
int k = 30;

//&"And", and the result is false as long as one value in the expression is false
System.out.println((i > j) & (i > k)); //False & false, output false
System.out.println((i < j) & (i > k)); //True & false, output false
System.out.println((i > j) & (i < k)); //False & true, output false
System.out.println((i < j) & (i < k)); //True & true, output true
System.out.println("--------");

//|"Or", or. As long as one of the values in the expression is true, the result is true
System.out.println((i > j) | (i > k)); //false | false, output false
System.out.println((i < j) | (i > k)); //true | false, output true
System.out.println((i > j) | (i < k)); //false | true, output true
System.out.println((i < j) | (i < k)); //true | true, output true
System.out.println("--------");

//^"XOR", the same is false, the different is true
System.out.println((i > j) ^ (i > k)); //false ^ false, output false
System.out.println((i < j) ^ (i > k)); //true ^ false, output true
System.out.println((i > j) ^ (i < k)); //false ^ true, output true
System.out.println((i < j) ^ (i < k)); //true ^ true, output false
System.out.println("--------");

//!  "Non", negative
System.out.println((i > j)); //false
System.out.println(!(i > j)); //! false, output true
  • Short circuit logic operator
Symboleffectexplain
&&Short circuit andThe function is the same as & but it has short circuit effect
||Short circuit orThe function is the same as | but has short circuit effect

In logic and operation, as long as the value of one expression is false, the result can be determined as false. It is not necessary to calculate the values of all expressions. Short circuit and operation have such effects, which can improve efficiency. Similarly, in logic or operation, once the value is found to be true, the expression on the right will no longer participate in the operation.

Logic and &, whether true or false on the left, must be executed on the right.

Short circuit &, if the left is true, execute on the right; If the left is false, the right is not executed. (leave is false)

Logic or |, whether true or false on the left, must be executed on the right.

Short circuit or 𞓜 if the left is false, execute on the right; If the left is true, the right is not executed. (if it is true, it is true)

int x = 3;
int y = 4;
System.out.println((x++ > 4) & (y++ > 5)); // Both expressions can operate
System.out.println(x); // 4
System.out.println(y); // 5

System.out.println((x++ > 4) && (y++ > 5)); // It can be determined that the result on the left is false, and the right does not participate in the operation
System.out.println(x); // 4
System.out.println(y); // 4

4.8.2.6 bit operators

Operators used for bitwise data evaluation (similar to logical operators)

Symbolexplain
&A & b, bitwise sum the values of a and b
|a|b, the values of a and B are or calculated bit by bit
~~a. Invert the a value bit by bit
^a^b, XOR the values of a and b bit by bit
//Bitwise Operators 
//After converting decimal data into binary, the corresponding operation is carried out bit by bit
public class Test5 {
	public static void main(String[] args) {
		//The binary of the result is automatically converted to decimal output
		// 6->0110
		// 3->0011
		//0 stands for false and 1 for true
		
		//6&3 0010->2
		System.out.println(6&3);
		
		//6|3 0111->7
		System.out.println(6|3);
		
		//6^3 0101->5
		System.out.println(6^3);
		
		//~6 the data stored in the actual computer is 63 bits and 1 symbol bit
		System.out.println(~6);
		
		//Shift right
		System.out.println(6>>2);
		//Shift left
		System.out.println(6<<2);
	}
}

4.8.2.7 ternary operator

It is also called ternary expression. Simple logical judgment can be made through grammatical writing

  • Writing format
Relational expression ? Expression 1 : Expression 2;

The position in front of the question mark is the judgment condition. The judgment result is boolean. When it is true, expression 1 is called, and when it is false, expression 2 is called. The logic is: if the conditional expression is true or satisfied, execute expression 1, otherwise execute the second.

Example

int a = 10;
int b = 20;
int c = a > b ? a : b; // Judge whether a > b is true. If true, take the value of a; if false, take the value of B

graphic

4.8.2.8 operator priority

Expressions in Java are expressions connected by operators and conform to Java rules. The priority of the operator determines the order of operations in the expression. Generally, the order of priority from high to low is: self increasing and self decreasing operation, arithmetic operation, bit operation, logic operation and assignment operation. If two operations have the same priority, they are performed from left to right. The following table shows the precedence of operators in Java.

priorityDescriptionOperatorexplain
1Parentheses()Calculate the code in parentheses first
2Self increasing, self decreasing, logical non, positive sign, negative sign, negative sign++ – ! + - ~The operator that causes the variable itself to change is evaluated first
3Multiply, divide, remainder* / %Arithmetic priority multiplication and division, left to right at the same level
4Add, subtract+ -The addition and subtraction method is calculated after multiplication and division, and the same level is from left to right
5Shift left, shift right, unsigned shift right<< >> >>>Peer from left to right
6Less than, less than or equal to, greater than, greater than or equal to, judge the inheritance relationship< <= > >= instanceofPeer from left to right
7Equal to, not equal to== !=Peer from left to right
8And&Peer from left to right
9XOR^Peer from left to right
10or|Peer from left to right
11Logic and&&Peer from left to right
12Logical or||Peer from left to right
13assignment= += -= *= /= %= <<= >>= &= ^= |= >>>=Final assignment

4.9 data input

In the initial learning, because there is no front and back-end data interaction, we can only declare variables for data operation, but the variable value is fixed and can not be input at any time, so we can use the Scanner tool class provided by java API to realize data input operation

  • Use steps

1. Guide Package

The Scanner class is under the java.util package, so you need to import it. The statement of package guide needs to be defined on the class.

import java.util.Scanner; 

2. Create Scanner object

Scanner sc = new Scanner(System.in);// Create a Scanner object, sc represents the variable name, and others are immutable

3. Call method to receive data

int i = sc.nextInt(); // Indicates that the value entered by the keyboard is returned as an int number.
//You can also call nextLine(); Method to get the input string
//Note, however, that nextLine() cannot be used with nextInt()

Example

import java.util.Scanner;
public class ScannerDemo {
	public static void main(String[] args) {
		//create object
		Scanner sc = new Scanner(System.in);
		//receive data 
		int x = sc.nextInt();
		//output data
		System.out.println("x:" + x);
	}
}

4.10 process control statement

It controls the execution order of java code statements through specific syntax, just like controlling operator priority

4.10.1 sequence flow control statement

Sequential structure is the simplest and most basic process control in the program. There is no specific syntax structure. It is executed in sequence according to the sequence of codes. Most codes in the program are executed in this way.

  • Sequential structure execution flow chart

4.10.2 select process control statement

It is also called branch flow control statement. During program execution, select the corresponding branch according to the result of expression judgment (similar to ternary operator)

  • if branch statement

Grammar one

//if single branch syntax
if (Relational expression) {
    Statement body;	
}

Execution process

① First, evaluate the value of the relationship expression
② If the value of the relational expression is true, the statement body is executed
③ If the value of the relational expression is false, the statement body is not executed
④ Continue to execute the following statements


Example

public class IfDemo {
	public static void main(String[] args) {
		System.out.println("start");	
		//Define two variables
		int a = 10;
		int b = 20;	
		//Requirement: judge whether the values of a and b are equal. If they are equal, output: A is equal to b on the console
		if(a == b) {
			System.out.println("a be equal to b");
		}		
		//Requirement: judge whether the values of a and c are equal. If they are equal, output: A is equal to c on the console
		int c = 10;
		if(a == c) {
			System.out.println("a be equal to c");
		}		
		System.out.println("end");
	}
}

Grammar II

//if double branch syntax
if (Relational expression) {
    Statement body 1;	
} else {
    Statement body 2;	
}

Execution process

① First, evaluate the value of the relationship expression
② If the value of the relational expression is true, the statement body 1 is executed
③ If the value of the relational expression is false, statement body 2 is executed
④ Continue to execute the following statements


Example

public class IfDemo02 {
	public static void main(String[] args) {
		System.out.println("start");		
		//Define two variables
		int a = 10;
		int b = 20;
		b = 5;	
		//Requirement: judge whether a is greater than b. If yes, the value of a output on the console is greater than b; otherwise, the value of a output on the console is not greater than b
		if(a > b) {
			System.out.println("a The value of is greater than b");
		} else {
			System.out.println("a The value of is not greater than b");
		}		
		System.out.println("end");
	}
}

Grammar III

//if multi branch syntax
if (Relationship expression 1) {
    Statement body 1;	
} else if (Relational expression 2) {
    Statement body 2;	
} 
...
else {
    Statement body n+1;
}

Execution process

① First, evaluate the value of relationship expression 1
② If the value is true, execute statement body 1; If the value is false, the value of relationship expression 2 is evaluated
③ If the value is true, execute statement body 2; If the value is false, the value of relationship expression 3 is evaluated
④...
⑤ If no relational expression is true, the statement body n+1 is executed.

Example

import java.util.Scanner;
public class IfDemo03 {
	//Enter a week (1, 2,... 7) on the keyboard and output the corresponding Monday, Tuesday,... Sunday
	public static void main(String[] args) {
		System.out.println("start");
		// Requirement: enter a week (1, 2,... 7) on the keyboard and output the corresponding Monday, Tuesday,... Sunday
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter a number of weeks(1-7): ");
		int week = sc.nextInt();
		if(week == 1) {
			System.out.println("Monday");
		} else if(week == 2) {
			System.out.println("Tuesday");
		} else if(week == 3) {
			System.out.println("Wednesday");
		} else if(week == 4) {
			System.out.println("Thursday");
		} else if(week == 5) {
			System.out.println("Friday");
		} else if(week == 6) {
			System.out.println("Saturday");
		} else {
			System.out.println("Sunday");
		}	
		System.out.println("end");
	}
}

The difference between ternary operator and if statement

1. Grammatical differences
Ternary operators are operators, and branch statements are process control statements
2. Difference between returned results
After the execution of the ternary operator, a variable must be created to save the result, and the branch statement can directly execute the code block
3. Differences in use
When making a simple judgment and returning constant data, use the ternary operator
When judging complex conditions, branch statements are used

  • switch branch statement

grammar

switch (expression) {
	case Value 1:
		Statement body 1;
		break;
	case Value 2:
		Statement body 2;
		break;
	...
	default:
		Statement body n+1;
		break;
}

Execution process

① First, calculate the value of the expression
② Secondly, compare with case in turn. Once there is a corresponding value, the corresponding statement will be executed, and the break will end in the process of execution.
③ Finally, if all case s do not match the value of the expression, the body of the default statement is executed, and the program ends.
Note: the result of the expression in switch can be byte short int char String enumeration


Example 1

public class SwitchDemo01{
	//Keyboard input a month and output a season
    public static void main(String[] args) {
        //Enter the month data with the keyboard and receive it with variables
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a month:");
        int month = sc.nextInt();
        //case penetration
        switch(month) {
            case 1:
            case 2:
            case 12:
                System.out.println("winter");
                break;
            case 3:
            case 4:
            case 5:
                System.out.println("spring");
                break;
            case 6:
            case 7:
            case 8:
                System.out.println("summer");
                break;
            case 9:
            case 10:
            case 11:
                System.out.println("autumn");
                break;
            default:
                System.out.println("The month you entered is incorrect");
        }
    }
}

Note: if the case in switch does not correspond to break, case penetration will occur.
Example 2

public class SwitchDemo02{
	public static void main(String[] args) {
		//Enter the number of days that have passed in the current year according to the entered date
		Scanner scanner=new Scanner(System.in);
		System.out.println("Please enter the year");
		int year=scanner.nextInt();
		System.out.println("Please enter the month");
		int month=scanner.nextInt();
		System.out.println("Please enter a date");
		int day=scanner.nextInt();
		//Thinking: days passed on May 9, 2021
		//Days in January + February + March + April + 9 date
		
		//Declared variable has been saved for days
		int sumDay=0;
		//Calculate the number of days in February according to the year
		//Days in February
		int twoDay=28;
		if(year%4==0){
			twoDay=29;
		}
		switch (month-1) {
		case 11:
			sumDay+=30;
		case 10:
			sumDay+=31;
		case 9:
			sumDay+=30;
		case 8:
			sumDay+=31;
		case 7:
			sumDay+=31;
		case 6:
			sumDay+=30;
		case 5:
			sumDay+=31;
		case 4:
			sumDay+=30;
		case 3:
			sumDay+=31;
		case 2:
			sumDay+=twoDay;
		case 1:
			sumDay+=31;
		default:
			sumDay+=day;
		}
		System.out.println("Already passed"+sumDay+"day");
	}
}

4.10.3 loop flow control statement

  • while Loop

grammar

Initialization statement;
while (Conditional judgment statement) {
	Loop body statement;
    Conditional control statement;
}

Execution process

① Execute initialization statement
② Execute the conditional judgment statement to see whether the result is true or false
If false, the loop ends
If true, continue
③ Execute loop body statement
④ Execute conditional control statements
⑤ Go back to ② continue

Example

public class WhileDemo {
    public static void main(String[] args) {
        //Requirement: output "HelloWorld" 5 times on the console
		//for loop implementation
		for(int i=1; i<=5; i++) {
			System.out.println("HelloWorld");
		}
		System.out.println("--------");
		//while loop implementation
		int j = 1;
		while(j<=5) {
			System.out.println("HelloWorld");
			j++;
		}
    }
}
  • do... while loop

  • for loop

4.10.4 process jump statement

Tags: Java Javascript echarts

Posted on Tue, 16 Nov 2021 19:54:41 -0500 by klevis miho