[java] The first eight chapters: quick memory

Before I knew it, I had been learning Java for nearly two months. The textbook also slowly turned to the eighth chapter. I always feel that I have not learned anything. I have always wanted to stop and tidy up, so today

2021-10-23 09:38:03 Saturday

Review summary of the first eight chapters of java (theoretical content)

I am confused and have no coding experience. I will sort out and extract some theoretical things for my own reference. There must be mistakes.

Chapter One

Simple understanding of java

Java has the characteristics of simplicity, object-oriented, distributed, robustness, security, platform independence and portability, multithreading, and dynamics [2]. Java can write desktop applications, web applications, distributed systems and embedded system applications, etc.

Working principle
consists of four aspects:
(1) Java programming language
(2) Java class file format
(3) Java virtual machine
(4) Java application program interface (4) Java application program interface To be
specific, Baidu java introduction

The basic steps to build a java development environment:

Click -> Baidu's basic steps to build a java development environment
to see for yourself; it is very simple to follow step by step.

Chapter 2: Basic Data Types and Operations

There are a total of 8 basic data types in java, and the storage space occupied by each data type is fixed. This feature also increases the portability of java. This is different from c language c++, because java runs on **virtual machine (jvm)**, and the adaptation between data types, operating systems and hardware is realized through virtual machines.

8 basic data types in Java : byte short int long float double boolean char


  • byte short int long all represent signed numbers, that is, the highest bit is used to represent positive and negative, 0 represents positive, 1 represents negative;
  • byte occupies one byte, indicating the range: -~2^7-1 ie -128~127
  • short occupies two bytes, indicating the range: –~2^15-1
  • int occupies four bytes, indicating the range: -~2^31-1
  • long occupies eight bytes, indicating the range: -~2^63-1
  • float occupies four bytes, double occupies eight bytes
  • char occupies two bytes, one char represents a unicode code, range: 0~2^16
  • boolean occupies one byte, only true and false two values

Among them, the use and usage attention are similar to the C language, including but not limited to (type conversion and operation, implicit type conversion, explicit type conversion) and so on.

java operator


Level 1: Arithmetic Operators

image

Click to view the code
package step1;
import java.util.Scanner;
public class Cal {
	public static void main(String[] args) {
		/*********start*********/
		 System.out.println("请输入第一个整数");
         System.out.println("请输入第二个整数");
		 Scanner sc=new Scanner(System.in);
		int a=sc.nextInt();
		int b=sc.nextInt();
		int c,d,e,f,g;
		c=a+b;d=a-b;e=a*b;f=a/b;g=a%b;
		System.out.println("两数相加的结果为:"+c);
		System.out.println("两数相减的结果为:"+d);
		System.out.println("两数相乘的结果为:"+e);
		System.out.println("两数相除的结果为:"+f);
		System.out.println("两数取余数的结果为:"+g);
		/*********end*********/
	}

}

Test case:

image

Pass 2: Relational Operators

image

Click to view the code
package step2;
import java.util.Scanner;
public class Relative {
	public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int a=sc.nextInt();
        int b=sc.nextInt();
        /*********start*********/
		System.out.println("a==b="+(a==b));
		System.out.println("a!=b="+(a!=b));
		System.out.println("a>b="+(a>b));
		System.out.println("a<b="+(a<b));
		System.out.println("b>=a="+(b>=a));
		System.out.println("b<=a="+(b<=a));
		/*********end*********/
	}

}

The first test will input data: 20,34;
you need your program to output:

a==b=false
a!=b=true
a>b=false
a<b=true
b>=a=true
b<=a=false			

Level 3: Logical Operators

What is a logical operator?
Logical operators are used to test the logical relationship between two operands, and the two operands must be of Boolean type (such as relational expressions), and the result obtained is also of Boolean type. The variable or expression connected by logical operators is Boolean type is called logical expression

image

We can understand logical operators from the perspective of "voting and election":
AND: require everyone to vote for a certain issue;
or: only require one person to vote for it to pass a certain issue;
NOT: someone originally voted for it, and the non-operator can invalidate their vote; XOR
: only one person can vote for it before a certain issue can be passed

Click to view the code
package step3;
import java.util.Scanner;
public class testLogic {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
  		boolean a=sc.nextBoolean();
        boolean b=sc.nextBoolean();
        boolean c=sc.nextBoolean();     
		/*********start  *********/  
        System.out.println(!a);      
        System.out.println(a && b &&c);          
        System.out.println( c || b );	       
        System.out.println( !b  );        
		/*********end  *********/
	}
}

Test instructions After writing the program according to the relevant requirements, I will test your program. Expected input:

true,false,true

Expected output:
false
false
true
true

Level 5: Operator precedence

image

Java-specific operator (instancceof) <I don’t know if it’s unique, but I’ll see you once>

Binary operation instance operator, used to judge whether the specified object is a specific type (class type or interface type <Chapter 5 content>)
For example:

		obj instanceof String
		其中,obj是一对像实例,若obj是string类型实例,则运算结果是true,否则为false。

String, the java class, stores string types, Chapter 7

2.5 practice

1. Output the value range of java basic data types

Tip: The Java language provides corresponding wrapper classes for basic data types, namely Boolean, Byte, Character, and Short. Integer, Long, Float, Double. The static member variables MIN_VALUE and MAX_VALLUE are encapsulated in the wrapper class, which respectively express the minimum and maximum values ​​that the basic data types can represent.

Click to view the code

public class HOME {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("Boolean最大值:true" +"最小值:flase");    //这里好像不是这么写的,管他呢,知道就行 ,不太会写代码
		System.out.println("byte的取值范围:");
		System.out.println(Byte.MIN_VALUE+"~"+Byte.MAX_VALUE);
		System.out.println("Character的取值范围:");
		System.out.println((int)Character.MIN_VALUE+"~"+(int)Character.MAX_VALUE);
		System.out.println("short的取值范围:");
		System.out.println(Short.MIN_VALUE+"~"+Short.MAX_VALUE);
		System.out.println("Integer的取值范围:");
		System.out.println(Integer.MIN_VALUE+"~"+Integer.MAX_VALUE);
		System.out.println("Long的取值范围:");
		System.out.println(Long.MIN_VALUE+"~"+Long.MAX_VALUE);
		System.out.println("Float的取值范围:");
		System.out.println(Float.MIN_VALUE+"~"+Float.MAX_VALUE);
		System.out.println("Double的取值范围:");
		System.out.println(Double.MIN_VALUE+"~"+Double.MAX_VALUE);

	}

}


Chapter 3: Structured Programming (Process-Oriented Programming)

  • sequential structure
    image

  • branch structure
    image

  • loop structure
    image

Same as c, do not write

Practice: find the approximate value of π

Click to view the code

public class HOME4 {

	public static void main(String[] args) {
		
		System.out.println("PI = ");
		float k = 1;
		float b = 1;
		float c = 0;
		while((1/b)>1e-6) {
			c += k*1/b;
			b +=2;
			k = -k;
			
		}
		System.out.println(4*c);

	}



}

Chapter 4: Arrays

Just understand and learn to use all the content
image
in the following figure. Specifically, the Java Basic Grammar (6) - the definition and use of arrays , very specific C language is also applicable

Chapter 5: Classes and class inheritance (should be a very important chapter)

Object Oriented Basic Concepts

Object-oriented: Extract the involved objects, and then consider the relationship between objects to build the entire project. Object-oriented design is an object-oriented implementation process that provides a symbolic design system. , object-oriented is guided by domain object development.

Example (maybe not quite right):
put an elephant in the freezer

Process Oriented Thinking:

  • open the refrigerator
  • pack the elephant
  • turn off the refrigerator

Object-oriented thinking:

  • refrigerator open
  • refrigerator storage
  • refrigerator off

image
Next, we start to understand all the content of the above picture from the object,

1. Object definition

meaning

Objects are instances of classes that possess concrete state behavior. For example, Student is a class (describing the common state and behavior of similar objects), while an object refers to a specific individual Student. Objects are dynamic, and each object has a dynamic process from creation, operation to extinction. At the same time, the object also occupies memory space and stores the state data of the object, that is, member variables. (For example, the height of Wenhai <object> <member variable>)

		//定义方法:类名 对象名;
		//或者类名 对象名 = new 类名( 参数列表 );
		Student a;
		Student a = new Student();

composition

It is related to member variables and methods in the class (for example, a person has multiple attributes: name, gender, age, weight, etc., and has multiple behaviors: eating, walking, etc.) Object = attribute + behavior

template

There is nothing to say, the template is a class, so let me introduce the class

What is a class: a class does not exist as an entity, such as the mobile phone class, the mobile phone is not an entity, such as the iPhone7 is an entity, the mobile phone is not, the class is just a mold, to determine the characteristics (properties) and behaviors (methods) that the object will
have

		定义类名 public class 类名{
		//[初始化模块](https://www.cnblogs.com/wp456/p/3233186.html "初始化模块")的定义【初始化模块首先被执行】

		 //定义属性(成员变量)的部分

			编写类的属性 属性1的类型 属性1;

			属性2的类型 属性2;

		 	..........

			属性n的类型 属性n;

		//定义方法(行为)的部分;

			编写类的方法 方法1;

			方法2;

			 ........

			方法n;
		}

For example: the definition of the mobile phone class:

Click to view the code
public class Telphone {//1.定义一个类
	
    //2.定义属性(成员变量)
    float screen;//屏幕
    float cpu;//cpu大小
    float mem;//内存大小
    //3.定义方法
void call(){
    System.out.println("Telphone有打电话的功能!");
}
void sendMessage(){
   System.out.println("screen:"+ screen + "cpu:"+ cpu + "mem:"+ mem +"Telphone有发短信的功能");
}
}

The difference between member variables and local variables is similar to that of c, so I won’t go into details, but modifiers need to be mastered
image

image

features

  • Encapsulation: Encapsulation is an information shielding technology. Through encapsulation, the state and behavior of the object are combined into an independent module, and the internal details of the object (including the private state inside the object and the specific implementation of the behavior) are hidden as much as possible. The purpose of encapsulation is to separate the designer of the object from the user . As a user, he does not need to understand the internal implementation details of the object, but only needs to use the behavior method provided by the designer to realize the function.

The private keyword
is a permission modifier.
Members used to modify members (member variables and member functions)
to be private are only valid in this class.

One of the commonly used ones:
privatize member variables and provide corresponding set and get methods to access them. Improve security for data access.

private : private, is a permission modifier. Used to modify members.
Private content is valid only within this class.
Note: Private is only one form of encapsulation.


  • Inheritance: Inheritance represents the hierarchical relationship between classes. The inheritance relationship enables objects of subclasses to share the state (attributes <non-private member variables>) and behaviors (methods <except constructors>) of parent class objects

For example:
parent class: Telphone

Click to view the code
package HOME9;

public class Telphone {
		
	    //2.定义属性(成员变量)
	    float screen;//屏幕
	   private float cpu;//cpu大小
	    float mem;//内存大小
	    //3.定义方法
	void call(){
	    System.out.println("Telphone有打电话的功能!");
	}
	void sendMessage(){
	   System.out.println("screen:"+ screen + "cpu:"+ cpu + "mem:"+ mem +"Telphone有发短信的功能");
	}

}


Subclass: iPhone Click to view the code
package HOME9;

public class iPhone extends Telphone {



}

test:

public static void main(String[] args) {
		iPhone apple = new iPhone();
		//子类可以继承父类非private属性(成员变量)和方法(非构造方法)
		//apple.cpu =5;如果有此行,则报错‘The field Telphone.cpu is not visible’
		apple.mem = 6;
		apple.screen = 7;
			
		apple.call();
		apple.sendMessage();
		

	}

result:
image

Polymorphism: Polymorphism means that behavior methods with the same name can have different implementations in different classes. While the subclass inherits the parent class, the method implementation of the class can be expanded or modified to make the method of the same name of the subclass more suitable for the objects of the subclass

Necessary conditions for the realization of polymorphism: (key points to write down)

  • There is an inheritance relationship
  • Existence method override
  • Parent class references point to subclass objects

Advantages of polymorphism:

  • simplifies the code
  • Improved maintainability and scalability

For example:

Click to view the code
public class DuoTaiDemo01 {
	public static void main(String[] args) {
		Man m = new Doctor();
		m.cut();
		
		m = new Director();
		m.cut();
		
		m = new Hairdresser();
		m.cut();
	}
}

class Man {
	public void cut() {
		System.out.println("我是man, 我也不知道怎么cut");
	}
}

class Doctor extends Man {
	public void cut() {
		System.out.println("动手术");
	}
}

class Director extends Man {
	@Override
	public void cut() {
		System.out.println("暂停");
	}
}

class Hairdresser extends Man {
	@Override
	public void cut() {
		System.out.println("剪头发");
	}
}

Here comes the important point, take notes

Features of polymorphic access members:

Father father = new Son()

Left Type———Right Type

Member variables:

  1. Look at the type on the left during compilation, if there is no variable in the type on the left, an error will be reported when compiling
  2. Look at the type on the left during runtime, the value of the variable on the left is the result of the operation
  3. Compile and look at the left, execute and look at the left

Member method:

Compile to the left, execute to the right

Construction method:

1. Polymorphic access to subclass constructors will first access parent class constructors

2. Help subclasses initialize members inherited from parent classes

static method:

Compile and look at the left, execute and look at the left

The example code is as follows:

package HOME9;

public class DuoTaiDemo02 {
	public static void main(String[] args) {
		Fu fu = new Zi();
		System.out.println(fu.num); // 10
		fu.method();
		
		fu.show();
	}
}

class Fu {

	int num = 10;

	public void method() {
		System.out.println("Fu.method()");
	}
	
	public static void show() {
		System.out.println("Fu.show");
	}
}

class Zi extends Fu {

	int num = 20;

	@Override
	public void method() {
		System.out.println("Zi.method()");
	}
	
	public static void show() {
		System.out.println("Zi.show");
	}
	
}

result:
image

Upcasting (automatic transition)

Format: <parent type> <reference variable name> = new <subtype>();
Features:
the subclass is converted to the parent class, and the reference of the parent class points to the subclass object. It can be understood as automatic type conversion (and automatic type conversion are two concepts).
At this time, the method called by the parent class reference variable is the method of the subclass overriding or inheriting the parent class.
At this time, the subclass specific attributes and methods cannot be called through the parent class reference variable.

Solution (instanceof + downcast)

downcasting (casting)

Format: <subtype> <reference variable name> = (<subtype> )<reference variable of parent type>;
Features:
parent class is converted to subclass, parent class reference is converted to subclass object. It can be understood as mandatory type conversion.
In the process of downcasting, if it is not converted to the real subclass type, a type conversion exception will occur

Exception name: Type conversion exception java.lang.ClassCastException
Cause: In the process of downcasting, it is not converted into a real type
Solution: Make a type judgment before each downcasting

The syntax of type judgment: instanceof
left object instanceof class name The result of this expression is boolean type
to test whether the object on its left is an instance of the class on its right

The disadvantages of polymorphism can be solved by using the instanceof keyword + downcasting.
We know that we need to judge all subclasses of the parent class one by one, which violates the principle of opening and closing.
We can continue to develop for the principle of opening and closing, but what if the parent class reference is Object? It cannot be judged
one by one, and there are consistent security risks. It can be considered generic.

Example 1 code is as follows:

package HOME9;

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

		Car c = new Benz();
		c.run();
		
		c = new BYD();
		c.run();
		
		if (c instanceof Benz) {
			Benz benz = (Benz) c;
			benz.leakOli();
		} else if (c instanceof BMW) {
			BMW b = (BMW) c;
			b.fillOil();
		} else  if (c instanceof BYD) {
			BYD byd = (BYD) c;
			byd.electric();
		}
		
		Object obj = new BMW();
		
	}
}

class Car {
	public void run() {
		System.out.println("Car.run()");
	}
}

class BMW extends Car {
	@Override
	public void run() {
		System.out.println("BMW.run()");
	}
	
	public void fillOil() {
		System.out.println("加油");
	}
}

class Benz extends Car {
	@Override
	public void run() {
		System.out.println("Benz.run()");
	}
	
	public void leakOli() {
		System.out.println("漏油");
	}
}

class BYD extends Car {
	@Override
	public void run() {
		System.out.println("BYD.run()");
	}、*------*、
	
	public void electric() {
		System.out.println("充电");
	}
}

result:
image

Chapter 6: Polymorphism and Inner Classes

Polymorphism (Chapter 5 has written a bit too much, so I won’t write this chapter):

Main content (upcast, downcast, instanceof operator)


Abstract classes and abstract methods

Abstract class : It is an abstraction of concrete classes, which is used to complete the shared public design of the class framework. Concrete subclasses inherit and extend the public design (think like polymorphism ), and
abstract classes cannot instantiate objects
. 1. The use of abstract

When some methods of the parent class are uncertain, you can use the abstract keyword to modify the method [abstract method], and use abstract to modify the class [abstract class].

We all know that the parent class extracts the attributes and methods shared by the subclasses. Some of these attributes and methods have been clearly implemented, and some cannot be determined. Then we can define them as abstract and reuse them in later classes. In this way, the abstract class was born.

For example, if the parent class of "animal" is defined, the attributes of "animal name" and "animal age" have been specified, but the method of "animal call" is not clear, then "animal call" can be defined as an abstract method.

Therefore, the abstract class is to extract the same but uncertain things for future reuse. The purpose of defining an abstract class is to implement the abstract class in subclasses .
example:

package javastudy;

public class AbstractDemo1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }
}

// 这就是一个抽象类
abstract class Animal {
    String name;
    int age;

    // 动物会叫
    public abstract void cry(); // 不确定动物怎么叫的。定义成抽象方法,来解决父类方法的不确定性。抽象方法在父类中不能实现,所以没有函数体。但在后续在继承时,要具体实现此方法。
}

// 抽象类可以被继承
// 当继承的父类是抽象类时,需要将抽象类中的所有抽象方法全部实现。
class cat extends Animal {
    // 实现父类的cry抽象方法
    public void cry() {
        System.out.println("猫叫:");

    }
}

interface

Similar to abstraction, an interface is an abstraction of a class, indicating the functions of a class, and an interface describes a capability. For example, organizing a conference requires the reception of participants.

Interfaces are not classes. Interfaces are written in a similar way to classes, but they are different concepts. A class describes the properties and methods of an object. An interface contains the methods that a class implements.

Unless the class implementing the interface is an abstract class, the class defines all the methods in the interface .

Interfaces cannot be instantiated, but they can be implemented . A class that implements an interface must implement all the methods described in the interface, otherwise it must be declared as an abstract class. In addition, in Java, interface types can be used to declare a variable, they can be a null pointer, or be bound to an object that implements this interface.

The difference between interface and class and the characteristics of interface

Click here -> Java interface ( I didn't understand it )

The explanation in the textbook: the abstract class mainly embodies the design idea of ​​the class template, defines the general characteristics of its subclasses and some of the shared functions that have been realized recently. Abstract classes and subclasses realize the relationship between "general to special" ( is polymorphism a method, and abstract classes are the means to implement this method, including interfaces?? )

Default methods in interfaces (default)

public interface MyInterface {
     
    // 普通接口方法
     
    default void defaultMethod() {
        // 默认方法
    }
}
Why do we need default methods

Prior to Java8, interfaces could only have abstract methods. You cannot add new functionality to an existing interface without forcing all implementing classes to create implementations of the new method.

The reason for the addition of default methods in Java 8 is pretty obvious.

In a typical abstraction-based design, an interface has one or more implementing classes. The interface needs to add a method, and all implementations must add the implementation of this method. Otherwise the constraints of the interface are not satisfied.

Default interface methods are the solution to this problem. Adding a default method to an interface does not require modifying the implementation class, and the default method added to the interface is directly available in the implementation class.
For example:

Click to view the code
interface MobilePhone {
    /**
     * 获取手机品牌
     */
    String getBrand();

    /**
     * 获取手机颜色
     */
    String getColor();

    /**
     * 获取手机长度(毫米)
     */
    Double getLength();

    /**
     * 设置手机时间
     */
    default String setTime(String newTime) {
        return "time set to " + newTime;
    }

    /**
     * 对getLength方法进行拓展,返回厘米为单位的长度
     */
    default String getLengthInCm() {
        return getLength() / 10 + "cm";
    }
}
Click to view the code
public class DefaultTests implements MobilePhone {
    @Override
    public String getBrand() {
        return "iphone";
    }

    @Override
    public String getColor() {
        return "red";
    }

    @Override
    public Double getLength() {
        return 150.00;
    }

    @Test
    public void defaultTest() {
        System.out.println(setTime("8:00 am"));
        System.out.println(getLengthInCm());
    }
}
result:

image

static method in interface

Static methods in interfaces, like static methods defined in classes, do not belong to specific objects, so they are not part of the api that implements the interface, and must be called using InterfaceName.staticMethod.

To understand how static methods work in interfaces, let's look at an example:

interface NewInterface { 
  
    // 静态方法
    static void hello() 
    { 
        System.out.println("Hello, New Static Method Here"); 
    } 
  
    // 抽象方法 
    void overrideMethod(String str); 
} 
  
// 实现类
public class InterfaceDemo implements NewInterface { 
  
    public static void main(String[] args) 
    { 
        InterfaceDemo interfaceDemo = new InterfaceDemo(); 
  
        // 调用接口静态方法 
        NewInterface.hello(); 
  
        // 调用被覆写后抽象方法 
        interfaceDemo.overrideMethod("Hello, Override Method here"); 
    } 
  
    // 实现接口方法
    @Override
    public void overrideMethod(String str) 
    { 
        System.out.println(str); 
	}
Why interfaces support static methods

The idea behind static methods in interfaces is to provide a simple mechanism that allows for the cohesion of related methods in an interface without having to create new objects.

Abstract classes can do the same thing. The main difference is that abstract classes can have constructors, member variables, and methods.

It is recommended to put static utility methods that are only related to the interface in the interface (to improve cohesion), instead of creating some additional utility classes to place these methods.

inner class

In Java, a class can nest another class, the syntax is as follows:

class OuterClass {   // 外部类
    // ...
    class NestedClass { // 嵌套类,或称为内部类
        // ...
    }
}

To access the inner class, you can do this by creating an object of the outer class and then creating an object of the inner class.

There are two types of nested classes:

  • non-static inner class
  • static inner class
non-static inner class

A non-static inner class is a class nested within another class. It has access to members of the outer class, often referred to as an inner class.

Since the inner class is nested in the outer class, you must first instantiate the outer class and then create an object of the inner class to implement it.
Example:

Click to view the code
class OuterClass {
  int x = 10;

  class InnerClass {
    int y = 5;
  }
}

public class MyMainClass {
  public static void main(String[] args) {
    OuterClass myOuter = new OuterClass();
    OuterClass.InnerClass myInner = myOuter.new InnerClass();
    System.out.println(myInner.y + myOuter.x);
  }
}
The output of the above example execution is:

image
Private inner class
The inner class can be decorated with private or protected, if you don't want the inner class to be accessed by the outer class, you can use the private modifier:

Example:

Click to view the code
class OuterClass {
  int x = 10;

  private class InnerClass {
    int y = 5;
  }
}

public class MyMainClass {
  public static void main(String[] args) {
    OuterClass myOuter = new OuterClass();
    OuterClass.InnerClass myInner = myOuter.new InnerClass();
    System.out.println(myInner.y + myOuter.x);
  }
}
Error:

image
Error message 'The type OuterClass.InnerClass is not visible'

static inner class

Static inner classes can be defined using the static keyword, we do not need to create an outer class to access static inner classes, we can access it directly:
instance:

Click to view the code
class OuterClass {
  int x = 10;

  static class InnerClass {
    int y = 5;
  }
}

public class MyMainClass {
  public static void main(String[] args) {
    OuterClass.InnerClass myInner = new OuterClass.InnerClass();
    System.out.println(myInner.y);
  }
}
The output of the above example execution is:

image

image
It seems that there is an anonymous inner class , I don’t understand

Chapter 7: Java common classes and enumeration classes

Commonly used classes: object class , String class , StringBuilder class, StringBuffer class , Math class , Random class , Calendar class , SimpleDateFormat class , enumeration class

object class


image

String class


image

StringBuilder and StringBuffer classes


image

Math class


image

Random class


image

Calendar class and Date class and SimpleDateFormat class


image

enum class


image

Chapter 8: Regular Expressions and Exception Handling

regular expression

Regular expressions define patterns of strings.

Regular expressions can be used to search, edit or process text.

Regular expressions are not limited to one language, but there are subtle differences in each language.

exception handling


Declare custom exceptions

In Java you can customize exceptions. Here are a few things to keep in mind when writing your own exception classes.

  • All exceptions must be a subclass of Throwable.
  • If you want to write a checked exception class, you need to inherit the Exception class.
  • If you want to write a runtime exception class, you need to inherit the RuntimeException class.

You can define your own exception class like this:

		class MyException extends Exception{
		}

The exception class created by inheriting the Exception class is a checked exception class.
The following InsufficientFundsException class is a user-defined exception class that inherits from Exception.
An exception class is like any other class, containing variables and methods.

**Example:** The following example is a simulation of a bank account. The identification is completed through the bank card number, and the operation of depositing and withdrawing money can be performed.

InsufficientFundsException.java file code

Click to view the code
// 文件名InsufficientFundsException.java
import java.io.*;
 
//自定义异常类,继承Exception类
public class InsufficientFundsException extends Exception
{
  //此处的amount用来储存当出现异常(取出钱多于余额时)所缺乏的钱
  private double amount;
  public InsufficientFundsException(double amount)
  {
    this.amount = amount;
  } 
  public double getAmount()
  {
    return amount;
  }
}
To show how to use our custom exception class,

The CheckingAccount class below contains a withdraw() method that throws an InsufficientFundsException.

CheckingAccount.java file code:

Click to view the code
// 文件名称 CheckingAccount.java
import java.io.*;
 
//此类模拟银行账户
public class CheckingAccount
{
  //balance为余额,number为卡号
   private double balance;
   private int number;
   public CheckingAccount(int number)
   {
      this.number = number;
   }
  //方法:存钱
   public void deposit(double amount)
   {
      balance += amount;
   }
  //方法:取钱
   public void withdraw(double amount) throws
                              InsufficientFundsException
   {
      if(amount <= balance)
      {
         balance -= amount;
      }
      else
      {
         double needs = amount - balance;
         throw new InsufficientFundsException(needs);
      }
   }
  //方法:返回余额
   public double getBalance()
   {
      return balance;
   }
  //方法:返回卡号
   public int getNumber()
   {
      return number;
   }
}
The BankDemo program below demonstrates how to call the deposit() and withdraw() methods of the CheckingAccount class.

BankDemo.java file code:

//文件名称 BankDemo.java
public class BankDemo
{
   public static void main(String [] args)
   {
      CheckingAccount c = new CheckingAccount(101);
      System.out.println("Depositing $500...");
      c.deposit(500.00);
      try
      {
         System.out.println("\nWithdrawing $100...");
         c.withdraw(100.00);
         System.out.println("\nWithdrawing $600...");
         c.withdraw(600.00);
      }catch(InsufficientFundsException e)
      {
         System.out.println("Sorry, but you are short $"
                                  + e.getAmount());
         e.printStackTrace();//将错误行打印出来,exception中的一个方法
      }
    }
}

Compile the above three files and run the program BankDemo, the result is as follows:
image

catch exception

Exceptions can be caught using the try and catch keywords. Try/catch code blocks are placed where exceptions may occur.

The code in the try/catch code block is called protected code, and the syntax for using try/catch is as follows:

		try
		{
			 // 程序代码
		}catch(ExceptionName e1)
		{
 			  //Catch 块
		}
	或者 多重捕获:异常子类在上,父类在下
try{
// 程序代码
}catch(异常类型1 异常的变量名1){
 // 程序代码
}catch(异常类型2 异常的变量名2){
 // 程序代码
}catch(异常类型3 异常的变量名3){
 // 程序代码
}

Example :

Click to view the code
public class ExcepTest{
  public static void main(String args[]){
    int a[] = new int[2];
    try{
       System.out.println("Access element three :" + a[3]);
    }catch(ArrayIndexOutOfBoundsException e){
       System.out.println("Exception thrown  :" + e);
    }
    finally{
       a[0] = 6;
       System.out.println("First element value: " +a[0]);
       System.out.println("The finally statement is executed");
    }
  }
}
result:

image
Note the following:

  • catch cannot exist independently of try.
  • It is not mandatory to add a finally block after the try/catch.
  • There cannot be neither a catch block nor a finally block after the try code.
  • No code can be added between try, catch, finally blocks.

over! It’s too time-consuming, I hope I can use it in the future. There are many uses in the essay (~~most of them are copied~~), one of the purposes of writing this essay is to sort out what I really need on the Internet at this stage! The problem now is that I have too little code experience and can’t use these things. I hope that after the practical class, I will have a deeper understanding and application. After all, I haven’t used it before, so I don’t have the confidence to write something that I really think

2021-10-24 19:04:39 Sunday> The main content of this article comes from,

Rookie tutorial ,
W3SCHOOL.COM
https://blog.csdn.net/zhouym_/article/details/89421577
https://www.cnblogs.com/ibelieve618/p/6410910.html
https://www.cnblogs.com/wuhenzhidu/p/anonymous.html https://blog.csdn.net/qq_39 754721/article/details/94736251 https://www.cnblogs.com/weink1215/p/4433790.html https://blog.csdn.net/weixin_42110638/article/details/85467987
"
Introduction to Java Project Case Development"—Tsinghua Press

Guess you like

Origin blog.csdn.net/qq_25218219/article/details/120938674