Study Notes: Dark Horse Programmer Java-Basics (Part 1)

Java language introduction to mastery chapters

  1. Study notes: Java-Basics (Part 1)_ljtxy.love’s blog-CSDN blog
  2. Study Notes: Java-Intermediate (Part 2)_ljtxy.love’s Blog-CSDN Blog
  3. Study Notes: Java-Advanced Chapter (Part 3)_ljtxy.love’s Blog-CSDN Blog
  4. Study Notes: Java-Advanced Chapter (1) (Part 4)_ljtxy.love's Blog-CSDN Blog
  5. Study Notes: Java-Advanced Chapter (2) (Part 5)_ljtxy.love’s Blog-CSDN Blog
  6. Study Notes: New Features of Java8_ljtxy.love’s Blog-CSDN Blog

Article directory

1 Overview

Summary of notes:

  1. Definition: Java is a high-level language . It is designed as a general-purpose, object-oriented programming language that is cross-platform and portable
  2. Features: Easy to learn, object-oriented programming, platform independence, security, high performance, multi-thread support, open source and free
  3. Cross-platform principle: Java provides different virtual machines for different operating systems . For different operating systems, install different virtual machines.
  4. Three major versions:
    • JavaSE: SE is the standard version, which contains the Java core class library and is mainly used to develop desktop applications.
    • JavaME: ME is a micro version, which contains the SE central classification library and has its own extensions. It is mainly used for mobile embedded development .
    • JavaEE: EE is the enterprise version, including SE and extensions (Servlet, JDBC, etc.), mainly used to develop distributed network programs
  5. JRE、JVM、JDK:
    • JVM (Java Virtual Machine), Java virtual machine
    • JRE (Java Runtime Environment), Java runtime environment , includes JVM and Java core class library (Java API)
    • JDK (Java Development Kit) is called Java development tool, including JRE and development tools
  6. Download and install
  7. Catalog introduction
  8. Environment variable configuration

1.1 Definition

Java is a widely used computer programming language launched in 1995 by Sun Microsystems (later acquired by Oracle). It is designed as a general-purpose, object-oriented programming language that is cross-platform and portable

Replenish:

  • Language: the way people communicate with each other

  • Computer language: a special language for information exchange between humans and computers

1.2 Features

  1. Easy to learn: Java uses a syntax similar to C++, but it removes some complex features that can easily lead to errors, making it easier to learn.
  2. Object-oriented programming: Java is a fully object-oriented programming language, which means that all program elements are objects, and the logic of the program is realized through the interaction between objects.
  3. Cross-platform : Java programs can run on different platforms because Java programs are run through JVM (Java Virtual Machine), which can execute the same Java code on different platforms.
  4. Security : Java is a highly secure programming language as it has built-in security mechanisms such as memory management, exception handling, and access control.
  5. High Performance : Although Java is an interpreted language, it can improve performance through JIT (Just-In-Time Compilation) technology.
  6. Multi-thread support: Java provides built-in multi-thread support, making it easy for programmers to write multi-thread programs.
  7. Open source and free: Java is an open source and free programming language, and its development tools and operating environment can be obtained through many channels.

The principle of cross-platform Java language

  • The operating system itself actually does not understand the Java language.
  • But for different operating systems, Java provides different virtual machines .

Insert image description here

image-20230227102000755

1.3 three major versions

​ JavaSE、JavaME、JavaEE

1.3.1JavaSE Standard Edition

JavaSE (Java Platform, Standard Edition), the Java language (Standard Edition), is used for the development of desktop applications and is the basis for the other two versions.

1.3.2JavaME Micro Edition

​ JavaME (Java Platform, Micro Edition), a small version of the Java language, is used for the development of embedded consumer electronic devices or small mobile devices . (embedded, TV, microwave oven, TV, etc.), the most important of which is the development of small mobile devices (mobile phones). It has gradually declined and has been replaced by Android and IOS. However, Android can also be developed in Java.

1.3.3JavaEE Enterprise Edition

​ JavaEE (Java Platform, Enterprise Edition) is used for Web-oriented website development. (Mainly engaged in the development of backend servers) In the field of servers, Java is the well-deserved leader.

Insert image description here

1.3JDK installation

1.3.1 Overview

  • JVM (Java Virtual Machine), Java virtual machine
  • JRE (Java Runtime Environment), Java runtime environment , includes JVM and Java core class library (Java API)
  • JDK (Java Development Kit) is called Java development tool, including JRE and development tools

Insert image description here

illustrate:

When we develop, we only need to install the JDK , which includes the Java operating environment and virtual machine. When we only need to run, we only need to install JRE

1.3.2基本用例

说明:

通过官方网站获取JDK,网址:Java Downloads | Oracle 中国

注意:

  • 安装路径不要有中文,不要有空格等一些特殊的符号。
  • 以后跟开发相关的所有软件建议都安装在同一个文件夹中,方便管理。

步骤一:下载JDK
Insert image description here

补充:安装目录

Insert image description here

  • 以上是JDK17的安装目录,以下是JDK的目录解释
目录名称 说明
bin 该路径下存放了JDK的各种工具命令。javac和java就放在这个目录。
conf 该路径下存放了JDK的相关配置文件。
include 该路径下存放了一些平台特定的头文件
jmods 该路径下存放了JDK的各种模块
legal 该路径下存放了JDK各模块的授权文档
lib 该路径下存放了JDK工具的一些补充JAR包

步骤二:环境变量配置

说明:

​ 开发Java程序,需要使用JDK提供的开发工具(比如javac.exe、java.exe等命令),而这些工具在JDK的安装目录的bin目录下,如果不配置环境变量,那么这些命令只可以在bin目录下使用,而我们想要在任意目录下都能使用,所以就要配置环境变量

1.配置JAVA_HOME环境

image-20230809140945961

2.配置PATH环境

Insert image description here

补充:

  • JAVA_HOME:告诉操作系统JDK安装在了哪个位置(未来其他技术要通过这个找JDK)
  • Path : Tell the operating system where the javac (compile) and java (execution) commands provided by JDK are installed.

Step 3: Demo

  • Create a new cmd naming window and enterjava --version

image-20230809141449697

illustrate:

​ Here you can see that the JDK version is 17

2. Basic use case-HelloWorld

Summary of notes:

The Java program development and operation process requires three steps: write the program, compile the program, and run the program

illustrate:

HelloWorldDemonstrate the basic execution flow of Java processes through programs

Step 1: Create a Java program

  • Create a new HelloWorld.classfile and write
class HelloWorld {
    
    
    public static void main(String[] args) {
    
    
        System.out.println("Hello, World!"); 
    }
}

Step 2: Compile the Java program

illustrate:

​isjavac a command-line tool for the Java compiler that compiles Java source code files ( .javaending with the extension) into Java bytecode files ( .classending with the extension). Java bytecode files can be run on the Java Virtual Machine (JVM).

  • Open a command line window and execute javacthe command
javac HelloWorld.java

Description: result

Insert image description here

Step 3: Execute the bytecode file

  • Open a command line window and execute javacommands in the current directory
java HelloWorld

Description: result

Insert image description here

Notice:

When running class files, no .classsuffix is ​​required

3. Basic grammar

Summary of notes:

  1. Comments : single-line comments, multi-line comments, documentation comments

  2. Keywords:

    • Definition: English words given a specific meaning by Java
    • class、static、……
  3. Literal:

    • Definition: The writing format of data in the program
    • 666、”MySoul“、……
  4. variable:

    • Definition: A container for temporary storage of data
    • int a = 16;、double b = 10.1;、……
    • Note: Variables in Java need to have variable type, variable name and end with semicolon
  5. type of data:

    • Basic data types: byte, short, int, long, float, double, char and boolean
    • Reference data types: strings, arrays, classes and interfaces,…
    • difference :
      1. Primitive data types are stored on the stack , while reference data types are stored on the heap.
      2. Variables of basic data types are independent of each other , while variables of reference data types may share the same object.
  6. Identifier:

    • Definition: Identifiers are names used to name program elements such as variables, methods, classes, and interfaces.
    • Notice:
      1. Must consist of numbers, letters, **underscore_, dollar sign $**.
      2. Numbers cannot begin with
      3. cannot be a keyword
      4. case sensitive
    • Alibaba naming convention details
  7. Permission modifiers:

    • Definition: Permission modifier is a keyword in Java that is used to control access permissions to classes, methods, and variables
    • Permission scope: private< 默认/空着不写< protected<public
  8. Bag:

    • Definition: A package is a mechanism for organizing and managing Java classes

    • Naming conventions:

      路径名.路径名.xxx.xxx
      // 例如:com.itheima.oa
      
    • Importing the package: It is not necessary to import the package under the java.lang package. Because of the Java development environment, the default is the lang package.

3.1 Notes

3.1.1 Overview

Comments are explanations and explanations of the code

3.1.2 Classification

There are three types of comments in Java:

  • Single line comment:
// 这是单行注释文字
  • Multi-line comments:
/*
这是多行注释文字
这是多行注释文字
这是多行注释文字
*/

Notice:

​ Multi-line comments cannot be nested!

  • Documentation comments (not used yet)
/**
这是多行注释文字
这是多行注释文字
这是多行注释文字
*/

Instructions: Techniques used

  • If we want to explain the code, we can use comments
  • When the content of the comment is relatively small and can be written in one line, you can use a single-line comment.
  • If the content of the comment is relatively large and needs to be written on multiple lines, you can use multi-line comments.

3.2 Keywords

3.2.1 Overview

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

3.2.2 Classification

Java keywords are predefined vocabulary with special meaning in the programming language, these keywords are used to control the structure, flow and behavior of the program

Notice

There are many keywords, so you don’t have to remember them carefully.

  1. Modifier keywords : public, protected, private, static, final,abstract
  2. Access control keywords : public, protected, private, default(default)
  3. Class, interface and package keywords : , class, interface, enum, , package, import,extendsimplements
  4. Method keywords : void, return, this,super
  5. Process control keywords : if, else, switch, case, , default, while, do, for, break,continuereturn
  6. Exception handling keywords : try, catch, finally, throw,throws
  7. Logical keywords : true, false,null
  8. Other keywords : new, instanceof, synchronized, transient, volatile,assert

3.2.3 Basic use case-keyword demonstration

  • ClassClass This keyword indicates defining a class
public class HelloWorld{
    
    
    
}

illustrate:

  • Explanation: class means defining a class

  • Class name: HelloWorld

  • The curly brackets after HelloWorld indicate the scope of this class

3.3 Literals

3.3.1 Overview

Java literals are constant values ​​used directly in programs, which represent fixed values ​​of various data types. Literals can be constant values ​​of data types such as integers, floating point numbers, characters, and strings. They appear directly in the code without calculation or conversion.

3.3.2 Classification

  1. Integer literal : represents an integer value, and can use decimal, octal (starting with 0) and hexadecimal (starting with 0x or 0X) notation. For example: 42, 012, 0xFF.
  2. Floating-point number literal : Represents floating-point values, including ordinary floating-point numbers and scientific notation. For example: 3.14, 2.0e-5.
  3. Character literal : represents a single character, enclosed in single quotes. For example: 'A', '1', '@'.
  4. String literal : represents a string, enclosed in double quotes. For example: "Hello, World!", "Java".
  5. Boolean literal : represents a Boolean value, with only two values: trueand false.
  6. Null Literal : Indicates a null reference, which is used to indicate that the object reference does not point to any valid object.
  7. Escape sequence : Some special character sequences, starting with a backslash \, are used to represent characters that cannot be input directly, such as newline characters \n, tab characters, \tetc.
  8. Array literal : represented by curly braces {}, used to initialize the array. For example: {1, 2, 3}.
  9. Enumeration constant : A constant value of an enumeration type that represents a specific option in the enumeration.
  10. Character encoding literal : indicates the Unicode encoding of the character, starting with \u, followed by four hexadecimal digits. For example: \u0041represents the character 'A'.

3.3.3 Basic use cases

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("欢迎来到黑马程序员"); // 输出字符串
    }
}

Supplement: Distinguishing skills

  1. Numbers without a decimal point are literals of integer type.
  2. As long as there is a decimal point , it is a literal value of 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. A boolean literal has only two values, true and false.
  6. A literal of empty type has only one value, null

3.4 Variables

3.4.1 Overview

Variables are containers for temporarily storing data in a program. But only one value can be stored in this container.

3.4.2 Format

数据类型 变量名 = 数据值;

illustrate:

  • 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.

Supplement: Parameter explanation

  • Variable name: In fact, it is the name of this container

  • Data value: the data actually stored in the container

  • Semicolon: indicates the end of a sentence, just like the period used when writing essays.

3.4.3 Basic Use Case - Variable Demonstration

public class VariableDemo2{
    
    
	public static void main(String[] args){
    
    
		//1.变量名不允许重复
		//int a = 10;
		//int a = 20;
		//System.out.println(a);
		
		//2.一条语句可以定义多个变量
		//了解。
		//int a = 10, b = 20, c = 20,d = 20;
		//System.out.println(a);//?
		//System.out.println(b);//?
		
		
		//3.变量在使用之前必须要赋值
		int a = 30;
		System.out.println(a);
	}
}

Notice:

  • Variable names cannot be repeated
  • In one statement, multiple variables can be defined. But this method affects the reading of the code, so just understand it.
  • Variables must be assigned a value before they can be used.

3.5 Data types

3.5.1 Overview

Java data types are classifications used to define the types of data that a variable or expression can store.

3.5.2 Classification

  • Basic data types
  • Reference data types (learn more about object-oriented)

3.5.3 Basic data types

  1. Integer Types : byte:8 bits, ranging from -128 to 127, short:16 bits, ranging from -32,768 to 32,767, int:32 bits, ranging from -2^31 to 2^31 - 1, long:64 bits, The range is -2^63 to 2^63 - 1
  2. Floating-Point Types : float: 32-bit, used to represent single-precision floating-point numbers, double: 64-bit, used to represent double-precision floating-point numbers
  3. Character Type (Character Type) : char: 16 bits, used to store a Unicode character
  4. Boolean Type (Boolean Type) : boolean: used to represent Boolean values, only two values: trueandfalse

Notice:

  • Value range of byte type: -128 ~ 127
  • Approximate value range of int type: -more than 2.1 billion ~ more than 2.1 billion

Supplement: The relationship between the value range of integer type and decimal type:

  • double > float > long > int > short > byte
  • Integer defaults to int type in java, and floating point number defaults to double type

Code example:

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);

    }
}

Notice:

  • If you want to define a variable of integer type and don't know which data type to choose, int is used by default.
  • If you want to define a variable of decimal type and don't know which data type to choose, double is used by default.
  • If you want to define a long type variable, you need to add the L suffix after the data value . (Both uppercase and lowercase letters are acceptable, but uppercase letters are recommended.)
  • If you want to define a float type variable, you need to add the F suffix after the data value . (Both upper and lower case are acceptable)

3.5.4 Reference data types

  1. Class : Class is a template used to create objects. It defines the properties (member variables) and methods (member methods) of the object. By instantiating a class, you create an object of the class and use the object to call the class's methods.
  2. Interface : An interface defines a set of method specifications, but has no actual method body. A class can implement one or more interfaces to obtain the methods defined by the interface and implement these methods in the class.
  3. Array : An array is a data structure used to store elements of the same type. It can be a one-dimensional array or a multi-dimensional array used to store multiple elements contiguously in memory.
  4. Enum (Enum) : An enumeration is a special class used to represent a set of predefined constants. Enumerations are often used to represent a group of related values.
  5. String : String is a reference data type, but it has special properties that allow it to be manipulated like a basic data type. A string is actually a sequence of characters, and it has many methods for handling string operations.
  6. Custom reference types : In addition to the above-mentioned built-in reference data types, developers can also create custom classes and interfaces, as well as their instances, to build more complex data structures and functions.

3.5.5 The difference between basic data types and reference data types

  1. Basic data types: Basic data types are passed by value, they allocate memory space in the Java virtual machine stack and store the value itself directly. When a variable of a basic data type is assigned a value, the value in the variable is actually copied to another variable. There is no relationship between the two variables.
  2. Reference data types: Reference data types are passed by reference. They allocate memory space in the Java virtual machine heap and store the reference (memory address) of the object. When a variable of a reference data type is assigned a value, the reference in the variable is actually copied to another variable, and both variables point to the same object.

Replenish:

For details, please refer to the Knowledge Gas Station基本数据类型和引用数据类型区别

Code example:

// 使用引用数据类型创建一个对象
String message = new String("Hello, World!");

// 创建一个数组
int[] numbers = new int[5];

// 使用自定义类创建对象
class Person {
    
    
    String name;
    int age;
}
Person person = new Person();
person.name = "Alice";
person.age = 30;

// 枚举类型
enum Day {
    
    
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Day today = Day.WEDNESDAY;

3.5.6 Commonly used data types

  • ​ Integer: int
  • ​ Decimal: (floating point number) double

Code example:

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
	}
}

Replenish:

​ null cannot be printed directly. If you need to print, you need to print it in the form of a string.

The most commonly used data type selections:

  • When defining variables, different types of variables should be selected according to the actual situation.

    For example: for a person’s age , you can choose the byte type

    For example: for the age of the earth , you can choose the long type

  • If the range is not certain in the integer type , then the int type is used by default.

  • If the decimal type is not sure of the range , then the double type is used by default.

  • If you want to define a variable of character type , use char

  • If you want to define a variable of Boolean type , use boolean

3.6 Identifier

In Java, identifiers are the names used to identify various elements in the program , such as variables, methods, classes, interfaces, etc. An identifier is a sequence of letters, numbers, an underscore (_), and a dollar sign ($), and must begin with a letter, an underscore, or a dollar sign. Identifiers are used in programming to name various entities, making the program easier to read, understand, and maintain.

3.6.1 Mandatory requirements

This must be done, otherwise the code will report an error.

  • Must consist of numbers, letters, underscore_, **dollar sign$**.
  • Numbers cannot begin with
  • cannot be a keyword
  • Case sensitive.

3.6.2 Soft suggestions

1. Small hump nomenclature

Applies to variable names and method names

  • If it is a word, then all lowercase, such as: name

  • If it is multiple words, start with the second word and capitalize the first letter, for example: firstName, maxAge

2. Big camel case nomenclature

applies to class names

  • If it is a word, capitalize the first letter. For example: Demo, Test.

  • If there are multiple words, the first letter of each word needs to be capitalized. For example: Hello World

3.6.3 Alibaba Naming Specification Details

  1. Try not to use pinyin. However, some internationally accepted pinyin can be regarded as English words.

    Correct: alibaba, hangzhou, nanjing

    错误:jiage、dazhe

  2. When naming variables, methods, and classes, do not use underscores or dollar signs.

    Error: _name

    Correct: name

3.7 Permission modifiers

3.7.1 Overview

​ There are four types of access rights in Java. When using different access rights modifiers, the modified content will have different access rights. We have learned and before. Next, let’s study protected public and privatedefault modifiers role.

  • public: public, accessible from everywhere.

  • protected: This class, this package, and subclasses in other packages can access it.

  • Default (no modifier): this class, accessible to this package.

    Note: The default is to leave it blank and not write it, it is not default.

  • private: private, accessible to the current class.
    public > protected > 默认 > private

3.7.2 Permission access capabilities

Scope of authority

private<Default/leave blank<protected<public

public protected default private
in the same class
classes in the same package
Subclasses of different packages
Unrelated classes in different packages

It can be seen that public has the greatest authority. Private is the least privileged.

When writing code, if there are no special considerations, it is recommended to use permissions like this:

  • Member variables are used to privatehide details.
  • Use the constructor method publicto facilitate object creation.
  • Member methods are used to publicfacilitate calling methods.

Replenish:

Without permission modifier, it is the default permission.

3.7.3 Permission usage rules

In actual development, generally only private and public are used

  • Member variables private
  • method public

Notice:

​ If the code in a method is to extract common code from other methods, this method is generally also private.

3.8 pack

3.8.1 Overview

In Java, packages are a way of organizing classes and interfaces . They classify related classes and interfaces into a namespace through logical organization. The main purpose of packages is to avoid naming conflicts and provide better code management and organization

A package is actually a folder in the operating system. Packages are used to classify management technologies. Different technology categories are placed under different packages to facilitate management and maintenance.

In the IDEA project, the package building operations are as follows:

image-20230813112207023

Naming convention for package names :

路径名.路径名.xxx.xxx
// 例如:com.itheima.oa
  • The package name is usually the company domain name spelled backwards. For example, if the dark horse is www.iheima.com, the package name can be defined as com.iheima.technical name.
  • Package names must be connected with ".".
  • Each pathname in the package name must be a legal identifier and cannot be a Java keyword.

3.8.2 Guide package

When is a guide package needed?

​ Situation 1: When using classes in the **non-core package (java.lang)** provided in Java

​ Situation 2: When using classes in other packages written by yourself

When is no guide package needed?

​ Situation 1: When using classes in the Java core package ( java.lang )

​ 情况二:在使用自己写的同一个包中的类时

假设demo1和demo2中都有一个Student该如何使用?

代码示例:

//使用全类名的形式即可。
//全类名:包名 + 类名
//拷贝全类名的快捷键:选中类名crtl + shift + alt + c 或者用鼠标点copy,再点击copy Reference
com.itheima.homework.demo1.Student s1 = new com.itheima.homework.demo1.Student();
com.itheima.homework.demo2.Student s2 = new com.itheima.homework.demo2.Student();

4.IDEA开发工具

笔记小结:

  1. 概述:目前用于Java程序开发最好的工具
  2. 层级结构介绍:project - module - package - class
  3. 类操作
    • 新建类文件
    • 删除类文件
    • 修改类文件
  4. 模块操作
    • 新建模块
    • 删除模块
    • 修改模块
    • 导入模块
  5. 项目操作
    • 关闭项目
    • 打开项目
    • 修改项目
    • 新建项目

4.1概述

​ IDEA全称IntelliJ IDEA,是用于Java语言开发的集成环境,它是业界公认的目前用于Java程序开发最好的工具。

补充:

​ 把代码编写,编译,执行,调试等多种功能综合到一起的开发工具

4.2安装

说明:

​ 学习好东西,参考链接:IDEA2023.学习持续更新-搜云库技术团队 (souyunku.com)

步骤一:下载

说明:

​ 下载链接为:https://www.jetbrains.com/idea

image-20230809160833406

步骤二:安装

1.进入安装界面

image-20230227141623703

2.修改安装目录

image-20230227141634020

说明:

​ 建议不要放在C盘

3.额外选项

image-20230227141649386

说明:

​ 勾选64-bit launcher。表示在桌面新建一个64位的快捷方式。

4.安装

image-20230227141701750

5.启动

Insert image description here

说明:

​ 选择第二个不导入,保持默认设置,再点击OK

4.3目录层级结构

笔记小结

  • 层级关系:project - module - package - class

  • 包含数量:

  • 一个project中可以创建多个module

  • 一个module中可以创建多个package

  • 一个package中可以创建多个class

3.4.1概述

image-20230227141855655

补充:结构分类

  • project(项目、工程)
  • module(模块)
  • package(包)
  • class

4.3.2 Project

​ Taobao, JD.com, and Dark Horse programmer websites all belong to projects, and IDEA is a Project.

4.3.2 Module

​ In a project, multiple modules can be stored, and different modules can store different business function codes in the project. The official website of Dark Horse Programmers contains at least the following modules:

  • forum module
  • Registration and consultation modules

4.3.3 Package

There are many businesses in one module. Taking the forum module of the Black Horse Programmer official website as an example, it contains at least the following different businesses.

  • post
  • Comment

In order to distinguish these businesses more clearly, packages will be used to manage these different businesses.

4.3.4 Classes

4.4 Common Configurations

1. Modify the font

image-20230227142334713

illustrate:

Choose Consolas as the font. This font is softer.

Related operations of category 4.5

Class related operations

  • Create new class file
  • Delete class files
  • Modify class files

4.6 Module related operations

Module related operations

  • new module
  • Delete module
  • modify module
  • import module

4.7 Project related operations

Project related operations

  • Close project
  • Open project
  • Modify project
  • New Project

Modify project

Click File and select Project Structure

image-20230227143125944

In this interface, the default is Module

So, first click on Project

On the right page, enter a new project name

Modify the JDK version and compiled version to JDK14

Click OK again

image-20230227143221007

  • At this time, it was discovered that the project name has been modified.

image-20230809165947767

  • But the name of the local folder has not been changed yet

image-20230809170012544

  • Need to close the current project first

image-20230809170022657

  • Click the cross next to an item to remove it from the list

image-20230809170033150

  • Manually modify the name of the folder on your local hard drive
  • Click Open or Import to reopen the project

image-20230809170043305

  • Select the modified item

    click OK

image-20230809170052181

  • At this point you will find that the project name and the name of the local hard disk folder have been modified.

image-20230809170059554

4.8 Plug-in management

Reference links:

IntelliJ Idea uses 12 commonly used plug-ins (to improve development efficiency), with excellent theme plug-ins_idea plug-ins_Java technology climber's blog-CSDN blog

20 excellent plug-ins worth recommending by IDEA_idea plug-in_Xinyuan Yima's blog-CSDN blog

5. Operators and expressions

Summary of notes:

  1. Overview:

    1. Java operators are special symbols used to perform operations on one or more operands

    2. An expression is a grammatical statement composed of variables, constants, operators, and method calls.

    3. The difference between operators and expressions:

      • Operators are symbols that operate on constants or variables.

      • An expression is an expression that conforms to Java syntax.

  2. Arithmetic operators:

    • Definition: Arithmetic operators are used to perform basic mathematical operations

    • For example:

      +-*/ 
      
  3. Increment and decrement operators:

    • Definition: The increment and decrement operator is a special arithmetic operator used to add or subtract 1 to the value of a variable .

    • For example:

       ++--
      
  4. Assignment operator:

    • Definition: The assignment operator is an operator used to assign values ​​to variables in Java.

    • For example:

      b = 20;
      
  5. Extended assignment operator:

    • Definition: The extended assignment operator is an operator that combines arithmetic operators and assignment operators

    • For example:

       "+=""-=""*=""/=""%="
      
    • Features: The extended assignment operator also includes a forced conversion in the hidden layer

  6. Relational operators:

    • Meaning: Relational operators are used to compare the size relationship between two values.

    • For example:

      a > b
      
    • Note: Distinguish between == and = assignment operators and relational operators

  7. Logical Operators:

    • Meaning: Used to combine multiple Boolean expressions to generate a new Boolean expression

    • For example:

      true & truefalse & false
      
    • Note: Logical operators also have

      !、&|^ 
      
  8. Short-circuiting logical operators:

    • Meaning: If the result of the entire expression can be determined , do not continue to calculate the remaining expression.

    • For example:

      用户名正确  && 密码正确
      
  9. Ternary operator:

    • Meaning: Known as the conditional operator, it is the only operator in Java with three operands

    • Format:

      关系表达式 ? 表达式1 :表达式2
    • For example:

      a > b ? a : b
      
  10. Operator precedence: parentheses first ()

  11. Implicit conversion and forced conversion

    1. Implicit conversion: automatic type promotion

      • Value relationship: byte < short < int < long < float < double
      • Note: The storage space of float type is smaller than that of long type, but the representation range of float type is larger than that of long type.
    2. Cast: forced type promotion

      • Format:

        目标数据类型 变量名 = (目标数据类型)被强转的数据
        
  12. String + operation (special case):

    • Meaning: When a character appears in the + operation, the character will be taken to the computer's built-in ASCII code table to look up the corresponding number, and then the calculation will be performed.

    • For example:

      char c = 'a';
      int result = c + 0;
      System.out.println(result);//9
      

5.0 Overview

5.0.1 Definition

Java operators are special symbols used to perform operations on one or more operands. An expression is a grammatical statement composed of variables, constants, operators, and method calls.

5.0.2 Operators

Definition: It is a symbol that operates on constants or variables.

for example:

 +  -  *  / 

5.0.3 Expressions

Definition: A formula that uses operators to connect constants or variables and conforms to Java syntax is an expression.

for example:

a + b 这个整体就是表达式。

illustrate:

​ And + is a type of arithmetic operator, so this expression is also called an arithmetic expression.

5.1 Arithmetic operators

5.1.1 Overview

5.1.1.1Definition

Arithmetic operators are used to perform basic mathematical operations, such as addition, subtraction, multiplication, division, and modulo (remainder) operations. In Java, arithmetic operators include plus sign (+), minus sign (-), multiplication sign (*), division sign (/), and modulo operator (%). These operators can be used to handle variables of numeric types such as int, long, float, and double

5.1.1.2 Classification

+ - * / %

5.1.1.3 Features

+ - * :跟小学数学中一模一样没有任何区别.

5.1.2 Basic use case - operator demonstration

/Number

/1.整数相除结果只能得到整除,如果结果想要是小数,必须要有小数参数。
2.小数直接参与运算,得到的结果有可能是不精确的。
案例:
System.out.println( 10 / 3);//3
System.out.println(10.0 / 3);//3.3333333333333335

%Number

%:取模、取余。
   他做的也是除法运算,只不过获取的是余数而已。
案例:
System.out.println(10 % 2);//0
System.out.println(10 % 3);//1
应用场景:
//可以利用取模来判断一个数是奇数还是偶数
System.out.println(15 % 2);//1  奇数

5.1.3 Case - numerical splitting

Demonstration: Enter a three-digit number with the keyboard, split it into units, tens, and hundreds, and then print it on the console

//1.键盘录入一个三位数
//导包 --- 创建对象 --- 接收数据
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个三位数");
int number = sc.nextInt();//123

//2.获取这个三位数的个位、十位、百位并打印出来
//公式:
//针对于任意的一个数而言
//个位: 数字 % 10
int ones = number % 10;
//十位: 数字 / 10 % 10
int tens = number / 10 % 10;
//百位: 数字 / 100 % 10
int hundreds = number / 100  % 10;

//输出结果
System.out.println(ones);
System.out.println(tens);
System.out.println(hundreds);

detail:

  • Formula: Get every digit of any number.

    1. Units place: number % 10

    2. Tens digit: number/10 % 10

    3. Hundreds place: number / 100 % 10

    4. Thousands: Number / 1000 % 10

    5. ……

5.2 Increment and decrement operators

5.2.1 Overview

5.2.1.1 Definition

The increment and decrement operator is a special arithmetic operator used to add or subtract 1 to a variable. In Java, there are two forms of increment and decrement operators: prefix form and suffix form.

5.2.1.2 Classification

++  自增运算符

illustrate:

++: Just add 1 to the value in the variable

--  自减运算符

illustrate:

​ --: Just change the value in the variable to -1

5.2.1.3 Features

  • Putting it in front of the variable is called first++. For example: ++a
  • Put it after the variable, we call it post++. For example: a++

detail:

​ No matter whether it is ++ first or ++ last. When written separately on a line, the results of the operation are exactly the same.

5.2.2 Basic use case - self-increment and self-decrement demonstration

//++
int a = 10;
a++;//就是让变量a里面的值 + 1
System.out.println(a);//11
++a;//就是让变量a里面的值 + 1
System.out.println(a);//12

5.3 Assignment operator

5.3.1 Overview

The assignment operator is an operator used to assign values ​​to variables in Java. In Java, the assignment operator is represented by the equal sign (=), with the variable name on the left and the value assigned to the variable on the right.

5.3.2 Basic use case-assignment operator demonstration

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
    }
}

5.4 Spread assignment operator

4.4.1 Overview

4.4.1.1

​ The extended assignment operator refers to adding other arithmetic operators to the original assignment operator, such as +=, -=, *=etc.

5.4.1.2 Classification

​ +=、-=、*=、/=、%=

4.5.1.3 Features

​It is to perform operations on the left side and the right side, and assign the final result to the left side, without any impact on the right side.

5.4.2 Basic use case - spread operator demonstration

public class OperatorDemo7 {
    
    
    public static void main(String[] args) {
    
    
        //扩展赋值运算符
        int a = 10;
        int b = 20;
        a += b;//把左边和右边相加,再把最终的结果赋值给左边,对右边没有任何影响
        // 相当于 a = a + b;
        System.out.println(a);//30
        System.out.println(b);//20
    }
}

Notice:

  • The extended assignment operator also includes a implicit cast

  • For example:

    public class OperatorDemo8 {
           
           
        public static void main(String[] args) {
           
           
            byte a = 10;
            byte b = 20;
            //a += b;
            a = (byte)(a + b);
            System.out.println(a);//30
        }
    }
    

    Note: Take += as an example. a += b ;actually equivalent to a = (byte)(a + b);

5.5 Relational operators

5.5.1 Definition

Also called a comparison operator, it actually just makes a judgment based on the left side and the right side.

5.5.2 Classification

symbol explain
== It is to judge whether the left side and the right side are equal. If it is true, it is true. If it is not true, it is false.
!= It is to judge whether the left side and the right side are not equal. If it is true, it is true. If it is not true, it is false.
> It is to determine 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 determine 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

detail:

  • The final result of a relational operator must be of Boolean type. Either true or false
  • When writing ==, never write =

5.6 Logical operators

5.6.1 Overview

5.6.1.1Definition

​ Logical operators are operators used to connect multiple conditional expressions and are used to build complex conditional expressions.

5.6.1.2 Use of & and |

&: logical AND (and)

​ If both sides are true, the result is true. As long as one is false, the result is false.

|: logical or (or)

​ If both sides are false, the result is false. As long as one of them is true, the result is true.

5.6.2 Basic Use Case - Logical Operator Demonstration

// &  //两边都是真,结果才是真。
System.out.println(true & true);//true
System.out.println(false & false);//false
System.out.println(true & false);//false
System.out.println(false & true);//false

System.out.println("===================================");

// | 或  //两边都是假,结果才是假,如果有一个为真,那么结果就是真。
System.out.println(true | true);//true
System.out.println(false | false);//false
System.out.println(true | false);//true
System.out.println(false | true);//true

5.6.3 Application scenarios

5.6.3.1 Scenario examples

​ According to the fixed scene, choose to use & or |

  • User login.

    The username is entered correctly & the password is entered correctly

    Because only the username and password are correct at the same time, then you can log in successfully, as long as one of them fails.

    skills:

    ​ When we need to satisfy both the left and right conditions at the same time, we can use and

  • Mother-in-law chooses son-in-law

    Mother-in-law: Son-in-law, you can either buy a house or a car. Just wear my little cotton-padded jacket.

    Buy a house | Buy a car

    Of the two conditions, as long as one of them is met, the padded jacket can be worn.

    skills:

    ​ When only one of the two conditions is met, you can use or

5.6.3.2 Use of ^ (XOR)

​ It won’t be used much in the future, just understand it.

Calculation rules: If both sides are the same, the result is false; if both sides are different, the result is true

Code example:

//^   //左右不相同,结果才是true,左右相同结果就是false
System.out.println(true ^ true);//false
System.out.println(false ^ false);//false
System.out.println(true ^ false);//true
System.out.println(false ^ true);//true

5.6.3.3 Use of! (negation)

​ It is the negation, also called non.

Calculation rules: the negation of false is true, the negation of true is false

Warm reminder: Use at most one negation.

Code example:

System.out.println(!false);//true
System.out.println(!true);//false
System.out.println(!!false);//报错

detail:

​ Note: Only use at most one to negate

5.7 Short-circuit logical operators

5.7.1 Overview

5.7.1.1 Definition

​ The short-circuit logical operator means that in logical operations, if the result of the entire logical expression can be obtained based on the value of the expression on the left, the expression on the right will no longer be calculated.

5.7.1.2 Classification

  • &&

    The operation result is exactly the same as &, but it has a short-circuit effect.

  • ||

    The result of the operation is exactly the same as |. It's just a short circuit.

Logical core:

​ When the left hand side cannot determine the result of the entire expression, the right hand side will be executed.

​ When the left side can determine the result of the entire expression, then the right side will not be executed. Thereby improving the operating efficiency of the code.

5.7.2 Application scenarios

5.7.2.1 Scenarios

1. User login case

Username is correct & password is correct

If an & is used, the password will be verified regardless of whether the username is correct.

think:

​ If the user name is entered correctly, then we will judge whether the password is correct, which is in line with business logic.

​ But if the username is entered incorrectly, is it still necessary to compare passwords now? No more.

​ If you use an &, then the left and right sides will be executed regardless of the situation.

​The username is correct&& the password is correct

​ If the user name is entered correctly, then it will be verified whether the password is entered correctly.

​ If the user name is entered incorrectly, the password will not be verified and the final result will be false. This improves the efficiency of program operation.

2. Mother-in-law chooses son-in-law

Own a house | own a car

First, check to see if there is a house. If you find there is, then go and see if there is a car.

think:

Since we already have a house, why do we still need to look at the car? It's unnecessary.

​ Have a house|| have a car

​ First, check if there is a room. If there is, then the right side will not be executed. The final result is directly true.

​ If there is no house, you will look to see if there is a car on the right.

5.7.2.2 Summary

The results of && and &, || and | are exactly the same.

​ But short-circuiting logical operators can improve the running efficiency of the program.

5.7.2.3 Recommendations

​ Most commonly used: && || !

5.8 Ternary operator

5.8.1 Overview

5.8.1.1Definition

​ Ternary expression or question mark colon expression.

5.8.1.2 Format

​ Relational expression? Expression1:Expression2;

detail:

  • Evaluates a relational expression.
  • If the relational expression evaluates to true, then expression 1 is executed.
  • If the relational expression evaluates to false, then expression 2 is executed.

Notice:

The final result of the ternary operator must be used, either assigned to a variable or printed directly.

5.8.2 Basic use case - ternary operator demonstration

public class OperatorDemo12 {
    
    
    public static void main(String[] args) {
    
    
        //需求:求两个数的较大值
        int a = 10;
        int b = 20;

        //格式:关系表达式 ? 表达式1 : 表达式2 ;
        //注意点:
        //三元运算符的最终结果一定要被使用。
        //要么赋值给一个变量,要么直接输出。
       int max =  a > b ? a : b ;
        System.out.println(max);


        System.out.println(a > b ? a : b);
    }
}

5.9 Operator precedence

There are many operators involved in Java, and each operator has its own priority. But these priorities require no memory. We only need to know one thing: parentheses take precedence over all

5.10 Implicit Conversions

5.10.1 Definition

In Java, implicit conversion is to assign a data or variable with a small value range to another variable with a large value range. At this time, we do not need to write additional code to implement it separately. The program automatically completes it for us. Also called automatic type promotion. In other words, a small range data type can be given to a large range data type, and can be directly given to

5.10.2 Promotion rules

  • The smaller value range will be calculated with the larger value range. The smaller value will be promoted to the larger value first, and then the calculation will be performed.
  • When operating data of three types: byte, short, and char, they will be directly promoted to int first, and then the operation will be performed.

5.10.3 Value range relationship

​ byte < short < int < long < float < double

5.11 Force conversion

5.11.1 Concept

5.11.1.1Definition

​ If you want to assign a data or variable with a large value range to another variable with a small value range. Direct operation is not allowed.

5.11.1.2 Format

​Target data type variable name = (target data type) the data being forced;

5.11.2 Basic Use Case - Lightweight Transformation Demonstration

public class OperatorDemo2 {
    
    
    public static void main(String[] args) {
    
    
        double a = 12.3;
        int b = (int) a;
        System.out.println(b);//12
    }
}

important point:

Forced conversion may cause data errors. (The accuracy of the data is lost)

+ operation of characters in 5.12

5.12.1 Concept

​ When a character appears in the + operation, the character will be taken to the computer's built-in ASCII code table to look up the corresponding number, and then the calculation will be performed.

5.12.2 Basic Use Case - Character + Demo

char c = 'a';
int result = c + 0;
System.out.println(result);//97

illustrate:

  • In the ASCII code table:

    1. ‘a’ ----- 97

    2. ‘A’ ----- 65

5.13 Bit shift operators

In Java, the bit shift operator is an operator that operates on binary bits. It can perform bit shift operations on integer type data. Java provides three bit shift operators: left shift (<<), right shift (>>), and unsigned right shift (>>>)

  1. Left shift (<<): Shifts the binary representation of a number to the left by the specified number of digits, padding the right side with zeros . The left shift operation can be thought of as multiplying the original number by the power of 2. For example, for an integer a, a << b means shifting the binary representation of a to the left by b places.
  2. Right shift (>>): Move the binary representation of a number to the right by the specified number of digits and fill it according to the sign bit of the highest bit. The right shift operation can be regarded as dividing the original number by the power of 2 and rounding. For example, for an integer a, a >> b means shifting the binary representation of a to the right by b places.
  3. Unsigned right shift (>>>): Shifts the binary representation of a number to the right by the specified number of bits, filling it with zeros regardless of the sign bit of the highest bit. The unsigned right shift operation treats the sign bit as an ordinary bit, so it is suitable for the bit shift operation of unsigned numbers.

These bit shift operators are very useful when dealing with the binary bits of integers and are often used for bit operations, setting and clearing bit flags, and optimizing specific algorithms. Please note that the bit shift operator only works on integer types (such as int, long, etc.), not floating point types.

6. Control Statements

Summary of notes:

  1. flow control statement

    1. Sequential structure:

      • Meaning: A structure that is executed sequentially according to the order in which it is written.
    2. judgment and choice structures

      • Meaning: A structure that selects and executes different code blocks based on different conditions

      • For example:

        ifswitch
        
    3. Loop structure

      • Meaning: A structure that repeatedly executes a certain piece of code

      • For example:

        whiledowhilefor
        
      • The difference between loops: 1. The for and while loops judge first and then execute. 2.do...while is executed first, then judged

  2. conditional control statement

    • Meaning: It is a program control structure used to execute or skip blocks of code based on certain conditions

    • For example:

      breakcontinue
      
    • Note : Conditional control statements cannot be used in non-loop structures.

6.1 Overview

6.1.1 Definition

Java control statements are statements used to control the execution of program flow. They can change the execution order of the program based on conditions or loops. Control statements can help you implement different conditional logic and loop structures to achieve different tasks and functions.

6.1.2 Classification

Java control statements are divided into: process control statements , conditional control statements

6.1 Flow Control Statements

6.1.1 Overview

6.1.1.1 Definition

During the execution of a program, the execution order of each statement has a direct impact on the result of the program. Therefore, we must know the execution flow of each statement. Moreover, many times we need to control the execution order of statements to achieve the functions we want.

6.1.1.2 Classification

  • sequential structure

  • Judgment and selection structure (if, switch)

  • Loop structure (for, while, do...while)

6.1.1 Sequence structure

6.1.1.1 Definition

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

6.1.1.2 Execution Flowchart

1545615769372

6.1.2 Judgment structure – f statement

  • if statement format 1
格式:
if (关系表达式) {
    
    
    语句体;	
}

Implementation process:

① First calculate the value of the relational expression

②If the value of the relational expression is true, execute the statement body

③If the value of the relational expression is false, the statement body will not be executed.

④Continue to execute the following statement content

1545616039363

Example:

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("结束");
	}
}
  • f statement format 2
格式:
if (关系表达式) {
    
    
    语句体1;	
} else {
    
    
    语句体2;	
}

Implementation process:

① First calculate the value of the relational expression

②If the value of the relational expression is true, execute statement body 1

③If the value of the relational expression is false, execute statement body 2

④Continue to execute the following statement content

1545616221283

Example:

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("结束");
	}
}

if statement format 3

格式:
if (关系表达式1) {
    
    
    语句体1;	
} else if (关系表达式2) {
    
    
    语句体2;	
}else {
    
    
    语句体n+1;
}

Implementation process:

①First calculate the value of relational expression 1

②If the value is true, execute statement body 1; if the value is false, calculate the value of relational expression 2

③If the value is true, execute statement body 2; if the value is false, calculate the value of relational expression 3

④…

⑤If no relational expression is true, execute statement body n+1.

1545616667104

6.1.3 Selection structure – switch statement

Format

switch (表达式) {
    
    
	case 1:
		语句体1;
		break;
	case 2:
		语句体2;
		break;
	...
	default:
		语句体n+1;
		break;
}

Implementation process:

  • First calculate the value of the expression

  • Secondly, it is compared with the case in sequence. Once there is a corresponding value, the corresponding statement will be executed. During the execution process, it will end when a break is encountered.

  • Finally, if all cases do not match the value of the expression, the default statement body will be executed, and the program will end.

  • The position and omission of default

    default can be placed anywhere or omitted

  • case penetration

    Not writing break will cause case penetration phenomenon

  • New features of switch in JDK12

int number = 10;
switch (number) {
    
    
    case 1 -> System.out.println("一");
    case 2 -> System.out.println("二");
    case 3 -> System.out.println("三");
    default -> System.out.println("其他");
}
  • The respective usage scenarios of the third format of switch and if

When we need to judge a range, use the third format of if

When we enumerate a limited number of data and select one of them to execute, use the switch statement

for example:

​ For Xiao Ming's test results, if you use switch, you need to write 100 cases, which is too troublesome, so it is simple to use if.

​ If it is the day of the week, the month, the function selection of 0~9 in the customer service call can use the switch

6.1.4 Loop structure

6.1.4.1for loop structure (master)

​ A loop statement can repeatedly execute a certain piece of code when the loop condition is met. This piece of code that is repeatedly executed is called a loop body statement. When the loop body is repeatedly executed, the loop judgment condition needs to be modified at an appropriate time If it is false, the loop will end, otherwise the loop will continue to execute, forming an infinite loop.

for loop format:

for (初始化语句;条件判断语句;条件控制语句) {
    
    
	循环体语句;
}

Format explanation:

  • Initialization statement: used to indicate the initial state when the loop is started. Simply put, it is what it looks like when the loop starts.
  • Conditional judgment statement: used to express the conditions for repeated execution of the loop. Simply put, it is to judge whether the loop can continue to execute.
  • Loop body statement: used to express the content of repeated execution of the loop. Simply put, it is what the loop repeatedly executes.
  • Conditional control statement: used to express the content of each change in the execution of the loop. Simply put, it controls whether the loop can be executed.

Implementation 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 execution

③ Execute the loop body statement

④Execute conditional control statements

⑤Return to ②Continue

For loop writing skills:

  • Determine the starting condition of the loop
  • Determine the end condition of the loop
  • Determine the code to be executed repeatedly by the loop

Code example:

//1.确定循环的开始条件
//2.确定循环的结束条件
//3.确定要重复执行的代码

//需求:打印5次HelloWorld
//开始条件:1
//结束条件:5
//重复代码:打印语句

for (int i = 1; i <= 5; i++) {
    
    
    System.out.println("HelloWorld");
}

6.1.4.2while loop

Format:

初始化语句;
while(条件判断语句){
    
    
	循环体;
	条件控制语句;
}

6.1.4.3do…while loop

Just understand this knowledge point

Format:

初始化语句;
do{
    
    
    循环体;
    条件控制语句;
}while(条件判断语句);

Features:

​Execute first, judge later.

6.1.4.4 Differences between the three formats

​For and while loops are judged first and then executed.

​ do...while is executed first and then judged.

​ Use a for loop when you know the number of loops or the loop range.

​ When you don’t know the number of loops or the scope of the loop, but you know the end condition of the loop, use a while loop.

6.1.4.4 Infinite loop

concept:

​ Also called an infinite loop. The cycle never stops.

for format:

for(;;){
    
    
    System.out.println("循环执行一直在打印内容");
}

explain:

The initialization statement can be left blank, indicating that no control variables are defined before the loop.

The conditional judgment statement can be left blank. If not written, it will default to true and the loop will continue.

The conditional control statement can be left blank, which means that the control variable will not change after each loop body is executed.

while format:

while(true){
    
    
    System.out.println("循环执行一直在打印内容");
}

explain:

​ The parentheses cannot be omitted, and true must be written, otherwise the code will report an error.

do…while format:

do{
    
    
    System.out.println("循环执行一直在打印内容");
}while(true);

explain:

​ The parentheses cannot be omitted, and true must be written, otherwise the code will report an error.

Notes on infinite loops:

  • The most commonly used format: while
  • No other code can be written under the infinite loop because it will never be executed.

6.2 Conditional control statements

  • break
  • continue

6.2.1break

​ Cannot exist alone. It can be used in switch and loop to indicate the end and jump out.

Code example:

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

6.2.2continue

​ Cannot exist alone. Can only exist in the cycle.

​ means: skip this cycle and continue to execute the next cycle.

Code example:

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

Random, like Scanner, is also a class written in advance in Java. We don't need to care about how to implement it, just use it directly.

7.Array

Summary of notes:

  1. Definition: An array refers to a container that can store multiple values ​​of the same data type at the same time.

  2. Defined by:

    • Format one:

      数据类型 [] 数组名;
      //例如
      int [] array;
      
    • Format two:

      数据类型  数组名 [];
      //例如
      int array [];
      
    • Note: Different data types correspond to different default values

      • Integer type: 0
      • Decimal type: 0.0
      • Boolean type: false
      • Character type: '\u0000'
      • ReferenceType: null
  3. Static array initialization:

    • Format one:

      数据类型[] 数组名 = new 数据类型[]{
               
               元素1,元素2,元素3,元素4...};
      //例如
      double[] arr = new double[]{
               
               1.1,1.2,1.3};
      
    • Format two:

      数据类型[] 数组名 = {
               
               元素1,元素2,元素3,元素4...};
      //例如
      int[] array = {
               
               1,2,3,4,5};
      
  4. Dynamic array initialization:

    • Format:

      数据类型[] 数组名 = new 数据类型[数组的长度];
      //例如
      double[] arr = new double[10];
      
  5. The difference between dynamic initialization of arrays and static initialization of arrays:

    1. Grammar is different
    2. Array lengths are different
    3. The timing of assignment is different
    4. Note: No matter what kind of array it is, the maximum length of the array is the length of the array -1. For example: arr.length - 1
  6. Address value:

    • Meaning: The address value of the array is a pointer or reference to the array object

    • For example:

      int[] arr = {
               
               1,2,3,4,5};
      System.out.println(arr);	//[I@6d03e736
      /*
      [ :表示现在打印的是一个数组。
      I:表示现在打印的数组是int类型的。
      @:仅仅是一个间隔符号而已。
      6d03e736:就是数组在内存中真正的地址值。(十六进制的)
      */
      
  7. index:

    • Meaning: Used to identify its position in the array

    • For example:

      arr[0]、arr[1]、……
      
    • Features:

      1. Starting value is 0
      2. Continuously
      3. Increase by +1 one by one.
  8. Array element access

    • Meaning: Access values ​​in an array based on index
    • Format: array name [index];
  9. Traverse

    • Meaning: Take out the elements in the tuple in sequence

    • Format:

      for(int i = 0; i < arr.length; i++){
               
               
          //在循环的过程中,i依次表示数组中的每一个索引
          sout(arr[i]);//就可以把数组里面的每一个元素都获取出来,并打印在控制台上了。
      }
      

      Description: arr.length means getting the length of the array

7.1 Overview

7.1.1 Definition

In Java, an array refers to a container that can store multiple values ​​of the same data type at the same time. However, when the array container stores data, it needs to be considered in conjunction with implicit conversion.

NOTE: Implicit conversions in arrays

  • ​ Defines an array of type int. So boolean. Double type data cannot be stored in this array, but byte type, short type, and int type data can be stored in this array.

7.1.2 Recommendations

​ The class of the container is consistent with the type of data stored.

illustrate:

  • The integers 1 2 3 4 56 can be stored using an array of type int.
  • Decimals 1.1 1.2 1.3 1.4 can be stored using double type arrays.
  • The strings "aaa" "bbb" "ccc" can be stored using an array of String type.

7.2 Array definition

7.2.1 Format 1

数据类型 [] 数组名
# 例如
int [] array

7.2.2 Format 2

数据类型  数组名 []
# 例如
int array []

detail:

  • Data type: Limits what type of data the array can store in the future.
    • Default initialization values ​​for arrays:
      1. Integer type: 0
      2. Decimal type: 0.0
      3. Boolean type: false
      4. Character type: '\u0000'
      5. ReferenceType: null
  • Square brackets: Indicates that an array is being defined.
  • Array name: It’s just a name for future use.

Notice:

​ Method brackets and array names, whoever writes in front and who writes in the back are the same

7.3 Static initialization of arrays

/* 完整格式:
数据类型[] 数组名 = new 数据类型[]{元素1,元素2,元素3,元素4...}; */
int[] arr = new int[]{
    
    11,22,33};
double[] arr = new double[]{
    
    1.1,1.2,1.3};
/* 简化格式:
数据类型[] 数组名 = {元素1,元素2,元素3,元素4...}; */
int[] array = {
    
    1,2,3,4,5};
double[] array = {
    
    1.1,1.2,1.3};

detail:

  • Data type: what type of data can be stored after the array is limited
  • Square brackets: indicates that what is defined is an array
  • Array name: In fact, it is just a name, which is convenient for future use. When naming, follow the small hump nomenclature
  • new: It opens up a space in memory for the array.
  • Braces: represent the elements in the array. The elements are the data stored in the array. Multiple elements must be separated by commas

Notice:

  • The data types in front and behind must be consistent
  • Once the array is created, the length cannot change

7.4 Dynamic initialization of arrays

/* 格式:
数据类型[] 数组名 = new 数据类型[数组的长度]; */
int[] agesArr = new int[3];
int[] scoresArr = new int[10];

7.5 Address value

int[] arr = {
    
    1,2,3,4,5};
System.out.println(arr);//[I@6d03e736

double[] arr2 = {
    
    1.1,2.2,3.3};
System.out.println(arr2);//[D@568db2f2

detail:

  • When printing an array, what actually appears is the address value of the array. The address value of the array: represents the location of the array in memory.

  • Address details

    /*
    以[I@6d03e736为例:
    [ :表示现在打印的是一个数组。
    I:表示现在打印的数组是int类型的。
    @:仅仅是一个间隔符号而已。
    6d03e736:就是数组在内存中真正的地址值。(十六进制的)
    但是,我们习惯性会把[I@6d03e736这个整体称之为数组的地址值
    */
    

7.6 Index

7.6.1 Definition

​ 在Java中,索引也叫角标、下标。换句话说,就是数组容器中每一个小格子对应的编号。

7.6.2特点

  • 索引一定是从0开始的。
  • 连续不间断。
  • 逐个+1增长。

7.7数组元素访问

7.7.1作用

  • 获取数组中对应索引上的值

  • 修改数组中对应索引上的值,一旦修改之后,原来的值就会被覆盖

7.7.2基本用例-数组访问演示

public class ArrDemo2 {
    
    
    /*

        数组中元素访问的格式:
                数组名[索引];

         作用:
            1.获取指定索引上对应的元素
            2.修改指定索引上对应的元素


    */
    public static void main(String[] args) {
    
    
       int[] arr = {
    
    1,2,3,4,5};
       //需求1:获取arr数组中,3索引上的值
        int number = arr[3];
        System.out.println(number);
        System.out.println(arr[3]);

       //需求2:将arr数组中,3索引上的值修改为10
            arr[3] = 10;
        System.out.println("修改之后为:" + arr[3]);

    }
}

7.8数组的遍历

7.8.1遍历

​ 就是把数组里面所有的内容一个一个全部取出来。

7.8.2基本用例-数组遍历演示

/* 格式:
数组名.length */
for(int i = 0; i < arr.length; i++){
    
    
    //在循环的过程中,i依次表示数组中的每一个索引
    sout(arr[i]);//就可以把数组里面的每一个元素都获取出来,并打印在控制台上了。
}

7.9数组两种初始化方式的区别

7.9.1静态初始化

int[] arr = {
    
    1,2,3,4,5};

说明:

​ 手动指定数组的元素,系统会根据元素的个数,计算出数组的长度。

7.9.2动态初始化

int[] arr = new int[3];

说明:

​ 手动指定数组长度,由系统给出默认初始化值。

7.9.3应用场景

  • 只明确元素个数,但是不明确具体的数据,推荐使用动态初始化。

说明:

// 使用数组来存储键盘录入的5个整数。
int[] arr = new int[5];
  • 已经明确了要操作的所有数据,推荐使用静态初始化。

说明:

// 将全班的学生成绩存入数组中,已知学生成绩为:66,77,88,99,100
int[] arr = {
     
     66,77,88,99,100}

7.9.4数组常见问题

索引越界

public class ArrDemo6 {
    
    
    public static void main(String[] args) {
    
    
       int[] arr = {
    
    1,2,3,4,5,5,5,5,5};
        //用索引来访问数组中的元素
        System.out.println(arr[1]);
        System.out.println(arr[10]);//ArrayIndexOutOfBoundsException

    }
}

说明:针对于任意一个数组,索引的范围

  1. 最小索引:0
  2. 最大索引:
    • 数组的长度 - 1
    • 数组名.length - 1

8.代码块

笔记小结:

  1. 局部代码块:略

  2. 构造代码块:略

  3. 静态代码块(重点)

    • 含义:被static修饰的代码块

    • 基本用例:

      /*格式:
      static{},需要通过static关键字修饰 */
      static{
               
               
      
      }
      // 当类加载时,此代码块就会被加载
      
    • 特点:随着类的加载而加载,并且自动出发,只执行一次

8.1局部代码块

public class CodeBlockLearn {
    
    
    public static void main(String[] args) {
    
    
        {
    
    
            int a=10;
            System.out.println(a);
        }
    }
}

说明:

  • 应用场景:那么当超出了方括号,变量a也就不存在了,有着提前释放变量的作用

8.2构造代码块

  • 卸载成员位置的代码块,可以把多个构造方法中重复的代码抽取出来
  • 执行时机:我们在创建本类对象的时候会先执行构造代码块再执行构造方法

说明:

​ 构造代码块优先于构造方法而执行的

8.3静态代码块(重点)

/*格式:
static{},需要通过static关键字修饰 */
public class MyClass {
    
    
    static {
    
    
        System.out.println("静态代码块执行了");
    }
 
    public static void main(String[] args) {
    
    
        System.out.println("主方法执行了");
    }
}

说明:

  • 执行时机:随着类的加载而加载,并且自动出发,只执行一次
  • 使用场景:在类加载时,做一些初始化的操作

9.关键字

笔记小结:见各模块

9.1this关键字

笔记小结:

  • 定义:当我们在一个类中使用 this 时,它指的是该类的当前对象

  • 基础用例:

     public class Person {
           
           
        private String name;
        private int age;
    
        public Person(String name, int age) {
           
           
                      this.name = name; //使用this关键字引用当前对象的成员变量name
            this.age = age; //使用this关键字引用当前对象的成员变量age
        }
    }
    

Definition: In Java, this is a keyword that represents the current object. It can be used to access properties and methods of the current object.

Basic use case

public class Person {
    
    
    private String name;
    private int age;

    public Person(String name, int age) {
    
    
        this.name = name; //使用this关键字引用当前对象的成员变量name
        this.age = age; //使用this关键字引用当前对象的成员变量age
    }
}

illustrate:

​When we use within a class this, it refers to the current object of that class.

9.2static keyword

Summary of notes:

  • Definition: static is a keyword used to modify member variables, member methods, and code blocks of a class. Its function is to associate these member variables, member methods, and code blocks with the class itself, rather than with the instance object of the class

  • Static variables and their access

    1. Meaning: static modifies member variables of a class

    2. definition:

      /* 格式:
      	修饰符 static 数据类型 变量名 = 初始值;*/
      public static String schoolName = "传智播客"
    3. access:

      /* 格式:
      	类名.静态变量 */
      System.out.println(Student.schoolName); // 传智播客
      
  • Instance variables and their access

    1. Meaning: Member variables of classes without static modification

    2. definition:

      /* 格式:
      	修饰符 数据类型 变量名 = 初始值;  */
      public String schoolName = "传智播客"
    3. access:

      /* 格式:
      	对象.方法名 */
      Student stu = new Student();
      System.out.println(stu.schoolName);
      
    4. Notice:

      • Instance variables belong to each object and must be created to access the class object .
      • Static variables do not belong to member objects , they belong to classes. The static variable is loaded as the class is loaded and takes precedence over the existence of the object.
  • Static methods and their access

    1. Meaning: member method of static modified class

    2. definition:

      /* 格式:
      	修饰符 static 类型 方法名() */
      public static void study(){
               
                // 类方法或者静态方法。
          System.out.println("我们都在黑马程序员学习");   
      }
      
    3. Access: through class name. method name ()

      /* 格式:
      	类名.方法名() */
      Student.study();
      
    4. Note: Instance methods belong to each object and must be created to access the class object .

  • Instance methods and their access

    1. Meaning: Member methods of non-static modified classes

    2. definition:

      /* 格式:
      	修饰符 类型 方法名()*/
      public void study(){
               
                // 类方法或者静态方法。
          System.out.println("我们都在黑马程序员学习");   
      }
      
    3. Access: requires new object

      /* 格式:
      	对象.方法名 */
      Student stu = new Student();
      System.out.println(stu.study());
      
  • Memory map :

    1. When the static keyword is used, a memory space called " static storage location " will be opened in the heap memory.
    2. Static methods cannot access non-static resources
    3. Static methods cannot call instance variables
    4. Non-static resources can access all
    5. Note that the lifetime of static members is as long as the lifetime of the class

9.2.1 Overview

Static is a keyword used to modify the member variables, member methods and code blocks of a class. Its function is to associate these member variables, member methods and code blocks with the class itself, rather than with the instance object of the class.

9.2.1 Static variables and their access

9.2.1.1 Overview

​ There is a static modified member variable, indicating that the member variable belongs to the class. This member variable is called a class variable or a static member variable . Just use the class name to access it directly. Because there is only one class, there is only one copy of static member variables in the memory area. All objects can share this variable.

9.2.1.2 Basic use case - static keyword usage

/* 格式:
	修饰符 static 数据类型 变量名 = 初始值;*/    
public class Student {
    
    
    public static String schoolName = "传智播客"// 类变量或者静态成员变量
    // .....
}

9.2.1.3 Access

/*格式:
	类名.静态变量	*/
public static void  main(String[] args){
    
    
    System.out.println(Student.schoolName); // 传智播客
    Student.schoolName = "黑马程序员";
    System.out.println(Student.schoolName); // 黑马程序员
}

9.2.2 Instance variables and their access

9.2.2.1 Overview

​ Member variables without static modification belong to each object. This member variable is called an instance variable . Before we wrote member variables, they are instance member variables.

9.2.2.2 Basic use case-instance variable usage

public class Student {
    
    
    public  String schoolName = "传智播客"// 成员变量
    // .....
}

9.2.2.3 Access

/* 格式:
	对象.实例成员变量 */
public static void main(String[] args) {
    
    
    Student stu = new Student();
    System.out.println(stu.schoolName);
}

detail:

​ Instance member variables belong to each object, and objects of the class must be created before they can be accessed.

9.2.3 Static methods and their access

9.2.3.1 Overview

​ There is a static modified member method, indicating that this member method belongs to the class. This member method is called a class method or static method. You can access it directly using the class name. Because there is only one class, there is only one copy of the static method in the memory area. All objects can share this method.

​ Like static member variables, static methods can also be accessed directly through the class name and method name .

9.2.3.2 Basic Use Cases

public class Student{
    
    
    public static String schoolName = "传智播客"// .....
        public static void study(){
    
     // 类方法或者静态方法。
        System.out.println("我们都在黑马程序员学习");   
    }
}

9.2.3.2 Access

/* 格式:
	类名.静态方法*/
public static void  main(String[] args){
    
    
    Student.study();
}

9.2.4 Instance methods and their access

9.2.4.1 Overview

Member methods without static modification belong to each object. This member method is also called an instance method .

detail

​Instance methods belong to each object and must be created to access the class object.

9.2.4.2 Basic use cases - instance method usage

/*格式:
	对象.实例方法*/
public class Student {
    
    
    // 实例变量
    private String name ;
    // 2.方法:行为
    // 无 static修饰,实例方法。属于每个对象,必须创建对象调用
    public void run(){
    
    
        System.out.println("学生可以跑步");
    }
	// 无 static修饰,实例方法
    public  void sleep(){
    
    
        System.out.println("学生睡觉");
    }
    public static void study(){
    
    
        
    }
}

9.2.4.3 Access

public static void main(String[] args){
    
    
    // 创建对象 
    Student stu = new Student ;
    stu.name = "徐干";
    // Student.sleep();// 报错,必须用对象访问。
    stu.sleep();
    stu.run();
}

summary

1. When statica member variable or member method is modified, the variable is called a static variable and the method is called a static method . Every object of this class shares static variables and static methods of the same class. Any object can change the value of this static variable or access the static method. But this method of access is not recommended. Because static variables or static methods can be accessed directly through the class name, there is no need to use objects to access them.

2. Member variables or member methods without static modification are called instance variables, instance methods , instance variables and instance methods must create an object of the class and then access it through the object.

3. The members modified by static belong to the class and will be stored in the static area. They are loaded as the class is loaded and are only loaded once, so there is only one copy, saving memory. It is stored in a fixed memory area (static area), so it can be called directly by the class name. It exists before the object, so it can be shared by all objects.

4. Members without static modification belong to objects. There will be as many copies of them as there are objects. So must be called by the object.

9.2.5Static memory map (key)

static method

image-20230303143249383

illustrate:

If you want a member variable in the class to be shared, you can make it static and modify it. This is the execution process in static memory.

Replenish:

After the method is pushed onto the stack, it will exit

Note: Static methods cannot access non-static methods

image-20230303151408269

illustrate:

  1. If name is non-static, it will not appear in the static storage location in the heap memory, so static methods cannot access non-static
  2. There are currently no instantiated objects in the heap memory, so static methods cannot call instance variables.

Replenish:

When the Student of the Student.teacherName method is read in the main method, the Student.class bytecode file will be loaded into the method area.

image-20230303151626162

illustrate:

If the show method can be called in the method method, then in the stack memory, this? ? ? Who will call the .show method? Normally, it should be called by an object, so static methods cannot access non-static

Replenish:

The life cycle of static members is as long as the life cycle of the class. That is to say, when the class is loaded, the static members are allocated memory; when the class is unloaded, the memory occupied by the static members is also released.

9.2.6Static modifies member variables and member methods

image-20230303143546266

9.2.7 Commonly used Static tools

A class that helps us do something, but does not describe anything

1. Some students didn’t understand. Let me explain it here. The last lesson mentioned that static variables are created before classes.

2. It means that I load the static variables first and then create the class. I follow this step.

3. Then, if this class only has methods, that is, tool classes, I don’t need to create this class.

4. Because I can call methods directly before this class, and only static methods can be created first

9.2.8 Disadvantages of Static

  1. The life cycle of static variables is too long: Static variables exist throughout the running of the program, which may occupy a large amount of memory space and affect the performance of the program.
  2. Concurrent access problems of static variables: Concurrent access problems may occur when multiple threads access static variables at the same time , resulting in data inconsistency or other errors.
  3. Static methods cannot be overridden by subclasses: Since static methods belong to classes, not objects, they cannot be overridden by subclasses, which limits the flexibility of the program.
  4. Static methods need to create objects when calling non-static methods or variables: Since static methods belong to classes and cannot directly access non-static methods or variables , they need to create objects to access them.
  5. Static code blocks cannot handle exceptions: Statements in static code blocks cannot handle exceptions and can only be handled by throwing exceptions.

static Static method execution – memory analysis_static method exists when running_qingdao_java's blog-CSDN blog

9.3 final keyword

Summary of notes:

  • Definition: finalIt is a keyword that can be used to modify variables, methods and classes to indicate immutable and final state .

  • Modify variables:

    1. Local variable: means that its value cannot be changed, that is, the variable is a constant. Variable values ​​cannot be modified

         final int a;
         a = 10;
      
    2. Member variable: means that its value cannot be changed, that is, the variable is a constant. Variables can only be assigned immediately when defining member variables.

       final int num = 10;
      
    3. Variables are clearly standardized: single words are all capitalized , and multiple words are separated by underscores.

  • Modified method: Indicates that the method cannot be overridden (overridden) by subclasses

    final public void show1() {
           
           
    		System.out.println("Fu2 show1");
    	}
    
  • Modified class: Indicates that the class is called a final class (or non-extensible class) because it cannot be inherited by other classes .

    final class Fu {
           
           
    }
    
  • detail:

    1. The variable modified by final is a basic type : then the data value stored in the variable cannot be changed.
    2. The variable modified by final is a reference type : then the address value stored in the variable cannot be changed , but the content of the object it points to can be modified.

9.3.1 Overview

finalIs a keyword that can be used to modify variables, methods and classes to indicate immutable and final state.

  1. Modify variables:
    • finalModified variables represent constants. Once assigned a value, they cannot be changed .
    • finalDeclared variables must be initialized at declaration time or in the constructor, otherwise the compiler will report an error.
    • When declaring finalvariables, generally use all uppercase letters and underscores.
  2. Modification method:
    • finalA modified method means that the method cannot overridden or overridden by subclasses .
    • When a class is declared as final, all methods in it automatically become final, but instance variables are not affected.
  3. Modification class:
    • finalModified class means that the class cannot be inherited .
    • Using finalmodified classes can ensure that the behavior of the class will not be changed, and can also improve the safety and reliability of the code.

9.3.2 Decorating variables

9.3.2.1 Local variables (emphasis)

public class FinalDemo1 {
    
    
    public static void main(String[] args) {
    
    
        // 声明变量,使用final修饰
        final int a;
        // 第一次赋值 
        a = 10;
        // 第二次赋值
        a = 20; // 报错,不可重新赋值

        // 声明变量,直接赋值,使用final修饰
        final int b = 10;
        // 第二次赋值
        b = 20; // 报错,不可重新赋值
    }
}

illustrate:

​ Local variables of basic types, after being modified by final, can only be assigned once and cannot be changed again.

9.3.2.2 Member variables (emphasis)

Member variables involve initialization. The initialization methods include display initialization and constructor initialization. Only one of them can be selected:

  • Display initialization (immediately assign values ​​when defining member variables) (commonly used);
public class Student {
    
    
    final int num = 10;
}
  • Construction method initialization (assign a value once in the construction method) (not commonly used, just understand).

    Note: A value must be assigned once in each constructor!

public class Student {
    
    
    final int num = 10;
    final int num2;

    public Student() {
    
    
        this.num2 = 20;
//     this.num2 = 20;
    }
    
     public Student(String name) {
    
    
        this.num2 = 20;
//     this.num2 = 20;
    }
}

illustrate:

​ Constant names modified by final generally have writing standards, and all letters are capitalized .

9.3.3 Modification method

9.3.3.1 Overview

Final modified methods cannot be overridden

9.3.3.2 Basic use case-modification method demonstration

/* 格式:
修饰符 final 返回值类型 方法名(参数列表){
    //方法体
} */
class Fu2 {
    
    
	final public void show1() {
    
    
		System.out.println("Fu2 show1");
	}
	public void show2() {
    
    
		System.out.println("Fu2 show2");
	}
}

class Zi2 extends Fu2 {
    
    
//	@Override
//	public void show1() {
    
    
//		System.out.println("Zi2 show1");
//	}
	@Override
	public void show2() {
    
    
		System.out.println("Zi2 show2");
	}
}

9.3.4 Modifier classes

9.3.4.1 Overview

Classes modified by final cannot be inherited

9.3.4.2 Basic use cases - use of modified classes

/* 格式:
	final class 类名 {
	} 	*/
final class Fu {
    
    
}
// class Zi extends Fu {} // 报错,不能继承final的类

illustrate:

​ Querying the API found that many of the classes we have studied, such as public final class String, public final class Math, etc., are modified by final, and the purpose is for us to use without allowing us to change its content.public final class Scanner

9.4private keyword

Summary of notes:

  1. Overview: Decorators for modifying member variables and methods of classes
  2. Function: prevent external programs from illegally accessing and operating object data

9.4.1 Overview

​ private is a modifier that can be used to modify members (member variables, member methods)

illustrate:

​ Members modified by private can only be accessed in this class. For member variables modified by private, if they need to be used by other classes, provide corresponding operations

detail:

  • Provide the "get variable name()" method to obtain the value of the member variable. The method is decorated with public
  • Provides the "set variable name (parameter)" method for setting the value of member variables. The method is modified with public

9.4.2 Basic use cases - private keyword usage

/*
    学生类
 */
class Student {
    
    
    //成员变量
    String name;
    private int age;

    //提供get/set方法
    public void setAge(int a) {
    
    
        if(a<0 || a>120) {
    
    
            System.out.println("你给的年龄有误");
        } else {
    
    
            age = a;
        }
    }

    public int getAge() {
    
    
        return age;
    }

    //成员方法
    public void show() {
    
    
        System.out.println(name + "," + age);
    }
}
/*
    学生测试类
 */
public class StudentDemo {
    
    
    public static void main(String[] args) {
    
    
        //创建对象
        Student s = new Student();
        //给成员变量赋值
        s.name = "林青霞";
        s.setAge(30);
        //调用show方法
        s.show();
    }
}

9.4.3 Case-Use of private

  • Requirements: Define a standard student class, require name and age to be modified with private, and provide set and get methods as well as a show method to facilitate displaying data. Create objects in the test class and use them. Finally, the console outputs Brigitte Lin, 30

  • Sample code:

    /*
        学生类
     */
    class Student {
          
          
        //成员变量
        private String name;
        private int age;
    
        //get/set方法
        public void setName(String n) {
          
          
            name = n;
        }
    
        public String getName() {
          
          
            return name;
        }
    
        public void setAge(int a) {
          
          
            age = a;
        }
    
        public int getAge() {
          
          
            return age;
        }
    
        public void show() {
          
          
            System.out.println(name + "," + age);
        }
    }
    /*
        学生测试类
     */
    public class StudentDemo {
          
          
        public static void main(String[] args) {
          
          
            //创建对象
            Student s = new Student();
    
            //使用set方法给成员变量赋值
            s.setName("林青霞");
            s.setAge(30);
    
            s.show();
            //使用get方法获取成员变量的值
            System.out.println(s.getName() + "---" + s.getAge());
            System.out.println(s.getName() + "," + s.getAge());
    
        }
    }
    

9.5this keyword

Summary of notes:

  1. Meaning: The essence of this is the address value of the method caller
  2. Memory map:
    • If the formal parameter of the method has the same name as the member variable, the variable without this modification refers to the formal parameter, not the member variable
    • The formal parameter of the method does not have the same name as the member variable, and the variable without this modification refers to the member variable

This keyword memory principle (key points)

image-20230228093820021

image-20230228094218260

illustrate:

After the method is executed, the stack will be popped

To sum up one sentence: the essence of this is the address value of the method caller

Variables modified by this are used to refer to member variables, and their main function is to distinguish the problem of duplicate names of local variables and member variables.

  • If the formal parameter of a method has the same name as a member variable, the variable without this modification refers to the formal parameter, and the variable with this modification is the member variable.
  • The formal parameter of the method does not have the same name as the member variable. The variable without this modification refers to the member variable.
public class Student {
    
    
    private String name;
    private int age;

    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getName() {
    
    
        return name;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    public int getAge() {
    
    
        return age;
    }

    public void show() {
    
    
        System.out.println(name + "," + age);
    }
}

9.6super keyword

Summary of notes:

  1. Meaning: Represents a reference to the parent class object , which can be used to call the constructor method , instance method and instance variable of the parent class

  2. Usage format:

    this.成员变量    	--    本类的
    super.成员变量    	--    父类的
    
    this.成员方法名()  	--    本类的    
    super.成员方法名()   --    父类的
    
    super(...) -- 调用父类的构造方法,根据参数匹配确认
    this(...) -- 调用本类的其他构造方法,根据参数匹配确认
    
  3. Super usage example:

    • Both super() and this() must be in the first line of the constructor, so they cannot appear at the same time.
    • super(...) is based on parameters to determine which constructor to call the parent class
  4. Memory map:

    image-20230813112237941

  5. detail:

    • There is a default super( ) in each construction method of the subclass, which calls the empty parameter construction of the parent class. Manually calling the parent class constructor overrides the default super( )

    • Both super() and this() must be in the first line of the construction method, so they cannot appear at the same time

    • super() and this() determine which constructor of the parent class to call based on the parameters.

    • super() can call the parent class constructor to initialize the data of member variables inherited from the parent class.

    • this( ) can call other constructors in this class

9.6.1 Overview

​ In Java, the super keyword represents the reference of the parent class object, which can be used to call the parent class's constructor, instance method and instance variable

class Person {
    
    
    private String name;
    private int age;

    public Person() {
    
    
        System.out.println("父类无参");
    }

    // getter/setter省略
}

class Student extends Person {
    
    
    private double score;

    public Student() {
    
    
        //super(); // 调用父类无参构造方法,默认就存在,可以不写,必须再第一行
        System.out.println("子类无参");
    }
    
     public Student(double score) {
    
    
        //super();  // 调用父类无参构造方法,默认就存在,可以不写,必须再第一行
        this.score = score;    
        System.out.println("子类有参");
     }
      // getter/setter省略
}

public class Demo07 {
    
    
    public static void main(String[] args) {
    
    
        // 调用子类有参数构造方法
        Student s2 = new Student(99.9);
        System.out.println(s2.getScore()); // 99.9
        System.out.println(s2.getName()); // 输出 null
        System.out.println(s2.getAge()); // 输出 0
    }
}

illustrate:

​ We found that the subclass has a parameter construction method that only initializes the member variable score in its own object, while the member variables name and age in the parent class still have no data. How to solve this problem? We can use super(… ) to call the parent class constructor to initialize the name and age inherited from the parent class object

9.6.3 Basic use cases - use of super keyword

/* 格式:
    super.成员变量    	--    父类的
    super.成员方法名()   --    父类的 */
class Person {
    
    
    private String name ="凤姐";
    private int age = 20;

    public Person() {
    
    
        System.out.println("父类无参");
    }
    
    public Person(String name , int age){
    
    
        this.name = name ;
        this.age = age ;
    }

    // getter/setter省略
}

class Student extends Person {
    
    
    private double score = 100;

    public Student() {
    
    
        //super(); // 调用父类无参构造方法,默认就存在,可以不写,必须再第一行
        System.out.println("子类无参");
    }
    
     public Student(String name , int age,double score) {
    
    
        super(name ,age);// 调用父类有参构造方法Person(String name , int age)初始化name和age
        this.score = score;    
        System.out.println("子类有参");
     }
      // getter/setter省略
}

public class Demo07 {
    
    
    public static void main(String[] args) {
    
    
        // 调用子类有参数构造方法
        Student s2 = new Student("张三"2099);
        System.out.println(s2.getScore()); // 99
        System.out.println(s2.getName()); // 输出 张三
        System.out.println(s2.getAge()); // 输出 20
    }
}

Notice:

  • There is a default super() in each constructor method of the subclass, which calls the empty parameter constructor of the parent class. Manually calling the parent class constructor will override the default super().

  • Both super() and this() must be in the first line of the constructor, so they cannot appear at the same time .

  • super(...) determines which constructor of the parent class to call based on the parameters.

9.6.4 Memory map

The parent class space takes precedence over subclass objects.

​ Every time a subclass object is created, the parent class space is initialized first, and then the subclass object itself is created. The purpose is that if the subclass object contains its corresponding parent class space, it can contain the members of its parent class. If the parent class members are not privately modified, the subclass can use the parent class members at will. The code is reflected in the fact that when the constructor of a subclass is called, the constructor of the parent class must be called first. Understanding the diagram is as follows:

image-20230813112250239

9.6.5Basic use cases of this()

this(…)

  • The default is to find other constructors in this class, and determine which constructor to call based on the parameters .
  • In order to borrow the functionality of other constructors.
/* 格式:
	this.成员变量    	--    本类的
	this.成员方法名()  	--    本类的    */
package com.itheima._08this和super调用构造方法;
/**
 * this(...):
 *    默认是去找本类中的其他构造方法,根据参数来确定具体调用哪一个构造方法。
 *    为了借用其他构造方法的功能。
 */
public class ThisDemo01 {
    
    
    public static void main(String[] args) {
    
    
        Student xuGan = new Student();
        System.out.println(xuGan.getName()); // 输出:徐干
        System.out.println(xuGan.getAge());// 输出:21
        System.out.println(xuGan.getSex());// 输出: 男
    }
}

class Student{
    
    
    private String name ;
    private int age ;
    private char sex ;

    public Student() {
    
    
  // 很弱,我的兄弟很牛逼啊,我可以调用其他构造方法:Student(String name, int age, char sex)
        this("徐干",21,'男');
    }

    public Student(String name, int age, char sex) {
    
    
        this.name = name ;
        this.age = age   ;
        this.sex = sex   ;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    public char getSex() {
    
    
        return sex;
    }

    public void setSex(char sex) {
    
    
        this.sex = sex;
    }
}

illustrate:

This memory map has been explained in detail in this keyword

Knowledge refueling chapter

1.Java memory model

In Java, HelloWorldthe memory map of executing a method

image-20230303093525909

illustrate:

Stack memory is used for methods , heap memory is used for objects , and the method area is used for temporary storage of executed class files.

Replenish:

  • Reference: https://www.bilibili.com/video/BV17F411T7Ao/?p=107
  • When the main method is executed, the StringDemo class file will be generated.

2.Idea shortcut keys

2.1 View the interface implementation class

illustrate:

Ctrl+Alt+B

Select a method and press Ctrl+Alt+B to view the implementation class that implements this interface.

image-20230321143750637

2.2 Small details of icons

Ctrl+F12 can view the status of the current class, such as member methods, member properties, etc.

image-20230424201934606

image-20230424202204121

C represents class, M represents method, F represents constant or static member variable , ➡️ represents inheritance, ⬆ represents overriding

3.The difference between int and Integer

In Java, intit is a primitive data type used to represent integer values. It is one of the most commonly used data types in Java, it has a size of 4 bytes (32 bits) and can represent integers between -2,147,483,648 and 2,147,483,647.

Integer​ It is It allows passing int values ​​as arguments to methods that expect an object, and also converting int values ​​to other types of values, such as strings.

Therefore, the main difference between intand Integeris intthat it is a primitive data type, Integerbut a class that encapsulates int values ​​for more operations. In addition, intin Java, it is a basic data type, Integerbut a reference data type, which means that Integerit is actually a pointer to an object rather than a simple data value.

4.The difference between String and Character

​IsString an object used to represent a character sequence (that is, a group of characters ). It is a class in Java that has many practical methods to manipulate and process strings, such as concatenation, replacement, search and split, etc. String constants can be enclosed in double quotes, for example "hello".

CharacterIt is a wrapper class for the char type in Java, which is used to represent a single character . Each Characterobject contains a value of type char. It also has some utility methods for manipulating and processing characters, such as converting characters to uppercase or lowercase. Character constants can be enclosed in single quotes, for example 'A'.

Therefore, the main difference between Stringand Characteris the data type they represent. StringUsed to represent a group of characters and Characterused to represent a single character. Also, Stringis a class, Characterbut a simple data type. In Java, a string is immutable, so it cannot be modified on the original string, Characterbut mutable, since it represents only one character.

5. The difference between basic data types and reference data types

Reference link: (29 messages) The difference between basic data types and reference data types_Brandon understands your blog-CSDN blog

Guess you like

Origin blog.csdn.net/D_boj/article/details/132192272