JAVA study notes—collection

Getting Started with JAVA

The birth of the Java empire

Java Features and Benefits

  • simplicity
  • Facing objects
  • portability
  • high performance
  • distributed
  • polymorphism
  • Multithreading
  • safety
  • Robustness

Three major versions of Java

  • Write Once,Run Anywhere

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

  • JavaME : Embedded development (mobile phones, small home appliances...), has become cold

  • JavaEE : Enterprise-level development (Web-side, server-side development...), based on JavaSE

JDK JRE JVM

  • JDK: Java Development Kit (Java developer tools, including JRE, JVM)
  • JRE: Java Runtime Environment (Java Runtime Environment)
  • JVM: Java Virtual Machine (Java virtual machine, cross-platform core)

Install development environment

Uninstall JDK

  1. Delete Java installation directory
  2. Delete the environment variable JAVA_HOME
  3. Delete the JAVA directory under path
  4. Java -version

Install JDK

  1. Search JDK8 on Baidu and find the download address
  2. Agree to the agreement and download the version corresponding to your computer, such as jdk-8u281-windows-x64.exe for a 64-bit operating system.
  3. Double-click to install JDK
  4. Remember the installation path
  5. Configure environment variables
    1. My Computer->Properties->Advanced System Settings->Environment Variables
    2. Create new system variable –> JAVA_HOME and enter the corresponding jdk installation path
    3. path variable–>% JAVA_HOME%\bin
  6. Test whether it is successful cmd–>Java -version

JAVA basics

Comment

  1. Single line comment //
  2. Multi-line comments /* */
  3. Documentation comments/** */

identifiers and keywords

  • All components of Java require names. Class names, variable names, and method names are all called identifiers

Notes on identifiers

  • All identifiers should start with a letter, $ (dollar sign), _ (underscore)
  • The first letter can be followed by any combination of letters, $, _ or numbers.
  • Keywords cannot be used as variable names or method names
  • Identifiers are case sensitive
  • It can be named in Chinese, but it is not recommended . Even if it is named in Pinyin, it is Low.

type of data

Strongly typed language

The use of variables is required to strictly comply with regulations. All variables must be defined before they can be used.
Weakly typed languages: JavaScript, Python

Java data types are divided into two categories

Primitive type (primitive type), there are 8 basic types, in addition they are all reference types Reference
type (reference type)

  • kind
  • interface
  • array
//整数
int num1 = 10; //最常用,只要别超过21亿(2^31-1)
byte num2 = 20; //-128~127
short num3 = 30;
long num4 = 30L; //long类型数字后面要加个L(尽量用大写,小写l容易与1搞混)
//小数:浮点数
float num5 = 50.1F; //float类型数字后面要加个F
double num6 = 3.141592653589793238;
//字符
char name = '国';
//字符串, String不是关键字,是类
//String namea = "薛之谦";
//布尔值:是非
boolean flag = true

What are bytes

  • Bit: is the smallest unit of internal data storage in a computer. 11001100 is an eight-digit binary number.
  • Byte (byte, B): It is the basic unit of data processing in computers. It is customary to express it with a capital B.
  • 1B(byte) = 8bit, 1 byte equals 8 bits
  • Characters: refers to the letters, numbers, words and symbols used in computers
  • 1bit means 1 bit
  • 1Byte represents one byte 1B=8b
  • 1024B = 1KB, 1024KB = 1M, 1024M = 1G

Extension and interview questions

//整数扩展: 二进制0b		八进制0		十进制		十六进制0x
int i = 10;
int i2 = 010; //八进制 8
int i3 = 0x10; //十六进制 16
int i4 = 0b100; //二进制 4
//浮点数扩展:
//面试题:银行业务字母怎么表示钱? BigDecimal(数学工具类)
//float double是有问题的,最好避免使用浮点数进行比较
float f = 0.1f; 	//0.1
double d = 1.0/10;  //0.1
System.out.println(f==d); //false
//浮点数 位有限,舍入误差,大约
//最好避免使用浮点数进行比较
float f1 = 23131313131f;
float f2 = f1+1;
System.out.println(f1==f2); //true
//字符扩展:所有字符本质还是数字
char c1 = 'a';
char c2 = '中';

System.out.println(c1);		//a
System.out.println((int)c1);//强制类型转换,97
System.out.println(c2);		//中
System.out.println((int)c2);//强制类型转换,20013

//编码 Unicode表(97=a,65=A)2字节 0-65536
//U000~UFFFF 十六进制(u0061=a,相当于十进制的97)
System.out.println('\u0061');  //a '\'是转义字符
// \t 制表符
// \n 换行 ···
//布尔值扩展
boolean flag = true;
if(flag==true){
    
    } //新手
if(flag){
    
    }	//老手这样写 Less is More(代码要精简易读)

type conversion

  • Since Java is a strongly typed language, type conversion is required when performing some operations.

  • Capacity high–>low:

    byte,short,cahr -> int -> long -> float -> double

    During the operation, data of different types are first converted into the same type and then the operation is performed.

    • Force conversion, (type) variable name, capacity from high to low
    • Automatic conversion, capacity from low to high
//强制转换 (类型)变量名 高--低
//自动转换 低--高
int i = 128;
byte b = (byte)i; //强制转换 内存溢出 -128~127
double d =i; //自动转换

System.out.println(i); //128
System.out.println(b); //-128
System.out.println(d); //128.0
/*
   注意点:
   1.不能对布尔值进行转换
   2.不能把对象类型转换为不相干的类型
   3.在把高容器转换到低容量的时候,强制转换
   4.可能存在内存溢出,或者精度问题
 * */
System.out.println((int)23.7); //23 丢失精度
char c = 'a';
int n = c+1;
System.out.println(n); //98
System.out.println((char)n); //b
//当操作数比较大时,注意溢出问题
//JDK7新特性,数字之间可以用下划线分割
int money = 10_0000_0000; //10亿,下划线不会被打印出来
System.out.println(money); //1000000000
int years = 20;

int total = money*years;  //数据大,溢出
System.out.println(total); //-1474836480

long total2 = money*years; //默认是int,转换前就有溢出问题
System.out.println(total2); //-1474836480

long total3 = money*(long)years; //先把一个数转Long
System.out.println(total3); //20000000000

variables, constants, scope

  • What is a variable: It is a quantity that can change
  • Java is a strongly typed language, each variable must declare its type
  • Java variables are the most basic storage unit in the program. The elements include variable name, variable type and scope.
//数据类型 变量名 = 值;
type varName [=value][{
    
    ,varName[=value]}];
//可以使用逗号隔开同多个类型的变量,但不建议在一行定义多个变量

variable scope

  • class variable (static)
  • instance variables
  • local variables
public class Variable{
    
    
    static int 	allClicks = 0; //类变量
    String str = "hello world"; //实例变量
    public void method(){
    
    
        int i=0; //局部变量
    }
}

constant

  • Constant: a value that cannot be changed after initialization, a value that will not change.
  • It can be understood as a special variable. After its value is set, it is not allowed to be changed while the program is running.
//常量一般用大写字符
final 常量名=;
final double PI=3.14;
//修饰符 不存在先后顺序,static可以写final后面
static final doube PI=3.14; //类变量,该类下的全局范围

Variable naming convention

  • All variable, method, class names: know the meaning by seeing the name
  • Class member variables: lowercase first letter + camel case principle: lastName, monthSalary
  • Local variables: lowercase first letter + camel case principle
  • Constants: uppercase letters and underscores: MAX_VALUE
  • Class name: capital letter + camel case principle: Man, GoodMan
  • Method name: lowercase first letter + camel case principle: run(), fastRun()

operator

  • Arithmetic operators: +, -, *, /, %, ++, –
  • Assignment operator: =
  • Relational operators: >, <, >=, <=, ==,!=, instanceof
  • Logical operators: &&, ||, !
  • Bit operators: &, |, ^, ~, >>, <<, >>>
  • Conditional operator:?
  • Extended assignment operators: +=, -=, *=, /=
int a=10;
int b=20;
System.out.println(a/b); //0
System.out.println((double)a/b); //0.5

long c=12300000000;
System.out.println(a+b); //int
System.out.println(a+c); //long 自动转换式子中容量大的数据类型

increment and decrement operators

// ++自增 --自减 单目运算符
int a = 3;
int b = a++; //b=a,a=a+1 先赋值 即b=3 a=4
int c = ++a; //a=a+1,c=a 先自增 即a=5 c=5

System.out.println(a); //5
System.out.println(b); //3
System.out.println(c); //5
//幂运算 2^3 2*2*2=8
double pow = Math.pow(2,3); // (底数,指数)double型
System.out.println(pow); //8.0

//扩展:笔试题 i=5 s=(i++)+(++i)+(i--)+(--i) s=?
int i=5;
int s=(i++)+(++i)+(i--)+(--i);
System.out.println(s); //24

Logical Operators

  • && logical AND operation: both variables are true, the result is true
  • || Logical AND operation: if one of the two variables is true, the result is true
  • ! Negation, true becomes false, false becomes true
// 与(and) 或(or) 非(取反)
boolean a = true;
boolean b = false;

System.out.println(a&&b); // false
System.out.println(a||b); // true
System.out.println(!(a&&b)); // true

int c=5;
boolean d = (c<5)&&(c++<5); //第一个值为false,后面就不进行判定了
System.out.println(d); //false
System.out.println(c); //5 c++未执行

Bit operations

/*
    A = 0011 1100
    B = 0000 1101

    A&B 0000 1100 按位与
    A|B 0011 1101 按位或
    A^B 0011 0001 异或
    ~B  1111 0010 非

    面试题:2*8 怎么算最快? 2<<3
    <<左移  *2 效率极高!!
    >>右移  /2
   */
System.out.println(2<<3); // 16

String concatenation

int a = 10;
int b = 20;

a+=b; // a = a+b
a-=b; // a = a-b

System.out.println(a); //10
//字符串连接符 + ,转化为String类型,然后拼接    注意!!
System.out.println(""+a+b); //1020
System.out.println(a+b+""); //30 先进行运算,再转为String拼接
System.out.println(a+b+"str"); //30str

ternary operator

// x ? y : z
//如果x为真,则结果为y,否则为z
//if(x) y; else z;
int score = 80;
String type = score<60?"不及格":"及格";
System.out.println(type); //及格

package mechanism

  • In order to better organize classes, Java provides a package mechanism, due to the namespace that distinguishes class names
  • Package syntax format:
package pkg1[.pkg2[.pkg3...]];
  • Generally, the inverted company domain name is used as the package name; com.kuangstudy.www
  • In order to be able to use the members of a package, the package needs to be imported in the Java program
import package1[.package2...].(className|*); //通配符* 导入包下所有的类
  • Reference: Alibaba Java Development Manual

JavaDoc generates documentation

The javadoc command is used to generate your own API documentation

Parameter information

  • @author author name
  • @version version number
  • @since indicates the earliest jdk version used
  • @param parameter name
  • @return return value
  • @throws Exception throwing situation

API documentation: https://docs.oracle.com/javase/8/docs/api/

/**
 * @author Kuangshen
 * @version 1.0
 * @since 1.8
 */
public class Demo05 {
    
    
    String name;

    /**
     * @author kuangshen
     * @param name
     * @return
     * @throws Exception
     */
    public String test(String name) throws Exception{
    
    
        return name;
    }
    
}
  1. Open the cmd command line in the folder where a certain class is located
  2. Input: javadoc -encoding UTF-8 -charset UTF-8 Doc (class name).java
  3. API documents related to this class will be automatically generated. Check the folder and find that there are some more files.
  4. Open index.html (home page) to view documentation comments

JAVA basics

JAVA process control

User InteractionScanner

  • The basic syntax we learned before did not realize the interaction between programs and people . Java provides us with a tool class that can obtain user input. java.util.Scanner is a new feature of Java5. We obtain user input through the Scanner class.
  • basic grammar
Scanner s = new Scanner(System.in);
  • Obtain the user's string through the next() and nextLine() methods of the Scanner class. Before reading, generally use hasNext() and hasNextLine() to determine whether there is still input data.
//创建一个扫描器对象
Scanner scanner = new Scanner(System.in);

System.out.println("使用next方式接收");
//判断用户有没有输入字符串
if(scanner.hasNext()){
    
      //使用hasNextLie()会接收一行 "hello word"
    //使用next方式接收
    String str = scanner.next(); 
    System.out.println("输入的内容为:"+str);
    //input: hello word
    //输入的内容为:hello
}
//凡是属于IO流的类如果不关闭会一直占用资源
scanner.close();

next()

  1. Valid characters must be read before the input can be completed.
  2. The next() method will remove any blanks encountered before entering valid characters.
  3. Only after entering a valid character, the blank entered after it will be used as the terminator.
  4. next() cannot get string with spaces

nextLine()

  1. Use Enter as the end character, that is, return all characters before entering the carriage return
  2. nextLine() can get blanks
//从键盘接收数据
Scanner scanner = new Scanner(System.in);
System.out.println("请输入数据:");

String str = scanner.nextLine();
System.out.println("输入的内容为:"+str);
scanner.close();

System.out.println("请输入整数:");
if(scanner.hasNextInt()){
    
    
    int i=scanner.nextInt();
    System.out.println("输入的整数为:"+i);
}else {
    
    
    System.out.println("输入的不是整数数据");
}

sequential structure

  • The basic structure of Java is a sequential structure. Unless otherwise specified, statements are executed one by one.
  • The sequential structure is the simplest algorithmic structure.
  • Statements are executed from top to bottom. They are composed of several processing steps that are executed in sequence.
  • It is a basic algorithm structure that is inseparable from any algorithm.

Select structure

  • if single selection structure if()
  • if double selection structure if( ){ }else{ }
  • if multiple selection structure if( ){ }else if{ }else{}
  • Nested if structure if( ){ if( ) }
int a = 80;
if(a>60){
    
    
    System.out.println("及格");
    if(a>80) System.out.println("且优秀");
}else if(a>0){
    
    
    System.out.println("不及格");
}else {
    
    
    System.out.println("缺考");
}
switch multiple selection structure
char grade = 'C'; //JDK新特性 可以是字符串(字符本质还是数字)
switch (grade){
    
    
    case 'A':
        System.out.println("优秀");
        break; //可选,跳出当前结构
    case 'B':
        System.out.println("良好");
        break;
    case 'C':
        System.out.println("合格");
        break;
    default: //默认,以上值没匹配到
        System.out.println("不及格");
        break;
}

Loop structure

while loop

//计算1+2+3+...+100
int i=0;
int sum=0;
while(i<100){
    
    
    i++;
    sum+=i;
}
System.out.println(sum); //5050

do … while loop

//先执行后判断,至少执行一次
do{
    
    
    i++;
    sum+=i;
}while(i<100) //跟上面效果一样

for loop

//(初始化;条件判断;迭代)
for(int i=0;i<100;i++){
    
    
    i++;
    sum+=i;
}
for(; ; ){
    
    ...} //死循环
Exercise 1
//练习:输出1-1000能被5整除的数,每行输出3个
for (int i = 1; i <= 1000; i++) {
    
    
    if(i%5==0){
    
    
        System.out.print(i+"\t"); //输出完不换行
    }
    if(i%(3*5)==0){
    
    
        System.out.println();
    }
}
Exercise 2
//练习2:输出九九乘法表
for(int i=1;i<=9;i++){
    
    
    for(int j=1;j<=i;j++){
    
    
        System.out.print(j+"*"+i+"="+i*j+"\t");
    }
    System.out.println();
}

Enhanced for loop

int[] numbers = {
    
    10,20,30,40,50}; //定义一个数组
for (int x:numbers){
    
    
    System.out.println(x); //遍历数组的元素 10 20 30 40 50
}
//相当于
for(int i=0;i<5;i++){
    
    
    System.out.println(numbers[i]);
}

break & continue

  • break can be used in the body of any loop, and can also be used in a switch statement to force an exit from the loop .
  • continue is used in loop statements to terminate a certain loop process , skip the remaining statements, and judge the next loop condition in between.
  • label: an identifier followed by a colon label:
//打印101-150之间所有的质数
int count = 0;
outer:for(int i=101;i<=150;i++){
    
    
    for (int j=2;j<i/2;j++){
    
    
        if(i%j==0)
            continue outer; //不建议使用标签
    }
    System.out.print(i+" ");
}

process control exercises

//打印等腰空心三角形
/*  例如:输入为4时
          *
         * *
        *   *
       * * * *
*/
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); //n为三角形高
for(int i=1;i<=n;i++){
    
    
    for(int j=1;j<=2*n-1;j++){
    
    
        if(i!=n){
    
     //若不为最后一行
            if(i+j==n+1)
                System.out.print("*"); //三角形左腰边
            else if(i+j==n+2*i-1)
                System.out.print("*"); //三角形右腰边
            else System.out.print(" ");
        }
        else if(j%2!=0){
    
      //最后一行,底边
            System.out.print("*");
        }else {
    
    
            System.out.print(" ");
        }
    }
    System.out.println(); //换行
}

JAVA method

method definition

  • Java methods are similar to functions in other languages. They are a piece of code used to complete a specific function.
  • A method contains a method header and a method body.
    • Modifier: Optional, defines the access type of the method and tells the compiler how to call the method.
    • Return value type: Methods may return values. returnValueType is the data type of the method return value. Some methods have no return value, so returnValueType is the keyword void.
    • Method name: It is the actual name of the method. The method name and the parameter list together constitute the method signature.
    • Parameter type: like a placeholder. When a method is called, a value is passed to the parameter, which is called an argument or variable. The parameter list refers to the parameter type, order and number of parameters of the method. Parameters are optional and methods can contain no parameters.
      • Formal parameters: used to receive external input data when the method is called.
      • Actual parameters: The data actually passed to the method when calling the method.
    • Method body: The method body contains specific statements that define the function of the method.
修饰符 返回值类型 方法名(参数类型 参数名,...{
    
    
   方法体...
   return 返回值;
}

method call

  • Calling method: object name. method name (actual parameter list).
  • Java supports two ways of calling methods, depending on whether the method returns a value.
  • When a method returns a value, the method call is usually treated as a value .
int larger = max(30,40);
  • If the method return value is void, the method call must be a statement.
  • Extension: Pass by value and pass by reference ( Java is both pass by value ).
  • To call methods of other classes, unless it is a static method, this class must be instantiated (new)
public class Demo01 {
    
    
   
    public static void main(String[] args) {
    
    
        int add = Demo01.add(1,2); // 通过类名直接调用静态方法
        System.out.println(add); // 3
    }
	// static静态方法,否则就要new实例化来调用
    public static int add(int a,int b){
    
    
        return a+b;
    }
}

Pass by value (java) & pass by reference

Method overloading

Overloading is a method in a class that has the same method name but different parameter lists.

Rules for method overloading:

  • Method names must be the same
  • Parameter lists must be different (different number, parameter type, or ordering)
  • The return types can be the same or different
  • Merely having different return types is not enough to be an overload of a method

implementation theory

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

Command line parameter passing

  • Sometimes you want to pass messages to a program when it is running. This is accomplished by passing command line arguments to the main() function.
public static void main(String[] args) {
    
    
    //args.length 数组长度
    for (int i = 0; i < args.length; i++) {
    
    
        System.out.println("args["+i+"]: "+args[i]);
    }
}

variable parameter

  • Starting with Jdk 1.5, Java supports passing variable parameters of the same type to a method.
  • In a method declaration, add an ellipsis (…) after specifying the parameter type.
  • Only one variable parameter can be specified in a method, and it must be the last parameter of the method.
//打印最大值
public static void printMax(int... num){
    
    
    if(num.length==0){
    
    
        System.out.println("没有值传入");
        return;
    }
    int result = num[0];
    for (int i = 1; i < num.length; i++) {
    
    
        if(num[i] > result){
    
    
            result = num[i];
        }
    }
    System.out.println("最大值是:"+result);
}
public static void main(String[] args) {
    
    
    printMax(1,2,3,4); //最大值是:4
    printMax(new int[]{
    
    1,2,3,4,5}); //最大值是:5
}

recursion

Recursion means: method A calls method A, which calls itself!

The recursive strategy requires only a small amount of code to describe multiple repeated calculations in the problem-solving process, greatly reducing the amount of code in the program. The power of recursion lies in defining infinite collections of objects with finite statements.

recursive structure

  • Recursive header: When not calling its own method, it will fall into an infinite loop without a header.
  • Recursive body: When does it need to call its own method?
//阶乘 n! n*(n-1)*...*2*1
public static int f(int n){
    
    
    if(n==1) return 1;
    return n*f(n-1); //递归:调用自身
}
public static void main(String[] args) {
    
    
    System.out.println(f(5)); //5!= 120
}

JAVA array

Array definition

  • An array is an ordered collection of data of the same type
  • An array describes several data of the same type, sorted and combined in a certain order.
  • Among them, each data is called an array element, and each array element can access them through subscripts.

Array declaration creation

  • Array variables must first be declared before an array can be used in a program.
dataType[] arrayRefVar; //首选
dataType arrayRefVar[]; //效果相同,但不是首选
  • The Java language uses the new operator to create an array. The syntax is as follows
dataType[] arrayRefVar = new dataType[arraySize]; 
//int[] nums=new int[10]
  • The elements of the array are accessed by index, and the array index starts from 0
  • Get the array length: arrays.length
int[] nums; //1.声明一个数组
nums = new int[3]; //2.创建一个数组
//3.给数组元素赋值
nums[0]=1;
nums[1]=2;
nums[2]=3;
for (int num : nums) {
    
     //打印数组所有元素
    System.out.println(num);
}

Three types of initialization of arrays

  • static initialization
//静态初始化:创建+赋值
int[] a={
    
    1,2,3};
Man[] mans={
    
    new Man(1,1),new Man(2,2)}
  • dynamic initialization
//包含默认初始化
int[] a=new int[2]; //默认值为0
a[0]=1;
a[1]=2;
  • Default initialization
    • The array is a reference type, and its elements are equivalent to the instance variables of the class. Therefore, once the array is allocated space, each element in the array is implicitly initialized in the same way as the instance variable.

Basic characteristics of arrays

  • Its length is determined, and once the array is created, its size cannot be changed.
  • Its elements must be of the same type, no mixed types are allowed.
  • The elements in an array can be of any data type, including basic types and reference types.
  • Array variables are reference types, and arrays can also be viewed as objects, where each element is equivalent to a member variable of the object.
  • The array itself is an object. In Java, objects are in the heap, so whether the array stores primitive types or other object types,

The array itself is on the heap.

array bounds

The legal range of subscripts is: [0, length-1]. If it goes out of bounds, an error will be reported.

Use of arrays

  • For-Each loop
int[] arrays = {
    
    1,2,3,4,5};
//打印全部的数组元素 JDK1.5 没有下标
for (int array : arrays) {
    
    
    System.out.println(array);
}
  • Array as method input parameter
//打印数组元素
public static void printArray(int[] a){
    
    
    for (int i = 0; i < a.length; i++) {
    
    
        System.out.print(a[i]+" ");
    }
}
  • Array as return value
//反转数组
public static int[] reverse(int[] arrays){
    
    
    int[] result = new int[arrays.length];
    //反转的操作
    for (int i = 0; i < arrays.length; i++) {
    
    
        result[i] = arrays[arrays.length-i-1];
    }
    return result;
}

Multidimensional Arrays

  • Multidimensional arrays can be regarded as arrays of arrays. For example, a two-dimensional array is a special array, and each element is a one-dimensional array.
int arr[][] = new int[3][2]; //二维数组,三行两列
int[][] array = {
    
    {
    
    1,2},{
    
    3,4},{
    
    5,6}};
//打印二维数组所有元素
for (int i = 0; i < array.length; i++) {
    
     //arrays.length=3
    for (int j = 0; j < array[i].length; j++) {
    
    
        System.out.print(array[i][j]+" ");
    }
    System.out.println();
}

Arrays class

  • Array utility class java.util.Arrays
  • Since the array object itself has no methods for us to use, the API provides a tool class Arrays for us to use.
  • The methods in the Array class are all static methods modified by static. When used, they are called directly using the class name, and they can be called without an object.
  • Common Functions
    • Assign a value to the array: fill method.
    • Sorting: sort method, ascending order.
    • Comparing arrays: The equals method compares whether the element values ​​in the array are equal.
    • Find array elements: binarySearch performs a binary search operation on the sorted array.
int[] a = {
    
    1,2,3,4,9000,32145,451,21};
System.out.println(a); // [I@28d93b30 (hashcode)

//Arrays.toString 打印数组元素
System.out.println(Arrays.toString(a)); //[1, 2, 3, 4, 9000, 32145, 451, 21]

//二分法查找某值 返回下标
System.out.println(Arrays.binarySearch(a, 9000)); // 4

//填充
Arrays.fill(a,2,4,0); //数组[a[2]~a[4])之间填充0
System.out.println(Arrays.toString(a)); //[1, 2, 0, 0, 9000, 32145, 451, 21]

//升序排序
Arrays.sort(a);

Bubble Sort

  • Bubble sort is the most famous sorting algorithm among the eight sorting algorithms.
  • Code: Two layers of loops, the outer layer bubbles for a number of rounds, and the inner layer compares sequentially.
  • When we see nested loops, we should immediately conclude that the time complexity of this algorithm is O(n^2) .
//冒泡排序
//1.比较数组中两个相邻的元素,如果第一个数大于第二个数,交换它们位置
//2.每一次比较,都会产生一个最大或最小的数字(升序为最大数)
//3.下一轮则可以少一次排序
//4.依次循环,直到结束
public static int[] sort(int[] array){
    
    
    int temp=0;
    //外层循环,次数length-1
    for (int i = 0; i < array.length-1; i++) {
    
    
        //内层循环:如果第一个数大于第二个数,交换它们位置
        for (int j = 0; j < array.length-1-i; j++) {
    
    
            if(array[j]>array[j+1]){
    
    
                temp=array[j];
                array[j]=array[j+1];
                array[j+1]=temp;
            }
        }
    }
    return array;
}

public static void main(String[] args) {
    
    
    int[] a={
    
    8,1,35,47,19,-2};
    int[] sort = sort(a);
    System.out.println(Arrays.toString(sort)); //[-2, 1, 8, 19, 35, 47]
}

sparse array

//创建一个二维数组 11*11  0:没有棋子,1:黑棋  2:白棋
int[][] array1 = new int[11][11];
array1[1][2] = 1;
array1[2][3] = 2;
//输出原始的数组
System.out.println("原始的数组:");
for (int[] array : array1) {
    
    
    for (int i : array) {
    
    
        System.out.print(i+"\t");
    }
    System.out.println();
}

//转换为稀疏数组保存
//1.有效值的个数
int sum = 0; //有效值总数
for (int i = 0; i < 11; i++) {
    
    
    for (int j = 0; j < 11; j++) {
    
    
        if(array1[i][j]!=0){
    
    
            sum++;
        }
    }
}
//2.创建一个稀疏数组
int[][] array2 = new int[sum+1][3];
array2[0][0] = 11;
array2[0][1] = 11;
array2[0][2] = sum;

//3.遍历二维数组,将有效值存放到稀疏数组
int count = 0;
for (int i = 0; i < array1.length; i++) {
    
    
    for (int j = 0; j < array1[i].length; j++) {
    
    
        if(array1[i][j]!=0){
    
    
            count++;
            array2[count][0] = i;
            array2[count][1] = j;
            array2[count][2] = array1[i][j];
        }
    }
}

//4.输出稀疏数组
System.out.println("稀疏数组:");
for (int i = 0; i < array2.length; i++) {
    
    
    for (int j = 0; j < array2[i].length; j++) {
    
    
        System.out.print(array2[i][j]+"\t");
    }
    System.out.println();
}
/* 结果:
输出原始的数组
0	0	0	0	0	0	0	0	0	0	0	
0	0	1	0	0	0	0	0	0	0	0	
0	0	0	2	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
稀疏数组
11	11	2	
1	2	1	
2	3	2	
*/
System.out.println("============还原==========");
int array3[][] = new int[array2[0][0]][array2[0][1]];
for(int i = 1;i<array2.length;i++){
    
    
		array3[array2[i][0]][array2[i][1]] = array2[i][2];
}
for (int[] array : array3) {
    
    
    for (int i : array) {
    
    
         System.out.print(i + " ");
    }
    System.out.println();
}

object-oriented

First introduction to object-oriented

Process Oriented & Object Oriented

  • process-oriented thinking
    • The steps are clear and simple, what to do in the first step, what to do in the second step...
    • Process-oriented is suitable for handling some simpler problems
  • object-oriented thinking
    • Birds of a feather flock together, a thinking mode of classification. When thinking about a problem, you will first think about what classifications are needed to solve the problem, and then think about these classifications individually. Finally, process-oriented thinking is carried out on the details under a certain category.
    • Object-oriented is suitable for dealing with complex problems and problems that require the cooperation of multiple people!
  • For describing complex things, in order to grasp it from a macro perspective and analyze it reasonably as a whole, we need to use object-oriented to analyze the entire system. However, specific micro-operations still need to be handled with a process-oriented approach.

What is object-oriented

  • Object-Oriented Programming (OOP)
  • Essence: Organize code in the form of classes, and organize (encapsulate) data in the form of objects .
  • abstract
  • Three major characteristics
    • encapsulation
    • inherit
    • Polymorphism
  • From an epistemological point of view, there are objects first and then classes. Objects are concrete things, and classes are abstractions of objects.
  • From the perspective of code running, there are classes first and then objects. Classes are templates for objects.

The relationship between classes and objects

  • A class is an abstract data type. It is an overall description/definition of a certain type of thing, but it does not represent a specific thing.
    • Animals, plants, mobile phones, computers…
    • Person class, Pet class, Cat class, etc. are all used to describe/define the characteristics and behaviors that a specific thing should have.
  • Objects are concrete instances of abstract concepts. For example, Zhang San is a concrete instance of a person, and Zhang San's dog Wangcai is a concrete instance of a dog.

Create and initialize objects

  • Use new to create objects.
  • When created using the new keyword, in addition to allocating memory, the created object will also be initialized by default and the constructor in the class will be called.
  • The constructor in a class is also called a constructor method and must be called when creating an object. It has the following characteristics:
    • Must be the same as the class name
    • There is no return type and void cannot be written.
  • Even if a class does not write anything, there will still be a default constructor.

Constructor

public class Person {
    
    
    //一个类即使什么都不写,也会存在一个默认的无参构造方法
    //显示地定义构造器
    String name;
    
    //作用:1. 使用new关键字,本质是在调用构造器
    //2. 用来初始化对象的值
    public Person(){
    
    } //无参构造
    
    //有参构造 3.一旦定义了有参构造,无参就必须显示定义
    public Person(String name){
    
    
        this.name=name;
    }
	//Alt+insert 快捷键插入构造方法
}

Memory analysis

//定义一个宠物类
public class Pet {
    
    
    public String name; //默认 null
    public int age; 	//默认 0
    //无参构造

    public void shout(){
    
    
        System.out.println("叫了一声");
    }
}
//应用类,创建调用对象
public class Application {
    
    
    public static void main(String[] args) {
    
    
        
        Pet dog = new Pet();

        dog.name = "旺财";
        dog.age = 3;
        dog.shout();
    }
}

A brief summary of classes and objects

  1. Classes and Objects
    A class is a template: abstract, an object is a concrete instance

  2. Method
    definition, call

  3. Reference type of object
    : basic type (8)

    Objects are operated by references: stack---->heap

  4. Attribute: Field member variable

    Default initial value:

    ​ Number: 0 0.0

    ​ char: u0000

    ​ boolean:false

    ​ Reference: null

    Modifier attribute type attribute name = attribute value

  5. Creation and use of objects

    • Object uses new keyword to create object, constructor Person person = new Person();
    • Object attribute person.name;
    • Object method person.sleep();

encapsulation

  • Reveal what should be revealed, hide what should be hidden
    • Our programming should pursue "high cohesion and low coupling". High cohesion means that the internal data details of the class are completed by itself and no external interference is allowed; low coupling: only a small number of methods are exposed for external use.
  • Encapsulation (hiding of data)
    • In general, direct access to the actual representation of data in an object should be prohibited and should instead be accessed through the manipulation interface, known as information hiding.
  • effect
    1. Improve program security and protect data
    2. Hiding code implementation details
    3. unified interface
    4. System maintainability increased

inherit

  • The essence of inheritance is to abstract a certain batch of classes to better model the world.
  • extends means "extend". A subclass is an extension of the parent class, represented by the keyword extends.
  • Classes in Java only have single inheritance, not multiple inheritance! A class can only inherit from one parent class.
  • Inheritance is a relationship between classes, in addition to dependencies, combinations, aggregations, etc.
  • There are two classes in the inheritance relationship, one is the subclass (derived class), and the other is the parent class (base class). The subclass inherits the parent class.
  • There should be an "is a" relationship between the subclass and the parent class in a sense.
//学生类(子类)继承 人类(父类)
public class Student extends Person{
    
     /*Person extends Object*/
    ...
}
  • If a subclass inherits the parent class, it will have all the methods of the parent class, but private properties and methods cannot be inherited .
  • In Java, all classes directly or indirectly inherit the Object class by default (Ctrl+H can view class relationships)
  • Classes modified by final cannot be inherited (no descendants).

super & this

  1. super() calls the constructor of the parent class and must be the first in the constructor
  2. super must only appear in methods or constructors of subclasses
  3. **super() and this()** cannot call the constructor at the same time, because this must also be written in the first line
  • The difference between super and this: super represents a reference to the parent class object and can only be used under inheritance conditions; this calls its own object and can be used without inheritance.
super(); //隐藏代码,默认调用了父类的无参构造,要写只能写第一行

Method overriding

  • Rewriting: The method of the subclass must be consistent with the method of the parent class, but the method body is different.
  • Overriding is the rewriting of methods and has nothing to do with attributes
  • Overriding methods is only relevant to non-static methods and has nothing to do with static methods (static methods cannot be overridden)
public class B {
    
    
    public static void test(){
    
     //静态方法
        System.out.println("B==>test()");
    }
}
public class A extends B{
    
     //继承
    public static void test(){
    
    
        System.out.println("A==>test()");
    }
}
public class Application {
    
    
    public static void main(String[] args) {
    
    
        //方法的调用之和左边定义的类型有关
        A a = new A();
        a.test(); //打印 A==>test()

        //父类的引用指向了子类,但静态方法没有被重写
        B b = new A();
        b.test(); //打印 B==>test()
    }
}

Modify A.java, B.java

public class B {
    
    
    public void test(){
    
     //非静态方法
        System.out.println("B==>test()");
    }
}
public class A extends B{
    
    
    @Override //重写了B的方法
    public void test() {
    
    
        System.out.println("A==>test()");
    }
}
//父类的引用指向了子类
B b = new A(); //子类重写了父类的方法,执行子类的方法
b.test(); //打印变成了 A==>test()
/* 
静态方法是类的方法,非静态方法是对象的方法
有static时,b调用了B类的方法,因为b是b类定义的
没有static时,b调用的是对象的方法,而b是A类new出来的对象,调用A的方法
*/
  • Static methods are methods of classes, non-static methods are methods of objects

  • When there is static, b calls the method of class B, because b is defined by class B.

  • When there is no static, b calls the method of the object, and b is defined by class A.

  • b is the object created by A new, and the method of A is called.

  • Static methods belong to classes, non-static methods belong to objects

  • important point:

    1. Method names and parameter lists must be the same
    2. The scope of the modifier can be expanded but cannot be reduced (public>protect>private)
    3. The scope of exceptions thrown can be narrowed but cannot be expanded.
    4. Methods modified by **static (belonging to classes, not instances), final (constant methods), and private (private)** cannot be overridden.
    5. Overriding, the method of the subclass must be consistent with the method of the parent class
  • Why rewrite?

    1. The functions of the parent class are not necessarily required by the subclass, or may not be satisfied.

      control + Enter : override;

Polymorphism

  • Dynamic Compilation: Type: Extensibility
  • That is, the same method can adopt different behaviors depending on the sending object.
  • The actual type of an object is determined, but there can be many references to the object.
  • Polymorphic existence conditions
    • Have inheritance relationship
    • Subclass overrides parent class method
    • Parent class reference points to child class object
Student s1 = new Student();
Person s2  = new Student();
Object s3  = new Student();
//子类能调用的方法都是你自己的或者继承父类的
//父类可以指向子类,但是不能调用子类独有的方法
s2.run();
//对象能执行哪些方法,主要看对象左边的类型,和右边关系不大
  • important point:
    1. Polymorphism is method polymorphism, not attribute polymorphism
    2. Parent class and subclass, there is a related type conversion exception: ClassCastException
    3. Existence conditions: inheritance relationship, method needs to be rewritten, parent class reference points to child class object!

Methods that cannot be overridden

  1. static method, belongs to the class, it does not belong to the instance
  2. final constant
  3. private private method

instanceof and type conversion

  • instanceof reference type comparison to determine what type an object is
public static void main(String[] args) {
    
    

    // Object > String
    // Objest > Person > Student
    // Objest > Person > Teacher
    Object object = new Student();
	// X instanceof Y,X引用指向的对象是不是Y的子类
    System.out.println(object instanceof Student); //true
    System.out.println(object instanceof Person); //true
    System.out.println(object instanceof Teacher); //false
    System.out.println(object instanceof Object); //true
    System.out.println(object instanceof String); //false
	
    //类型之间的转化:父-子(高-低),低可以转换为高
    Person obj = new Student(); //只能用Person方法(重写了用子类重写过的方法)
    (Student)obj.go(); //强转之后可以用Student方法(Student->go())
}

type conversion

  1. The parent class reference points to the object of the child class
  2. Converting a subclass to a parent class and upward transformation will lose some of its original methods.
  3. Convert the parent class to a subclass, cast down, force conversion, and then call the subclass method
  4. Convenient method calling (transformation), reducing repeated code, and simplicity.

Static

  • Static variables can be accessed directly using the class name, also called class variables.
  • Static variables (or methods) for a class are shared by all objects (instances).
  • The static area code is initialized together when loading the class, and is executed at the earliest and only once (the first time new).
  • Math->Random number:
//静态导入包
import static java.lang.Math.random;

public class Application {
    
    
    public static void main(String[] args) {
    
    

        //第一种随机数,不用导包
        System.out.println(Math.random()); //0.7562202902634543

        //第二种随机数,静态导入包
        System.out.println(random()); //0.5391606223844663
    }
}
{
    
    
  //匿名代码块
}
static {
    
    
  //静态代码块
}
public class noName {
    
    
    //2  赋初始值
    {
    
    
        System.out.println("匿名代码块");
    }
    //1  只执行一次
    static {
    
    
        System.out.println("静态代码块");
    }
    //3
    public noName(){
    
    
        System.out.println("构造方法");
    }
}

abstract class

  • The class modified by abstract is an abstract class, and the modified method is an abstract method.
  • There is no need for abstract methods in abstract classes, but classes with abstract methods must be declared as abstract classes.
  • Abstract classes cannot use new to create objects, it is used for subclasses to inherit.
  • Abstract methods only have method declarations and no implementation, leaving it to subclasses to implement them.
  • A subclass inherits an abstract class and must implement all methods of the abstract class, otherwise the subclass must also be declared as an abstract class.
//abstract 抽象类 类只能单继承(接口可以多继承)
public abstract class Action {
    
    

    //约束~有人帮我们实现~
    //抽象方法只有方法名,没有方法的实现
    public abstract void doSth();

    //1.不能new抽象类,只能靠子类去实现它,仅作为一个约束
    //2.抽象方法只能出现在抽象类中,抽象类可以有普通方法
    //3.抽象类有构造器,可以派生子类
    //4.抽象类的意义:约束,提高开发效率。但是类只能单继承,所以有局限 用的不多
}

interface

  • Ordinary class: only concrete implementation
  • Abstract class: both concrete implementation and specification (abstract method)
  • Interface: only specifications, no method implementation, professional constraints! Separation of constraints and implementation: interface-oriented programming~
  • An interface is a specification, which defines a set of rules, the idea of ​​"what you are...what you must do...".
  • The essence of interfaces is constraints, just like human laws, which are formulated and everyone abides by them.
//interface接口,接口都要有实现类
//实现类(implements 可以继承多个接口)
//多继承,利用接口实现多继承
public interface UserService {
    
    
    //定义的属性都是常量,默认修饰 public static final
    public static final int AGE = 99; //一般不用
    //所有的定义的方法都是抽象的 默认public abstract
    public abstract void run();
    void add();
    void query();
    void delete();
}
public class UserServiceImpl implements UserService{
    
    
    @Override
    public void add(String name) {
    
    
    }
    @Override
    public void delete(String name) {
    
    
    }
    @Override
    public void update(String name) {
    
    
    }
    @Override
    public void query(String name) {
    
    
    }
}

important point

  • The interface has no constructor and cannot be instantiated
  • Implementing classes must override methods in the interface
  • Implementations can implement multiple interfaces

inner class

  • An inner class is to define another class inside a class. For example, if a class B is defined in class A, then B is the inner class of A, and A is an outer class relative to B.
    1. Member inner class: can operate the private properties and methods of the outer class
    2. Static inner class: static modification, cannot access external class private properties
    3. Local inner class: class defined in the method of the outer class
    4. Anonymous inner class: initializer class without name
  • There can be multiple classes in a Java class, but there can only be one public class.
public class Outer {
    
    
    private int id = 10;

    public void out() {
    
    
        System.out.println("这是一个外部类的方法");
    }

    class Inner {
    
    
        public void in() {
    
    
            System.out.println("这是一个内部类的方法");
        }

        //获得外部类的私有属性
        public void getId() {
    
    
            System.out.println(id);
        }
    }
}
public class Application {
    
    
    public static void main(String[] args) {
    
    
        Outer outer = new Outer();
        //通过外部类来实例化内部类
        Outer.Inner inner = outer.new Inner();
        inner.in();
        inner.getId();
    }
}

public class Outer {
    
    
    //局部内部类
    public void method(){
    
    
        class Inner{
    
    
            public void in(){
    
    
                
            }
        }
    }
}
public class Outer {
    
    
    public static void main(String[] args) {
    
    
        //Apple apple = new Apple();
        //没有名字初始化类
        new Apple().eat();
        new UserService(){
    
    
            @Override
            public void hello() {
    
    
                
            }
        };
    }
}
class Apple{
    
    
    public void eat(){
    
    
        System.out.println("eat");
    }
}
interface UserService{
    
    
    void hello();
}

abnormal

  • When software programs are running, they may often encounter abnormal problems. Exceptions in English (Exception) mean exceptions. These exceptions require us to write programs to handle them reasonably so as not to cause the program to crash.
  • Exceptions refer to various unexpected conditions that occur during program operation: files cannot be found, network connection errors, illegal parameters, etc.
  • Exceptions occur during program execution and affect the normal execution flow.

Simple classification

  • Checked exceptions: The most representative exceptions are exceptions caused by user errors or problems, which cannot be foreseen by the programmer. For example, exceptions are thrown when the user wants to open a file that does not exist. These exceptions cannot be simply ignored at compile time.
  • Runtime exceptions: are exceptions that may be avoided by the programmer. Contrary to checked exceptions, runtime exceptions can be ignored at compile time.
  • Error: Error is not an exception, but a problem beyond the programmer's control. Errors in code are often ignored. For example, when the stack overflows and an exception occurs, they cannot be checked during compilation.

Exception handling mechanism

  • throw an exception
  • catch exception
  • Exception handling keywords: try, catch, finally, throw, throws
public static void main(String[] args) {
    
    
    int a = 1;
    int b = 0;

    try {
    
     //try监控区域
        System.out.println(a/b);
    }catch (ArithmeticException e){
    
     //catch 捕获异常
        System.out.println("程序出现异常,变量b不能为0");
    }catch (Exception e){
    
    
        e.printStackTrace();
    }finally {
    
     //一定会执行,处理善后工作,如关闭资源
        System.out.println("finally");
    }
    
    if(b==0){
    
     //抛出异常一般在方法中使用
        throw new ArithmeticException(); //主动抛出异常
    }
}
//Ctrl+Alt+T 快捷键插入 try-catch
  • Suppose you want to catch multiple exceptions, from small to large.
  • Exception shortcut key command + option + T
public class Application {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            new Application().test(1,0);
        } catch (ArithmeticException e) {
    
    
            e.printStackTrace();
        }
    }
    //假设这个方法中,处理不了这个异常。方法上抛出异常
    public void test(int a,int b) throws ArithmeticException{
    
    
        if(b==0){
    
    
            //主动抛出异常,一般在方法中使用
            throw new ArithmeticException();
        }
    }
}

Custom exception

  • Most exceptions that occur during programming can be described using Java's built-in exception classes. In addition, users can also customize exceptions. User-defined exceptions only need to inherit the Exception class
  • Use custom exception classes and classifications in programs
    1. Create a custom exception class
    2. Throw an exception object through the throw keyword in the method
    3. If the exception is handled in the method of the currently thrown exception, you can use the try-catch statement to capture and handle it; otherwise, use the throws keyword at the declaration of the method to indicate the exception to be thrown to the method caller, continue and perform the next step.
    4. Catch and handle exceptions in the caller of the exception method.
//自定义异常类
public class MyException extends Exception{
    
    
    //传递数字 > 10 抛出异常
    private int detail;
    public MyException(int message){
    
    
        this.detail = message;
    }
    //toString: 异常的打印信息
    @Override
    public String toString() {
    
    
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}
public class Test {
    
    
    //可能会存在异常的方法
    static void test(int a) throws MyException {
    
    
        if (a > 10) {
    
    
            throw new MyException(a); //抛出
        }
        System.out.println("传递的参数为 " + a);
    }

    public static void main(String[] args) {
    
    
        try {
    
    
            test(11);
        } catch (MyException e) {
    
    
            System.out.println("MyException=>" + e);
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_42823298/article/details/128568085