Java basics from entry to proficiency series (1)

1. Introduction to Java

The Java language is an advanced, concurrent, object-oriented computer programming language launched by Sun Microsystems in 1995. Java is widely used in web application development, mobile application development, and the development of large enterprise-level applications. The Java language has the advantages of cross-platform, good security, strong portability, easy to learn and use, etc., and has been widely used and recognized in the industry.

1.1. History of Java Development

  • 1991 Green project, the development language was originally named Oak (oak tree)
  • In 1994, the development team realized that Oak was very suitable for the Internet
  • In 1996, JDK 1.0 was released, and about 83,000 web pages were created using Java technology
  • In 1997, JDK 1.1 was released, and the JavaOne conference was held, which was the largest conference of its kind in the world at that time
  • In 1998, JDK 1.2 was released, and the enterprise platform J2EE was released in the same year
  • In 1999, Java was divided into J2SE, J2EE and J2ME, and JSP/Servlet technology was born
  • In 2004, a milestone version was released: JDK 1.5, which was renamed JDK 5.0 to highlight the importance of this version
  • 2005年,J2SE -> JavaSE,J2EE -> JavaEE,J2ME -> JavaME
  • In 2009, Oracle acquired SUN at a transaction price of US$7.4 billion
  • In 2011, JDK 7.0 was released
  • In 2014, JDK 8.0 was released, which is the most changed version since JDK 5.0
  • In 2017, JDK 9.0 was released to maximize modularity
  • In March 2018, JDK 10.0 was released, and the version number is also called 18.3
  • In September 2018, JDK 11.0 was released, and the version number is also called 18.9
  • On March 20, 2019, Java SE 12 was released. Java 12 is a short-term support release.
  • On September 23, 2019, Java SE 13 was released. A "text block" was added in this version. A text block is a multi-line string literal that avoids the need for most escape sequences and is automatically formatted in a predictable manner. string, and let the developer control the formatting if needed.

1.2, Java three major platforms

1.2.1, JavaSE (Java Standard Edition) Standard Edition

Supports the Java platform for desktop-level applications (such as applications under Windows), and provides a complete Java core API. This version was previously called J2SE

1.2.2, JavaEE (Java Enterprise Edition) Enterprise Edition

It is a set of solutions for developing applications in an enterprise environment. The technologies included in the technology system, such as Servlet, Jsp, etc., are mainly aimed at the development of Web applications. version formerly known as J2EE

1.2.3, Java ME (Java Micro Edition) Small Edition

A platform that supports Java programs running on mobile terminals (mobile phones, PDAs), simplifies the Java API, and adds support for mobile terminals. This version was previously called J2ME

1.3. Features of the Java language

1.3.1. Feature 1: Object-oriented

  • Two basic concepts:
    • kind
    • object
  • Three major characteristics:
    • encapsulation
    • inherit
    • polymorphism

1.3.2. Feature 2: Robustness

  • The pointer in C language is removed, and the advantages of C/C++ language are absorbed, but the parts that affect the robustness of the program (such as pointers, memory application and release, etc.) are removed, and a relatively safe memory management and access mechanism is provided. .
  • Automatic garbage collection mechanism, but there is still the possibility of memory overflow and memory leak.

1.3.3. Feature 3: Cross-platform

  • Cross-platform: applications written in the Java language can run on different system platforms. “Write once, Run anywhere”
  • Its principle: to achieve cross-platform through compiled bytecode files, as long as a corresponding version of Java Virtual Machine (JVM Java Virtual Machine) is installed on the operating system that needs to run java applications. The bytecode file is run by the Java virtual machine to realize its cross-platform feature.
    insert image description here

1.4, Java language environment construction

1.4.1. What is JVM, JDK, JRE

  • JVM (Java Virtual Machine): Java virtual machine
  • JDK (Java Development Kit Java Development Kit): JDK is provided for Java developers to use, which contains java development tools, including JRE. **So after installing JDK, you don't need to install JRE separately. The development tools include: compilation tool (javac.exe), packaging tool (jar.exe), etc.
  • JRE (Java Runtime Environment Java Runtime Environment): Including Java Virtual Machine (JVM Java Virtual Machine) and the core class libraries required by Java programs, etc. If you want to run a developed Java program, you only need to install JRE in the computer .

insert image description here

2. Java Basic Grammar

2.1. Notes

There are three types of annotations in Java:

  • Single line comment:
// 这是单行注释文字
  • Multi-line comments:
/*
这是多行注释文字
这是多行注释文字
这是多行注释文字
*/
注意:多行注释不能嵌套使用。
  • Documentation comments:
/**
 * @author  指定java程序的作者**
 * @version  指定源文件的版本**
 */
  • Tips and points to note
如果我们要对代码进行解释,那么就可以使用注释,当注释的内容比较少,一行就写完了,可以用单行注释。
如果注释的内容比较多,需要写在多行,那么可以使用多行注释。

注释的内容不会参与编译和运行的,仅仅是对代码的解释说明而已。
所以,不管在注释当中写什么内容,都不会影响代码运行的结果。

2.2. Keywords

2.1 Concept

An English word given a specific meaning by Java. After we write keywords in the code, when the program is running, we know what to do.

abstract assert boolean break byte
case catch char class const
continue default do double else
enum extends final finally float
for goto if implements import
instanceof int interface long native
new package private protected public
return strictfp short static super
switch synchronized this throw throws
transient try void volatile while

2.2. Literal quantity

Function: Tell the programmer the writing format of the data in the program.

literal type illustrate How to write in the program
integer numbers without decimals 666,-88
decimal numbers with decimals 13.14,-5.21
character Single quotes must be used, with only one character 'A', '0', 'i'
string Double quotes must be used, the content is optional "HelloWorld", "Dark Horse Programmer"
Boolean value Boolean value, indicating true and false, only two values: true, false true 、false
empty value a special value, null Value is: null
public class Demo {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(10); // 输出一个整数
        System.out.println(5.5); // 输出一个小数
        System.out.println('a'); // 输出一个字符
        System.out.println(true); // 输出boolean值true
        System.out.println("欢迎来到黑马程序员"); // 输出字符串
    }
}

distinguishing skills

  1. Numbers without a decimal point are integer literals.
  2. As long as a decimal point is included, it is a literal value of the decimal type.
  3. As long as it is enclosed in double quotation marks, no matter what the content is, whether there is content or not, it is a literal value of string type.
  4. Literals of character type must be enclosed in single quotes, no matter what the content is, but there can only be one.
  5. The literal value of character type has only two values, true and false.
  6. Literals of empty type have only one value, null.

2.3. Variables

A variable is a container for temporarily storing data in a program. But only one value can be stored in this container.

2.3.1, variable definition format

数据类型 变量名 = 数据值;
  • Data type: defines what type of data can be stored in a variable.
    • If you want to store 10, then the data type needs to be an integer type.
    • If you want to store 10.0, then the data type needs to be written as a decimal type.
  • Variable name: In fact, it is the name of the container.
    • When you want to use the data in the variable in the future, just use the variable name directly.
  • Data value: the data actually stored in the container.
  • Semicolon: Indicates the end of a sentence, just like the period when writing a composition before.
public class VariableDemo{
    
    
	public static void main(String[] args){
    
    
		//定义一个整数类型的变量
		//数据类型 变量名 = 数据值;
		int a = 16;
		System.out.println(a);//16
		
		//定义一个小数类型的变量
		double b = 10.1;
		System.out.println(b);//10.1
	}
}

2.4, data type

2.4.1. Classification of Java language data types

  • basic data type
    • Integer: byte \ short \ int \ long
    • Floating point type: float \ double
    • Character type: char
    • Boolean: boolean
  • reference data type
    • Class: class
    • Interface: interface
    • Array: array

2.4.2. Four categories and eight types of basic data types

type of data keywords memory usage Ranges
integer byte 1 Negative 2 to the 7th power ~ 2 to the 7th power -1 (-128~127)
short 2 Negative 2 to the 15th power ~ 2 to the 15th power -1 (-32768~32767)
int 4 Negative 2 to the 31st power ~ 2 to the 31st power -1
long 8 Negative 2 to the 63rd power ~ 2 to the 63rd power -1
floating point number float 4 1.401298e-45 ~ 3.402823e+38
double 8 4.9000000e-324 ~ 1.797693e+308
character char 2 0-65535
Boolean boolean 1 true,false

insert image description here

2.4.2.1, Case 1
public class VariableDemo3{
    
    
    public static void main(String[] args){
    
    
        //1.定义byte类型的变量
        //数据类型 变量名 = 数据值;
        byte a = 10;
        System.out.println(a);

        //2.定义short类型的变量
        short b = 20;
        System.out.println(b);

        //3.定义int类型的变量
        int c = 30;
        System.out.println(c);

        //4.定义long类型的变量
        long d = 123456789123456789L;
        System.out.println(d);

        //5.定义float类型的变量
        float e = 10.1F;
        System.out.println(e);

        //6.定义double类型的变量
        double f = 20.3;
        System.out.println(f);

        //7.定义char类型的变量
        char g = 'a';
        System.out.println(g);

        //8.定义boolean类型的变量
        boolean h = true;
        System.out.println(h);

    }
}
2.4.2.2, Case 2
/*
Java定义的数据类型

*/
class VariableTest1{
    
    
	public static void main(String[] args) {
    
    
	//1. 整型:byte(1字节=8bit) short(2字节) \ int (4字节)\ long(8字节)
		//① byte范围:-128 ~ 127

		byte b1 = 12;
		byte b2 = -128;
	//	b2 = 128; //编译不通过
		System.out.println(b1);
		System.out.println(b2);

		// ② 声明long型变量,必须以“1”或“L”结尾
		short s1 = 128;
		int i1 = 12345;
		long l1 = 345678586;
		System.out.println(l1);
		//2. 浮点型:float(4字节) \ double(8字节)
		//① 浮点型,表示带小数点的数值
		//② float表示数值的范围比long还大

		double d1 = 12.3;
		System.out.println(d1 +1);
		
		//定义float类型变量时,变量要以"f" 或"F"结尾
		float f1 = 12.3F;
		System.out.println(f1);

		//② 通常,定义浮点型变量时,使用double变量

		//3. 字符型:char(1字符=2字节)
		//① 定义char型变量,通常使用一对'' 
		char c1 = 'a';
		//编译不通过
		//c1 = 'AB';
		System.out.println(c1);

		char c2 = '1';
		char c3 = '中';
		char c4 = '&';
		System.out.println(c2);
		System.out.println(c3);
		System.out.println(c4);

		//② 表示方式:1.声明一个字符;2.转义字符;3.直接使用Unicode值来表示字符型常量
		char c5 = '\n';	//换行符
		c5 = '\t';	//制表符
		System.out.print("hello" + c5);
		System.out.println("world");

		char c6 = '\u0123';
		System.out.println(c6);
		
		char c7 = '\u0043';
		System.out.println(c7);
	}
}

2.4.3, ASCII code

ASCII code (American Standard Code for Information Interchange, American Standard Code for Information Interchange) is a character encoding system based on the Latin alphabet, which contains a total of 128 characters, using a 7-bit binary number (that is, the highest bit of a byte is 0 ) can be expressed. The ASCII code was first formulated in 1963, and has been revised and updated many times since then, and the last update was in 1986. ASCII codes are widely used in computers, communications, and other devices to represent text characters and control characters. Due to the limitations of computer system technology at that time, the ASCII code had only 128 character code points, of which only 95 were printable characters, which severely limited the scope of its functions.

That is, the characteristics of ASCII code are as follows:

  • Internally, all data is represented in binary. Each binary bit (bit) has two states of 0 and 1, so 8 binary bits can be combined to form 256 states, which is called a byte (byte). A byte can be used to represent 256 different states, each state corresponds to a symbol, which is 256 symbols, from 0000000 to 11111111.
  • ASCII code: In the 1960s, the United States formulated a set of character encodings, which made unified regulations on the relationship between English characters and binary digits. This is known as ASCII code. The ASCII code specifies a total of 128 character encodings. For example, the space "SPACE" is 32 (binary 00100000), and the uppercase letter A is 65 (binary 01000001). These 128 symbols (including 32 control symbols that cannot be printed out) only occupy the last 7 bits of a byte, and the first 1 bit is uniformly specified as 0.
  • shortcoming:
    • Not all characters can be represented.
    • The characters represented by the same encoding are different: for example, 130 represents é in the French encoding, but it represents the letter Gimel (ג) in the Hebrew encoding

2.4.4, Unicode encoding

Unicode encoding is an international encoding standard used to assign a unique number and name to all characters in various languages, symbols, and symbol systems around the world. Unicode encoding allows computers to process and represent text characters in many languages, including Asian scripts, classical Greek, ancient symbols and diagrams, and more.

Compared with ASCII encoding, Unicode encoding can support more character sets and encoding methods, so it is widely used in modern computer systems. For example, when using different languages ​​for programming and internationalized text processing, it is more convenient and simple to use Unicode encoding. At the same time, since Unicode encoding has become an international standard, it also solves the problems of confusion, confusion, and loss caused by encoding problems when exchanging text files between different computer systems.

That is, the Unicode encoding characteristics are as follows:

  • Unicode: An encoding that incorporates all symbols in the world. Each symbol is given a unique encoding, and there is no problem of garbled characters when using Unicode.
  • Disadvantages of Unicode: Unicode only specifies the binary code of the symbol, but does not specify how the binary code should be stored: Unicode and ASCII cannot be distinguished: the computer cannot distinguish whether three bytes represent one symbol or three symbols respectively. In addition, we know that English letters are represented by only one byte. If unicode uniformly stipulates that each symbol is represented by three or four bytes, then there must be two to three bytes before each English letter. is 0, which is a great waste of storage space.

2.4.5、UTF-8

UTF-8 is a variable-length character encoding standard used for electronic communications. It is defined by the Unicode Standard and its name comes from the Unicode (or Universal Character Set) Transformation Format - 8-bit. UTF-8 can encode the 1,112,064 valid character code points in Unicode using code units of 1 to 4 bytes (8 bits). UTF-8 is able to represent any character in the Unicode standard and has backward compatibility with ASCII.

That is, the Unicode encoding characteristics are as follows:

  • UTF-8 is the most widely used implementation of Unicode on the Internet.
  • UTF-8 is a variable-length encoding. It can use 1-4 bytes to represent a symbol, and the byte length varies according to different symbols.
  • UTF-8 encoding rules:
    • For single-byte UTF-8 encoding, the highest bit of the byte is 0, and the remaining 7 bits are used to encode characters (equivalent to ASCII codes).
    • For multi-byte UTF-8 encoding, if the encoding contains n bytes, then the first n bits of the first byte are 1, the n+1th bit of the first byte is 0, and the rest of the byte Bits are used to encode characters. For all bytes after the first byte, the highest two bits are "10", and the remaining 6 bits are used to encode characters.

2.5. Basic data type conversion

2.5.1, automatic type conversion

Automatic type conversion: A type with a small capacity is automatically converted to a data type with a large capacity. The data types are sorted by capacity as follows:
insert image description here

  • When there are multiple types of data mixed operations, the system first automatically converts all data into the data type with the largest capacity, and then performs calculations.
  • byte, short, and char are not converted to each other, and the three of them are first converted to int type during calculation.
  • The boolean type cannot be operated with other data types.
  • When the value of any basic data type is connected with a string (String) (+), the value of the basic data type will be automatically converted into a string (String) type.
/*
基本数据类型之间的运算规则:

前提:这里讨论只是7中基本数据类型变量的运算。不包含boolean类型的。
1. 自动类型提升:
	当容量小的数据类型的变量和容量大的数据类型的变量做运算时,结果自动提升为容量大的数据类型。
	char、byte、short-->int-->long-->float-->double

	特别的:当byte、char、short三种类型的变量做运算时,结果为int类型

2. 强制类型转换:
	
说明:此时容量大小指的是,表示数的范围的大和小。比如:float容量要大于long的容量
*/
class VariableTest2{
    
    
	public static void main(String[] args) {
    
    
		byte b1 = 2;
		int i1 = 129;

//		编译不通过
//		byte b2 = b1 + i1;
		int i2 = b1 + i1;
		long l1 = b1 + i1;
		System.out.println(i2);
		System.out.println(l1);

		float f = b1 + i1;
		System.out.println(f);
		//***************特别的**************************
		char c1 = 'a';	//97
		int i3 = 10;
		int i4 = c1 + i3;
		System.out.println(i4);

		short s2 = 10;
//		编译错误
//		char c3 = c1 + s2;
		
		byte b2 = 10;
//		char c3 = c1 + b2;	//编译不通过
//		short s3 = b2 + s2;	//编译不通过	
//		short s4 = b1 + b2;	//编译不通过
	}
}
class VariableTest4{
    
    
	public static void main(String[] args){
    
    
		//1. 编码情况
		long l = 123456;
		System.out.println(l);
		//编译失败:过大的整数
		//long l1 = 452367894586235;
		long l1 = 452367894586235L;

		//**************************
		//编译失败
//		float f1 = 12.3;
		
		//2. 编码情况2:
		//整型变量,默认类型为int型
		//浮点型变量,默认类型为double型
		byte b = 12;
	//	byte b1 = b + 1;	//编译失败
		
	//	float f1 = b + 12.3;	//编译失败
	}
}

2.5.2. Mandatory type conversion

  • The inverse process of automatic type conversion converts a data type with a large capacity into a data type with a small capacity. When using it, you need to add the mandatory conversion character: (), but it may cause precision reduction or overflow, so special attention should be paid.
  • Usually, a string cannot be directly converted to a basic type, but the conversion of a string to a basic type can be realized through the wrapper class corresponding to the basic type. like:String a = “43”; inti= Integer.parseInt(a);
  • The boolean type cannot be converted to other data types.

2.6, base conversion

2.6.1. Binary

Binary is a counting system and information processing method that uses the digits 0 and 1 to represent values ​​and information. It is widely used in mathematics and computer science. In the binary system, each digit can only be 0 or 1. It is a number system based on 2, which is different from the decimal number system we usually use. Binary is widely used in computer science because modern computers store all data in binary form and use binary codes to process and transmit data. Binary excels in computers because it can be processed with simple shifts and logical operations.

  • The Java integer constant defaults to the int type. When the integer is defined in binary, its 32nd bit is the sign bit; when it is a long type, the binary value occupies 64 bits by default, and the 64th bit is the sign bit.
  • Binary integers come in three forms:
    • Original code: Directly replace a value with a binary number. The most significant bit is the sign bit
    • Negative number's one's complement: It is the bitwise inversion of the original code, but the highest bit (sign bit) is determined to be 1.
    • The complement of a negative number: add 1 to its complement. Computers store all integers in two's complement form.
  • The original code, inverse code and complement code of a positive number are the same, and the complement code of a negative number is its inverse code + 1

2.6.2. Why use the original code, inverse code, and complement code representation?

  • The original code, inverse code, and complement code are used in computers to represent integers because this representation can avoid overflow when the computer performs operations such as addition and subtraction.
  • For signed integers, if the original code representation is used, positive and negative numbers need to be considered separately when performing addition and subtraction operations, and carry or borrow may occur, resulting in inaccurate operation results. However, the addition and subtraction operations can be unified into the addition and subtraction that only considers the numerical value by using the inverse code and the complement code representation, avoiding these problems.
  • Specifically, using the inverse code to represent negative numbers can effectively solve the carry problem under the original code representation. However, there are two zeros in the one's complement representation, that is, +0 and -0, which makes the computer unable to distinguish between +0 and -0, so it leads to the complement representation, which has no +0, only one -0, which can be Eliminates the effect of the sign bit on the computation.

Therefore, the use of original code, inverse code, and complement code representation can make computer operations more efficient and accurate, and it is also easy to understand and process integer calculations.

insert image description here
The addition of two numbers is actually the addition of the complements of two integers. The original code and the inverse code exist to help deduce the complements. The bottom layer of the computer uses the complements of the values ​​​​to save data. The essence of adding two integers is to calculate the sum of their complements. In complement notation, the one's complement of a number is its inverse (0 becomes 1, 1 becomes 0), and the complement is equal to its complement plus 1. Therefore, there is no need to distinguish between positive and negative numbers in computer addition operations, but to add the complements of the two numbers involved in the operation bit by bit, and finally convert the complements of the results back to the original code to get the correct result.

insert image description here

2.6.3, Conversion between binary and decimal

Convert binary to decimal times powers of 2

For example, the steps to convert binary number 1011 to decimal number are as follows:

  • Binary numbers are given weights bit by bit from right to left, the weight of the first bit is 1, the weight of the second bit is 2, the weight of the third bit is 4, and so on. Therefore, the first position has a weight of 1, the second has a weight of 2, the third has a weight of 4, and the fourth has a weight of 8.
  • Multiply the value of each bit with the corresponding weight to get the decimal value of the bit. So, the first bit has a value of 1 and is multiplied by 1 to get 1; the second bit has a value of 1 and is multiplied by 2 to get 2; the third bit has a value of 0 and is multiplied by 4 to get 0; and the fourth bit has a value of 1, multiplied by 8 to get 8.
  • Add the decimal values ​​of all the bits to get the final decimal result. Therefore, 1 + 2 + 0 + 8 = 11, so the binary number 1011 converts to 11 in decimal.

2.6.4, conversion between decimal and binary

Convert decimal to binary and divide by 2 to get the remainder, and arrange the remainder in reverse order

A simple example is converting the decimal number 13 to binary. Proceed as follows:

  • Dividing the number 13 by 2 gives a quotient of 6 and a remainder of 1.
  • Continue dividing the quotient by 2 to get a quotient of 3 and a remainder of 0.
  • Continue to divide the quotient by 2 to get a quotient of 1 and a remainder of 1.
  • Continue dividing the quotient by 2 to get a quotient of 0 and a remainder of 1.
  • Arrange the remainder in reverse order to get the binary number 1101.

Therefore, the decimal number 13 converts to binary number 1101.

2.7. Identifier

The sequence of characters that Java uses to name elements such as variables, methods, and classes is called an identifier

2.7.1. Define legal identifier rules

  • Must consist of numbers, letters, underscores _, and dollar signs $.
  • number cannot start with
  • cannot be a keyword
  • Case sensitive.

2.7.2. Naming conventions in Java

  • Package name: All letters are lowercase when composed of multiple words: xxxyyyzzz
  • Class name, interface name: When composed of multiple words, ** the first letter of all words is capitalized: ** XxxYyyZzz
  • Variable name, method name: When composed of multiple words, the first letter of the first word is lowercase, and the first letter of each word is capitalized at the beginning of the second word: xxxYyyZzz
  • Constant names: All letters are uppercase. When there are multiple words, each word is connected with an underscore: XXX_YYY_ZZZ
  • When naming, in order to improve readability, try to be as meaningful as possible, "see the name and know the meaning".
  • Java uses the unicode character set, so identifiers can also be declared using Chinese characters, but it is not recommended.

2.8. Introduction to Hierarchical Structure in IDEA

2.8.1. Structural classification

  • project (project, project)
  • module
  • package (package)
  • class (class)

Hierarchical relationship: project - module - package - class

2.8.1, detailed structure

  • Project (project, project): Taobao and Jingdong belong to each project, and IDEA is each Project.

  • module: In a project, multiple modules can be stored, and different modules can store different business function codes in the project. Such as commodity module, user module. In order to better manage the code, we will store the code in two modules.

  • Package (package): There are many services in one module. Taking the forum module of the user website as an example, it contains at least the following different services. Such as personal information, order information, etc. In order to distinguish these businesses more clearly, packages are used to manage these different businesses.

  • class (class): This is where the code is actually written.

  • Include quantity

    • Multiple modules can be created in a project
    • Multiple packages can be created in a module
    • Multiple classes can be created in a package
    • The division of these structures is to facilitate the management of class files.

2.9. Operators and expressions

  • Operator: It is a symbol that operates on constants or variables. For example: + - * /

  • Expression: use operators to connect constants or variables, and the formula that conforms to the Java syntax is an expression. For example: the whole of a + b is an expression. And + is a kind of arithmetic operator, so this expression is also called arithmetic expression

2.9.1, operator type

  • arithmetic operator
  • assignment operator
  • Comparison Operators (Relational Operators)
  • Logical Operators
  • bitwise operator
  • ternary operator
2.9.1.1, arithmetic operators

insert image description here

/*
运算符之一:算术运算符
+ - * / % (前)++ (后)++ (前)-- (后)-- 

*/
class Day3Test{
    
    
	public static void main(String[] args) {
    
    

		//除号:/
		int num1 = 12;
		int num2 = 5;
		int resule1 = num1 / num2;
		System.out.println(resule1);	//2

		int result2 = num1 / num2 * num2;
		System.out.println(result2);

		double result3 = num1 / num2;
		System.out.println(result3);	//2.0

		double result4 = num1 / num2 + 0.0;	//2.0
		double result5 = num1 / (num2 + 0.0);	//2.4
		double result6 = (double)num1 / num2;	//2.4
		double result7 = (double)(num1 / num2);	//2.0
		System.out.println(result5);
		System.out.println(result6);

		// %:取余运算
		//结果的符号与被模数的符号相同
		int m1 = 12;
		int n1 = 5;
		System.out.println("m1 % n1 = " + m1 % n1);

		int m2 = -12;
		int n2 = 5;
		System.out.println("m2 % n2 = " + m2 % n2);

		int m3 = 12;
		int n3 = -5;
		System.out.println("m3 % n3 = " + m3 % n3);

		int m4 = -12;
		int n4 = -5;
		System.out.println("m4 % n4 = " + m4 % n4);

		//(前)++ : 先自增1,后运算
		//(后)++ :先运算,后自增1
		int a1 = 10;
		int b1 = ++a1;
		System.out.println("a1 = " + a1 + ",b1 = " + b1);

        int a2 = 10;
		int b2 = a2++;
		System.out.println("a2 = " + a2 + ",b2 = " + b2);

		int a3 = 10;
		a3++;	//a3++;
		int b3 = a3;

		//注意点:
		short s1 = 10;
		//s1 = s1 + 1;	//编译失败
//		s1 = (short)(s1 + 1);	//正确的
		s1++;	//自增1不会改变本身变量的数据类型
		System.out.println(s1);

		//问题:
		byte bb1 = 127;
		bb1++;
		System.out.println("bb1 = " + bb1);

		//(前)-- :先自减1,后运算
		//(后)-- :先运算,后自减1

		int a4 = 10;
		int b4 = a4--;	//int b4 = --a4;
		System.out.println("a4 = " + a4 + ",b4 = " + b4);
	}
}

  • If you take the modulus for a negative number, you can ignore the negative sign of the modulus, such as: 5%-2=1. However, if the modulus is negative, it cannot be ignored. Also, the result of a modulo operation may not always be an integer.
  • For the division sign "/", its integer division and decimal division are different: when dividing integers, only the integer part is kept and the decimal part is discarded. For example: intx=3510;x=x/1000*1000; what is the result of x?
  • "+" can also convert non-strings into strings in addition to adding strings. For example: System.out.println("5+5="+5+5); //What is the print result? 5+5=55?
/*
练习:随意给出一个三位数的整数,打印显是它的个位数,十位数,百位数的值。
例如:
数字153的情况如下:
个位数:3
十位数:5
百位数:1

公式:
获取任意一个数上每一位数。
个位:数字 % 10
十位:数字 / 10 % 10
百位:数字 / 100 % 10
千位:数字 / 1000 % 10
。。。以此类推。。。
*/
class AriExer{
    
    
	public static void main(String[] args){
    
    
		int num = 187;
		System.out.println("百位数:" + num/100);
		System.out.println("十位数:" + num%100/10);
		System.out.println("个位数:" + num%10);
	}
}
2.9.1.2, assignment operator

Operation process: assign the result on the right side of the equal sign to the variable on the left

  • Symbol: =
    • When the data types on both sides of "=" are inconsistent, you can use automatic type conversion or use the principle of forced type conversion to deal with it.
    • Continuous assignment is supported.
  • Extended assignment operators: +=, -=, *=, /=, %=, the hidden layer of extended assignment operators also includes a cast.
public class OperatorDemo6 {
    
    
    public static void main(String[] args) {
    
    
        //1.最为简单的赋值运算符用法
        int a = 10;//就是把10赋值给变量a
        System.out.println(a);

        //2.如果等号右边需要进行计算。
        int b = 20;
        int c = a + b;//先计算等号右边的,把计算的结果赋值给左边的变量
        System.out.println(c);

        //3.特殊的用法
        a = a + 10;//先计算等号右边的,把计算的结果赋值给左边的变量
        System.out.println(a);//20

 		//扩展赋值运算符
        int a = 10;
        int b = 20;
        a += b;//把左边和右边相加,再把最终的结果赋值给左边,对右边没有任何影响,a += b ;实际上相当于 a = (byte)(a + b);
        // 相当于 a = a + b;  
        System.out.println(a);//30
        System.out.println(b);//20

    }
}
2.9.1.3. Relational operators

It is also called a comparison operator. In fact, it just judges with the left and right.

symbol explain
== It is to judge whether the left side is equal to the right side, if it is true, it is true, if it is not true, it is false
!= It is to judge whether the left side is not equal to the right side, if it is true, it is true, if it is not true, it is false
> It is to judge whether the left side is greater than the right side, if it is true, it is true, if it is not true, it is false
>= It is to judge whether the left side is greater than or equal to the right side, if it is true, it is true, if it is not true, it is false
< It is to judge whether the left side is smaller than the right side, if it is true, it is true, if it is not true, it is false
<= It is to judge whether the left side is less than or equal to the right side, if it is true, it is true, if it is not true, it is false
  • The final result of a relational operator must be of Boolean type. either true or false
  • When writing ==, never write =
/*
运算符之三:比较运算符
==  !=  > < >= <= instanceof

结论:
1.比较运算符的结果是boolean类型
2.区分 == 和 = 

*/
class CompareTest{
    
    
	public static void main(String[] args){
    
    
		int i = 10;
		int j = 20;
		System.out.println(i==j);	//false
		System.out.println(i = j);	//20

		boolean b1 = true;
		boolean b2 = false;
		System.out.println(b2 == b1);	//false
		System.out.println(b2 = b1);	//true
	}
}

2.9.1.4, logical operators
  • &— Logical AND
  • |— Logical OR
  • — Logical NOT
  • &&— short circuit with
  • ||— short circuit or
  • ^— logical XOR

insert image description here

  • Logical operators are used to connect Boolean expressions, which cannot be written as 3<x<6 in Java, but should be written as x>3 & x<6.
  • The difference between "&" and "&&":
    • When single &, whether the left side is true or false, the right side will perform calculations;
    • When double &, if the left side is true, the right side will participate in the operation, if the left side is false, then the right side will not participate in the operation.
  • The difference between "|" and "||" is the same, and || means: when the left side is true, the right side does not participate in the operation.
  • The difference between exclusive or (^) and or ( | ) is: when both left and right are true, the result is false. Understanding: exclusive or, the pursuit is "exclusive"!
/*
运算符之四:逻辑运算符
& && | || ! ^

说明:
1. 逻辑与运算符操作的都是boolean类型的变量

*/
class LogicTest{
    
    
	public static void main(String[] args){
    
    
		//区分& 与 &&
		//相同点1:& 与 && 的运算结果都相同
		//相同点2:当符号左边是true时,二者都会执行符号右边的运算
		//不同点:当符号左边是false时,&继续执行符号
		//开发中,推荐使用&&
		boolean b1 = false;
		int num1 = 10;
		if(b1 & (num1++ > 0)){
    
    
			System.out.println("我现在在南京");
		}else{
    
    
			System.out.println("我现在在北京");
		}
		System.out.println("num1 = " + num1);

		boolean b2 = false;
		int num2 = 10;
		if(b2 && (num2++ > 0)){
    
    
			System.out.println("我现在在南京");
		}else{
    
    
			System.out.println("我现在在北京");
		}
		System.out.println("num2 = " + num2);

		//区分:| 与 ||
		//相同点1:| 与 || 的运算结果都相同
		//相同点2:当符号左边是false时,二者都会执行符号右边的运算
		//不同点3:当符号左边是true时,|继续执行符号右边的运算,而||不再执行符号右边的运算
		//开发中,推荐使用||
		boolean b3 = true;
		int num3 = 10;
		if(b3 | (num3++ > 0)){
    
    
			System.out.println("我现在在南京");
		}else{
    
    
			System.out.println("我现在在北京");
		}
		System.out.println("num3 = " + num3);

		boolean b4 = true;
		int num4 = 10;
		if(b4 || (num4++ > 0)){
    
    
			System.out.println("我现在在南京");
		}else{
    
    
			System.out.println("我现在在北京");
		}
		System.out.println("num4 = " + num4);
	}
}

2.9.1.5, bitwise operators

Bitwise operations are operations performed directly on binary numbers of integers

insert image description here

/*
运算符之五:位运算符(了解)

结论:
1.位运算符操作的都是整型的数据变量
2.<< : 在一定范围内,每向左移一位,相当于 * 2
  >> : 在一定范围内,每向右移一位,相当于 / 2

面试题:最高效的计算2 * 8 ?	2 << 3 或 8 << 1
*/
class BitTest{
    
    
	public static void main(String[] args){
    
    
		int i = 21;
//		i = -21;
		System.out.println("i << 2 :" + (i << 2));
		System.out.println("i << 3 :" + (i << 3));
		System.out.println("i << 20 :" + (i << 20));
		System.out.println("i << 27 :" + (i << 27));
		int m = 12;
		int n = 5;
		System.out.println("m & n :" + (m & n));
		System.out.println("m & n :" + (m | n));
		System.out.println("m & n :" + (m ^ n));
		//练习:交换两个变量的值
		int num1 = 10;
		int num2 = 20;

		//方式一:
	//	int tent = num1;
	//	num1 = num2;
	//	num2 = tent;

		//方式二:
		//好处:不用定义临时变量
		//弊端:①相加可能超出存储范围 ② 有局限性:只适用于数值类型
//		num1 = num1 + num2;
//		num2 = num1 - num2;
//		num1 = num1 - num2;

		//方式三:使用位运算
		num1 = num1 ^ num2;
		num2 = num1 ^ num2;
		num1 = num1 ^ num2;

		System.out.println("num1 = " + num1 + ",num2 = " + num2);
	}
}

2.9.1.6, ternary operator

Also known as: ternary expression or question mark colon expression.
insert image description here

/*
运算符之六:三元运算符
1.结构:(条件表达式)?表达式1 : 表达式2
2. 说明
① 条件表达式的结果为boolean类型
② 根据条件表达式真或假,决定执行表达式1,还是表达式2.
  如果表达式为true,则执行表达式1
  如果表达式为false,则执行表达式2
③ 表达式1 和表达式2要求是一致的。
④ 三元运算符是可以嵌套的
3. 凡是可以使用三元运算的地方,都是可以改写if-else。
   反之,则不一定成立!!!
*/
class SanTest{
    
    
	public static void main(String[] args) {
    
    
		//获取两个整数的最大值
		int m = 12;
		int n = 5;
		int max = (m > n)? m : n;
		System.out.println(max);

		double num = (m > n) ? 2 : 1.0;
		//(m > n) ? 2 : "n大";	//编译错误

		//****************************************
		String str = (m > n) ? "m大" : ((m == n)? "m和n相等" : "n大");
		System.out.println(str);

		//****************************************
		//获取三个数中的最大值
		int n1 = 12;
		int n2 = 30;
		int n3 = -43;

		int max1 = (n1 > n2) ? n1 : n2;
		int max2 = (max1 > n3) ? max1 : n3;
		System.out.println("三个数中的最大值是:" + max2);

		//此方法:pass
		int max3 = (((n1 > n2)? n1 : n2) > n3) ?((n1 > n2) ? n1 : n2) : n3;
		System.out.println("三个数中的最大值是:" + max3);

		//改写成if-else
		if(m > n){
    
    
			System.out.println(m);
		}else{
    
    
			System.out.println(n);
		}
	}
}

2.9.2. Operator precedence

insert image description here

2.10, flow control statement

The flow control statement is a statement used to control the execution sequence of each statement in the program, and the statement can be combined into a small logic module that can complete a certain function. Its process control method adopts three basic process structures stipulated in the structured program design, namely:

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

2.10.1. Sequence structure

The program is executed line by line from top to bottom without any judgment or jump in the middle.

insert image description here

2.10.2、分支结构

根据条件,选择性地执行某段代码。有if…else和switch-case两种分支语句。

2.10.2.1、if…else
2.10.2.1.1、格式1
格式:
if (关系表达式) {
    
    
    语句体;	
}

执行流程:

  • ①首先计算关系表达式的值
  • ②如果关系表达式的值为true就执行语句体
  • ③如果关系表达式的值为false就不执行语句体
  • ④继续执行后面的语句内容

insert image description here

public class IfDemo {
    
    
	public static void main(String[] args) {
    
    
		System.out.println("开始");	
		//定义两个变量
		int a = 10;
		int b = 20;	
		//需求:判断a和b的值是否相等,如果相等,就在控制台输出:a等于b
		if(a == b) {
    
    
			System.out.println("a等于b");
		}		
		//需求:判断a和c的值是否相等,如果相等,就在控制台输出:a等于c
		int c = 10;
		if(a == c) {
    
    
			System.out.println("a等于c");
		}		
		System.out.println("结束");
	}
}
2.10.2.1.2、格式2
格式:
if (关系表达式) {
    
    
    语句体1;	
} else {
    
    
    语句体2;	
}

执行流程:

  • ①首先计算关系表达式的值
  • ②如果关系表达式的值为true就执行语句体1
  • ③如果关系表达式的值为false就执行语句体2
  • ④继续执行后面的语句内容

insert image description here

public class IfDemo02 {
    
    
	public static void main(String[] args) {
    
    
		System.out.println("开始");		
		//定义两个变量
		int a = 10;
		int b = 20;
		//需求:判断a是否大于b,如果是,在控制台输出:a的值大于b,否则,在控制台输出:a的值不大于b
		if(a > b) {
    
    
			System.out.println("a的值大于b");
		} else {
    
    
			System.out.println("a的值不大于b");
		}		
		System.out.println("结束");
	}
}
2.10.2.1.3、格式3
格式:
if (关系表达式1) {
    
    
    语句体1;	
} else if (关系表达式2) {
    
    
    语句体2;	
} 
else {
    
    
    语句体n+1;
}

执行流程:

  • ①首先计算关系表达式1的值
  • ②如果值为true就执行语句体1;如果值为false就计算关系表达式2的值
  • ③如果值为true就执行语句体2;如果值为false就计算关系表达式3的值
  • ④…
  • ⑤如果没有任何关系表达式为true,就执行语句体n+1。

insert image description here

//95~100 自行车一辆
//90~94   游乐场玩一天
//80 ~ 89 变形金刚一个
//80 以下  胖揍一顿

//1.键盘录入一个值表示小明的分数
Scanner sc = new Scanner(System.in);
System.out.println("请输入小明的成绩");
int score = sc.nextInt();
//2.对分数的有效性进行判断
if(score >= 0 && score <= 100){
    
    
    //有效的分数
    //3.对小明的分数进行判断,不同情况执行不同的代码
    if(score >= 95 && score <= 100){
    
    
        System.out.println("送自行车一辆");
    }else if(score >= 90 && score <= 94){
    
    
        System.out.println("游乐场玩一天");
    }else if(score >= 80 && score <= 89){
    
    
        System.out.println("变形金刚一个");
    }else{
    
    
        System.out.println("胖揍一顿");
    }
}else{
    
    
    //无效的分数
    System.out.println("分数不合法");
}
2.10.2.2、switch-case
switch (表达式) {
    
    
	case 1:
		语句体1;
		break;
	case 2:
		语句体2;
		break;
	...
	default:
		语句体n+1;
		break;
}
  • 首先计算出表达式的值
  • 其次,和case依次比较,一旦有对应的值,就会执行相应的语句,在执行的过程中,遇到break就会结 束。
  • 最后,如果所有的case都和表达式的值不匹配,就会执行default语句体部分,然后程序结束掉。
/**
*
	需求:键盘录入星期数,显示今天的减肥活动。
	周一:跑步  
	周二:游泳  
	周三:慢走  
	周四:动感单车
	周五:拳击  
	周六:爬山  
	周日:好好吃一顿
**/
public class SwitchDemo2 {
    
    
    public static void main(String[] args) {
    
    
        //1.键盘录入一个整数表示星期
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个整数表示星期");
        int week = sc.nextInt();

        //2.书写一个switch语句去跟week进行匹配
        switch (week){
    
    
            case 1:
                System.out.println("跑步");
                break;
            case 2:
                System.out.println("游泳");
                break;
            case 3:
                System.out.println("慢走");
                break;
            case 4:
                System.out.println("动感单车");
                break;
            case 5:
                System.out.println("拳击");
                break;
            case 6:
                System.out.println("爬山");
                break;
            case 7:
                System.out.println("好好吃一顿");
                break;
            default:
                System.out.println("输入错误,没有这个星期");
                break;
        }
    }
}

注意: switch结构中的表达式,只能是如下的六种数据类型之一:byte、short、char、int、枚举类型(JDK5.0)、String类型(JDK7.0) ,不能是:long,float,double,boolean。

  • default可以放在任意位置,也可以省略
  • 不写break会引发case穿透现象

2.10.3、循环结构

循环语句可以在满足循环条件的情况下,反复执行某一段代码,这段被重复执行的代码被称为循环体语句,当反复执行这个循环体时,需要在合适的时候把循环判断条件修改为false,从而结束循环,否则循环将一直执行下去,形成死循环。

2.10.3.1、for循环结构
for (初始化语句;条件判断语句;条件控制语句) {
    
    
	循环体语句;
}
  • 初始化语句: 用于表示循环开启时的起始状态,简单说就是循环开始的时候什么样
  • 条件判断语句:用于表示循环反复执行的条件,简单说就是判断循环是否能一直执行下去
  • Loop body statement: It is used to express the content of the repeated execution of the loop, in short, it is the thing that is repeatedly executed in the loop
  • Conditional control statement: used to indicate the content of each change in the loop execution, in short, it is to control whether the loop can be executed

Implementation process:

  • ①Execute the initialization statement
  • ② Execute the conditional judgment statement to see if the result is true or false
    • If false, the loop ends
    • If true, continue execution
  • ③ Execute the loop body statement
  • ④Execute conditional control statement
  • ⑤Back to ②Continue
//需求:打印5次HelloWorld
//开始条件:1
//结束条件:5
//重复代码:打印语句

for (int i = 1; i <= 5; i++) {
    
    
    System.out.println("HelloWorld");
}
2.10.3.2, while loop
初始化语句;
while(条件判断语句){
    
    
	循环体;
	条件控制语句;
}
/*
While循环结构的使用
一、循环结构的四个要素
① 初始化条件
② 循环条件
③ 循环体
④ 迭代条件

二、while循环的结构
①初始化部分
while(②循环条件部分){
    ③循环体部分;
    ④迭代部分;
}

执行过程: ① - ② - ③ - ④ - ② -  ③ - ④ - ... - ② 

说明:
1.写while循环千万要小心不要丢了迭代条件。一旦丢了,就可能导致死循环!
2.写程序要避免死循环。
3.能用while循环的,可以用for循环,反之亦然。二者可以相互转换。
区别:for循环和while循环的初始化条件部分的作用范围不同。

算法:有限性。
*/
class WhileTest{
    
    
	public static void main(String[] args){
    
    
		//遍历100以内的所有偶数
		int i = 1;
		while(i <= 100){
    
    
			if(i % 2 == 0){
    
    
				System.out.println(i);
			}
			i++;
		}
	}
}

2.10.3.3, do...while loop
do-while循环结构的使用
一、循环结构的四个要素
① 初始化条件
② 循环条件 --->boolean类型
③ 循环体
④ 迭代条件

二、do-while循环的结构
do{
    
    ;;
}while();

执行过程:① ------- ... -
 
说明:do-while循环至少执行一次循环体。

class DoWhileTest{
    
    
	public static void main(String[] args){
    
    
		//遍历100以内的所有偶数,并计算所有偶数的和和偶数的个数
		int number = 1;
		int sum = 0;	//记录总和
		int count = 0;	//记录个数
		do{
    
    
			if(number % 2 == 0){
    
    
				System.out.println(number);
				sum += number;
				count++;
			}
			number++;
		}while(number <= 100);

		System.out.println("总和为:" + sum);
		System.out.println("个数为:" + count);

		//*********************************
		int numb = 10;
		while(numb > 10){
    
    
			System.out.println("hello:while");
			numb--;
		}

		int numb2 = 10;
		do{
    
    
			System.out.println("hello:do-while");
			numb2--;
		}while(numb2 > 10);
	}
}

2.11, the use of conditional control statements break and continue

  • break
  • continue

2.11.1、break

break: cannot exist alone. It can be used in switch and loop to indicate the end and jump out.

//1.吃1~5号包子
for (int i = 1; i <= 5; i++) {
    
    
    System.out.println("在吃第" + i + "个包子");
    //2.吃完第三个的时候就不吃了
    if(i == 3){
    
    
        break;//结束整个循环。
    }
}

2.11.2、continue

continue: cannot exist alone. It can only exist in the loop, which means: skip this loop and continue to execute the next loop.

//1.吃1~5号包子
for (int i = 1; i <= 5; i++) {
    
    
    //2.第3个包子有虫子就跳过,继续吃下面的包子
    if(i == 3){
    
    
        //跳过本次循环(本次循环中,下面的代码就不执行了),继续执行下次循环。
        continue;
    }
    System.out.println("在吃第" + i + "个包子");
}

Guess you like

Origin blog.csdn.net/prefect_start/article/details/130183956