[java] Chapter 8: quick recall

Keywords: Java

Unconsciously, Java has been learned for nearly two months. The textbook also slowly turned to Chapter 8. I always felt that I didn't learn anything. I always wanted to stop and tidy up. Today is the day

October 23, 2021 09:38:03 Saturday

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

Learn confused, no code experience, sort out and extract some theoretical things for your own reference, there will be mistakes

Chapter I

Simple understanding of java

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

working principle
It 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
More specific, Introduction to Baidu java

Basic steps to build a java development environment:

Click - > Basic steps for Baidu to build a java development environment
Go and see for yourself; It's easy to follow step by step.

Chapter 2: basic data types and operations

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

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 and 1 represents negative;
  • Byte occupies one byte, indicating the range: - ~ 2 ^ 7-1, i.e. - 128 ~ 127
  • short takes up two bytes and represents the range – ~ 2 ^ 15-1
  • int takes four bytes, indicating the range: - ~ 2 ^ 31-1
  • long takes up eight bytes and represents the range: - ~ 2 ^ 63-1
  • float takes four bytes and double eight bytes
  • Char takes up two bytes. A char represents a unicode code. The range is 0 ~ 2 ^ 16
  • boolean takes up one byte and has only two values: true and false

The usage and usage notes are similar to those of c language, including but not limited to (type conversion and operation, implicit type conversion, explicit type conversion), etc.

java operator

Off 1: arithmetic operator

Click to view the code
package step1;
import java.util.Scanner;
public class Cal {
	public static void main(String[] args) {
		/*********start*********/
		 System.out.println("Please enter the first integer");
         System.out.println("Please enter the second integer");
		 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("The result of adding two numbers is:"+c);
		System.out.println("The result of subtracting two numbers is:"+d);
		System.out.println("The result of multiplying two numbers is:"+e);
		System.out.println("The result of dividing two numbers is:"+f);
		System.out.println("The result of the remainder of the two numbers is:"+g);
		/*********end*********/
	}

}

Test case:

Level 2: relational operators

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

}

Input data in the first test: 20,34;
Need your program output:

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

Off 3: logical operators

What are logical operators
Logical operators are used to test the logical relationship between two operands, and the two operands must be boolean (such as relational expressions), and the results obtained are also boolean. Variables or expressions with boolean results connected by logical operators are called logical expressions

We can understand logical operators from the perspective of "voting":
And: require everyone to vote to pass an issue;
Or: only one person is required to vote to pass a topic;
Non: a person's original voting consent, through the non operator, can invalidate his vote;
XOR: an issue can be passed only if there is and only one person votes for it

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 priority

java specific operator (instanceceof) < I don't know if it's unique. See you at once anyway >

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

		obj instanceof String
		Among them, obj Is an instance of a pair of images, if obj yes string Type instance, the operation result is true,Otherwise false. 

String, java class, storage string type, Chapter 7

2.5 practice

1. Output the value range of java basic data type

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 variable min is encapsulated in the wrapper class_ Value and MAX_VALLUE represents the minimum and maximum values that can be represented by the basic data type respectively.

Click to view the code
public class HOME {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("Boolean Maximum: true" +"Minimum: flase");    //It doesn't seem to be written like that here. Whatever, just know. I'm not very good at writing code
		System.out.println("byte Value range of:");
		System.out.println(Byte.MIN_VALUE+"~"+Byte.MAX_VALUE);
		System.out.println("Character Value range of:");
		System.out.println((int)Character.MIN_VALUE+"~"+(int)Character.MAX_VALUE);
		System.out.println("short Value range of:");
		System.out.println(Short.MIN_VALUE+"~"+Short.MAX_VALUE);
		System.out.println("Integer Value range of:");
		System.out.println(Integer.MIN_VALUE+"~"+Integer.MAX_VALUE);
		System.out.println("Long Value range of:");
		System.out.println(Long.MIN_VALUE+"~"+Long.MAX_VALUE);
		System.out.println("Float Value range of:");
		System.out.println(Float.MIN_VALUE+"~"+Float.MAX_VALUE);
		System.out.println("Double Value range of:");
		System.out.println(Double.MIN_VALUE+"~"+Double.MAX_VALUE);

	}

}

Chapter 3: structured programming (process oriented programming)

  • Sequential structure

  • Branching structure

  • Cyclic structure

Like c, no more

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: array

Understand and learn to use all the contents in the figure below

Here it is Basic Java syntax (VI) -- definition and use of array , very specific, c language also applies

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

Basic concepts of object oriented

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

Examples (may not be correct):
Put the elephant in the fridge

Process oriented thinking:

  • Open the refrigerator
  • Put in the elephant
  • Turn off the refrigerator

Object oriented thinking:

  • Open the refrigerator
  • Refrigerator storage
  • Refrigerator off


Next, let's start with the object to understand all the contents in the above figure,

1. Definition of object

meaning

An object is an instance of a class and has specific state behavior. For example, Student is a class (describing the common state and behavior of similar objects), and object refers to a specific Student individual. The object is dynamic, and each object has a dynamic process from creation, running to extinction. At the same time, the object also occupies memory space to store the state data of the object, that is, member variables. (for example, Wen Hai's height < member variable > < Object >)

		//Definition method: class name object name;
		//Or class name object name = new class name (parameter list);
		Student a;
		Student a = new Student();

form

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's nothing to say. Templates are classes. Let's introduce classes

What is a class: a class is not an entity. For example, the mobile phone is not an entity. For example, the iPhone 7 is an entity, and the mobile phone is not. The class is just a model to determine the characteristics (attributes) and behaviors (Methods) of the object
Class composition: properties and methods (if you see this from above, you won't have any questions about it)
Class definition method:

		Define class name public class Class name{
		//[initialization module]( https://www.cnblogs.com/wp456/p/3233186.html  Definition of "initialization module") [initialization module is executed first]

		 //Defines the part of the attribute (member variable)

			Write type property 1 of class property 1;

			Type of property 2;

		 	..........

			attribute n Type properties for n;

		//Define the part of the method (behavior);

			Write method 1 of class;

			Method 2;

			 ........

			method n;
		}

For example: definition of mobile phone class:

Click to view the code
public class Telphone {//1. Define a class
	
    //2. Define attributes (member variables)
    float screen;//screen
    float cpu;//cpu size
    float mem;//Memory size
    //3. Definition method
void call(){
    System.out.println("Telphone It has the function of making phone calls!");
}
void sendMessage(){
   System.out.println("screen:"+ screen + "cpu:"+ cpu + "mem:"+ mem +"Telphone It has the function of sending text messages");
}
}

The difference between member variables and local variables is similar to that of c, but I will not repeat it, but the modifier needs to be mastered

characteristic

  • Encapsulation: encapsulation is an information shielding technology, which combines the state and behavior of the object into an independent module to hide the internal details of the object as much as possible (including the internal private state of the object and the specific implementation of the behavior). The purpose of encapsulation is to separate the designer and user of the object. As a user, he does not need to understand the implementation details of the object, but only needs to use the behavior methods provided by the designer to realize the functions.

private keyword
Is a permission modifier.
Used to decorate members (member variables and member functions)
Privatized members are only valid in this class.

One of the common:
Privatize the member variable, provide the corresponding set externally, and access it with the get method. Improve the security of data access.

Private: private. It is a permission modifier. Used to decorate members.
Private content is only valid in this class.
Note: private is only an embodiment of encapsulation.

  • Inheritance: inheritance represents the hierarchical relationship between classes. The inheritance relationship enables the objects of the subclass to share the state (property < non private member variable >) and behavior (method < except constructor >) of the parent object

For example:
Parent class: Telphone

Click to view the code
package HOME9;

public class Telphone {
		
	    //2. Define attributes (member variables)
	    float screen;//screen
	   private float cpu;//cpu size
	    float mem;//Memory size
	    //3. Definition method
	void call(){
	    System.out.println("Telphone It has the function of making phone calls!");
	}
	void sendMessage(){
	   System.out.println("screen:"+ screen + "cpu:"+ cpu + "mem:"+ mem +"Telphone It has the function of sending text messages");
	}

}


Subclass: iPhone Click to view code
package HOME9;

public class iPhone extends Telphone {



}

Test:

public static void main(String[] args) {
		iPhone apple = new iPhone();
		//Subclasses can inherit non private attributes (member variables) and methods (non constructor methods) of the parent class
		//apple.cpu =5; If there is this line, the error "The field Telphone.cpu is not visible" will be reported
		apple.mem = 6;
		apple.screen = 7;
			
		apple.call();
		apple.sendMessage();
		

	}

result:

Polymorphism: polymorphism refers to the behavior method with the same name, which can have different implementations in different classes. While the subclass inherits the parent class, the method implementation of the class can be extended or modified to make the method with the same name of the subclass more suitable for the object of the subclass

Necessary conditions for the realization of polymorphism: (key points to be noted)

  • There is an inheritance relationship
  • Method override exists
  • A parent class reference points to a child class object

Advantages of polymorphism:

  • Simplified 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("I am man, I don't know how cut");
	}
}

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

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

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

Here's the point. Take notes

Characteristics of polymorphic access members:

Father father = new Son()

Left type - right type

Member variables:

  1. During compilation, look at the type on the left. If there are no variables in the type on the left, an error will be reported during compilation
  2. At run time, you can see the left type. The value of the variable of the left type is the result of the run
  3. Compile to the left, execute to the left

Member method:

Compile to the left and execute to the right

Construction method:

1. The polymorphic access subclass constructor will access the parent class constructor first

2. Help the subclass initialize the members inherited from the parent class

Static method:

Compile to the left, execute to 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:

Upward transformation (automatic transformation)

Format: < parent type > < reference variable name > = new < subtype > ();
characteristic:
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 completely two concepts)
At this time, the method called through the parent class reference variable is the method that the child class overrides or inherits the parent class
At this time, the child class specific properties and methods cannot be called by referencing variables through the parent class
Solution (instanceof + downward transformation)

Downward transformation (forced conversion)

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

Exception Name: type conversion exception java.lang.ClassCastException
Cause: in the process of downward transformation, it is not converted to the real type
Solution: make a type judgment before each downward transformation

Syntax of type judgment: instanceof
The object instanceof class name on the left. The result of this expression is boolean type
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 instanceof keyword + downward transformation
We know that we need to judge all subclasses of the parent class one by one, which violates the opening and closing principle
We can continue to develop for the open close principle, but what if the parent class reference is Object?
It is impossible to make a judgment one by one. Security risks exist consistently. It can be considered to be 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("come on.");
	}
}

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

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

result:

Chapter 6: polymorphism and inner class

Polymorphism (Chapter 5 is a little too much, so this chapter will not be written):

Main contents (up transformation, down transformation, instanceof operator)

Abstract classes and abstract methods

Abstract class: it is an abstraction of a specific class, which is used to complete the shared public design of the class framework. The specific subclass inherits and extends the public design (think it is polymorphic),
Abstract classes cannot instantiate objects
1, Use of abstract

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

As we all know, the parent class extracts the attributes and methods jointly owned by the child classes. Some of these attributes and methods have been explicitly implemented, and some cannot be determined. Then we can define them as abstractions and reuse them in the future. In this way, abstract classes are born.

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

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

package javastudy;

public class AbstractDemo1 {

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

    }
}

// This is an abstract class
abstract class Animal {
    String name;
    int age;

    // Animals call
    public abstract void cry(); // I'm not sure what animals call. It is defined as an abstract method to solve the uncertainty of parent method. Abstract methods cannot be implemented in the parent class, so there is no function body. However, it is necessary to implement this method in subsequent inheritance.
}

// Abstract classes can be inherited
// When the inherited parent class is an abstract class, you need to implement all the abstract methods in the abstract class.
class cat extends Animal {
    // cry abstract method for implementing parent class
    public void cry() {
        System.out.println("Cat barking:");

    }
}

Interface

Interface is similar to abstraction. It is an abstraction of a class, indicating the functions of the class. Interface describes a capability. For example, organizing a meeting has the need to receive participants.

Interfaces are not classes. The way of writing interfaces is very similar to classes, but they belong to different concepts. Class describes the properties and methods of an object. Interface contains the methods to be implemented by the class.

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

The interface cannot be instantiated, but it 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 become a null pointer or be bound to an object implemented by this interface.

Differences between interfaces and classes and characteristics of interfaces

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

Textbook explanation: abstract classes mainly reflect the design idea of class templates, define the general characteristics of their subclasses and some common functions that have been realized. Abstract classes and subclasses realize the relationship between "general to special" (is polymorphism a method, and abstract classes are the means to realize this method, including interfaces?)

Default method in interface (default)

public interface MyInterface {
     
    // Common interface method
     
    default void defaultMethod() {
        // Default method
    }
}
Why do I need a default method

Before Java 8, interfaces could only have abstract methods. You cannot add new functionality to an existing interface without forcing all implementation classes to create implementations of new methods.

The reason for the new default method in Java 8 is obvious.

In a typical abstract based design, an interface has one or more implementation classes. Methods should be added to the interface, and the implementation of this method should be added to all implementations. Otherwise, the constraints of the interface will not be satisfied.

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

Click to view the code
interface MobilePhone {
    /**
     * Get mobile phone brand
     */
    String getBrand();

    /**
     * Get phone color
     */
    String getColor();

    /**
     * Get phone length (mm)
     */
    Double getLength();

    /**
     * Set phone time
     */
    default String setTime(String newTime) {
        return "time set to " + newTime;
    }

    /**
     * Expand the getLength method and return the length in centimeters
     */
    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:

Static methods in interfaces

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

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

interface NewInterface { 
  
    // Static method
    static void hello() 
    { 
        System.out.println("Hello, New Static Method Here"); 
    } 
  
    // Abstract method 
    void overrideMethod(String str); 
} 
  
// Implementation class
public class InterfaceDemo implements NewInterface { 
  
    public static void main(String[] args) 
    { 
        InterfaceDemo interfaceDemo = new InterfaceDemo(); 
  
        // Calling interface static methods 
        NewInterface.hello(); 
  
        // Call overridden abstract method 
        interfaceDemo.overrideMethod("Hello, Override Method here"); 
    } 
  
    // Implementation interface method
    @Override
    public void overrideMethod(String str) 
    { 
        System.out.println(str); 
	}
Why does the interface support static methods

The idea behind the static methods in the interface is to provide a simple mechanism that allows the cohesion of related methods in the interface without creating 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 related only to the interface in the interface (improve cohesion), without creating additional utility classes to place these methods.

Inner class

Another Java class can be nested in one class. The syntax format is as follows:

class OuterClass {   // External class
    // ...
    class NestedClass { // Nested classes, or inner classes
        // ...
    }
}

To access the inner class, you can create an object of the outer class, and then create 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 external class members and is often called an internal class.

Because the inner class is nested in the outer class, you must first instantiate the outer class, and then create the 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 execution output of the above example is:


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);
  }
}
report errors:


The type OuterClass.InnerClass is not visible‘

Static inner class

Static internal classes can be defined using the static keyword. We do not need to create external classes to access static internal classes. We can access them directly:
example:

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 execution output of the above example is:


There seems to be another one Anonymous Inner Class , I don't understand

Chapter 7: java common classes and enumeration classes

Common classes: object class,String class,StringBuilder class, StringBuffer class,Math class,Random class,Calendar Class,SimpleDateFormat class,Enumeration class

object class

String class

StringBuilder and StringBuffer classes

Math class

Random class

Calendar Class and Date class and SimpleDateFormat class

Enumeration class

Chapter 8: regular expressions and exception handling

regular expression

Regular expressions define the pattern 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 exception

In Java, you can customize exceptions. When writing your own exception class, you need to keep the following points in mind.

  • All exceptions must be subclasses of Throwable.
  • If you want to write a checking 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 as follows:

		class MyException extends Exception{
		}

The Exception class created by inheriting the Exception class is a checking Exception class.
The following InsufficientFundsException class is a user-defined Exception class, which inherits from Exception.
An exception class, like any other class, contains 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 saving and withdrawing money can be carried out.

InsufficientFundsException.java file code

Click to view the code
// File name InsufficientFundsException.java
import java.io.*;
 
//Custom Exception class, inheriting Exception class
public class InsufficientFundsException extends Exception
{
  //The amount here is used to store the money that is lacking when an exception occurs (when the withdrawal money is more than the balance)
  private double amount;
  public InsufficientFundsException(double amount)
  {
    this.amount = amount;
  } 
  public double getAmount()
  {
    return amount;
  }
}
To show how to use our custom exception class,

Include a withraw () method in the CheckingAccount class below and throw an InsufficientFundsException exception.

CheckingAccount.java file code:

Click to view the code
// File name CheckingAccount.java
import java.io.*;
 
//Such simulated bank accounts
public class CheckingAccount
{
  //Balance is the balance and number is the card number
   private double balance;
   private int number;
   public CheckingAccount(int number)
   {
      this.number = number;
   }
  //Method: save money
   public void deposit(double amount)
   {
      balance += amount;
   }
  //Method: withdraw money
   public void withdraw(double amount) throws
                              InsufficientFundsException
   {
      if(amount <= balance)
      {
         balance -= amount;
      }
      else
      {
         double needs = amount - balance;
         throw new InsufficientFundsException(needs);
      }
   }
  //Method: return balance
   public double getBalance()
   {
      return balance;
   }
  //Method: return card number
   public int getNumber()
   {
      return number;
   }
}
The following BankDemo program demonstrates how to call the deposit() and withraw () methods of the CheckingAccount class.

BankDemo.java file code:

//File name 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();//Print out the error line, a method in exception
      }
    }
}

Compile the above three files and run the BankDemo program. The results are as follows:

Catch exception

Use the try and catch keywords to catch exceptions. try/catch code blocks are placed where exceptions can occur.

The code in the try/catch code block is called protection code. The syntax of using try/catch is as follows:

		try
		{
			 // Program code
		}catch(ExceptionName e1)
		{
 			  //Catch block
		}
	Or multiple capture: the abnormal subclass is above and the parent class is below
try{
// Program code
}catch(Variable name of exception type 1){
 // Program code
}catch(Variable name of exception type 2){
 // Program code
}catch(Variable name of exception type 3){
 // Program code
}

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:


Note the following:

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

Over! It takes too much time. I hope I can use it in the future. There are many essays (~ ~ in fact, most of them are copied ~ ~). One of the purposes of writing this essay is to sort out what I really need at this stage on the Internet! Now the problem is that I have too little code experience to use these things. I hope I will have a deeper understanding and application after the practice class. After all, if I haven't used it, I don't have the confidence to write what 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_39754721/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 Publishing House

Posted by Round on Sun, 24 Oct 2021 03:26:10 -0700