[java basics] static Single case design pattern Math class Arrays class

static keyword

Variables, methods, code blocks and internal classes used for modification (not involved for the time being). The modified members belong to the class, not just
It belongs to an object. In other words, since it belongs to a class, it can be called without creating an object.

Class variable

When static modifies a member variable, the variable is called a class variable. Each object of this class shares the value of the same class variable. Any object can change the value of the class variable, but you can also operate on the class variable without creating the object of the class.

  • Static variable: a variable declared in a class, outside a method, and decorated with static

    • Data type modifier: static;

    • Meaning: static variables no longer belong to the object itself, but to the class. Static variables will be shared by all objects created through this class

    • Calling method:

      Class name Static variable

    • characteristic:

      • 1. Static variables no longer belong to the object itself, but to the class. Static variables will be shared by all objects created through this class
      • 2. The life cycle of static variables is loaded with the loading of classes and disappears with the disappearance of classes, and only loaded once (once there is a bytecode file in the method area, it will not be loaded for the second time, and the original bytecode file will continue to be used)
public class StaticDemo01 {
	public static void main(String[] args) {
		//Create student object
		Student s1 = new Student("Guo Jing", 18);
		Student s2 = new Student("Huang Rong", 16);
		Student s3 = new Student("master hongqi", 50);
		Student.classroom = "zero ";

		//Print student information
		System.out.println(s1.print());
		System.out.println(s2.print());
		System.out.println(s3.print());

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

		//Considering that the three children's shoes are excellent, we will transfer them to another class
		//s1.classroom = "divine carving";
		Student.classroom = "Divine carving";

		//Print student information
		System.out.println(s1.print());
		System.out.println(s2.print());
		System.out.println(s3.print());

	}
}

public class Student {
	String name;
	int age;
	static String classroom;

	public Student(String name, int age) {
		this.name = name;
		this.age = age;
		//this.classroom = classroom;
	}

	public Student() {
	}

	public String print () {
		return name + "=" + age + "=" + classroom;
	}
}

Memory diagram of static variables

Three variables

Local variable: a variable declared inside or on a method declaration

Instance variable: a variable declared outside the method in the class and not decorated with static keyword

Static variable: a variable declared outside a method in a class and decorated with the static keyword

difference:

  • Different locations in the code
    • Local variable: inside a method or on a method declaration
    • Instance variable: outside method in class
    • Static variable: outside method in class
  • Different locations in memory
    • Local variables: stack memory
    • Instance variable: heap memory
    • Static variables: heap memory
  • The default value of the variable is different
    • Local variable: no default value
    • Instance variable: has default value
    • Static variables: have default values
  • The scope in the code is different
    • Local variables: in method
    • Instance variables: in instances
    • Static variables: in classes
  • The life cycle in memory is different
    • Local variables: load with the method call and disappear with the method out of the stack
    • Instance variable: loads as the object is created and disappears as the object is recycled
    • Static variables: load as the class is loaded and disappear as the class disappears
  • Variable loading times are different
    • Local variable: the variable will be loaded every time the method of the local variable is called
    • Instance variable: the variable will be loaded every time the object of the instance variable is created
    • Static variables: because bytecode files are loaded only once, static variables are loaded only once

practice:

Assign student numbers to students

public class Student {
	private String name;
	private int age;
	private int id;
	private static int num = 210726001;

	public Student(String name, int age) {
		this.name = name;
		this.age = age;
		//this.id = num++;
	}

	public Student() {
		//this.id = num++;
	}

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

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

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String print () {
		return name + "=" + age + "=" + id;
	}

	{
		this.id = num++;
	}
}

public class StaticDemo03 {
	public static void main(String[] args) {
		//Create student object
		Student s1 = new Student("Delireba", 18);
		Student s2 = new Student("Gulinaza", 20);
		Student s3 = new Student("Marzaha", 38);
		Student s4 = new Student();
		s4.setName("Andre Iguodala ");
		s4.setAge(35);

		//Print student information
		System.out.println(s1.print());
		System.out.println(s2.print());
		System.out.println(s3.print());
		System.out.println(s4.print());

	}
}

Static method

When a class has a large number of instance methods of tools, if you use these instance methods, you must create objects, and the objects have no other purpose except calling methods. When the main method does not end, the objects always exist in the heap memory, resulting in a waste of heap memory space. You can directly declare these instance methods as static methods. After declaration, the methods do not belong to the object itself, but directly belong to the class, Therefore, when using the method, you no longer need to create an object. You can call it directly through the class name

  • Format:

    Modifier static return value type method name () {}

  • Calling method:

    Class name Static method name ();

public class ArrayUtils {
	public static void printArr (int... arr) {
		if (arr == null) {
			return;
		}

		if (arr.length == 0) {
			System.out.println("array:[]");
			return;
		}
		System.out.print("array:[");
		for (int i = 0; i < arr.length; i++) {
			if (arr.length - 1 == i) {
				System.out.println(arr[i] + "]");
			} else {
				System.out.print(arr[i] + ", ");
			}
		}
 	}
}

public class StaticDemo04 {
	public static void main(String[] args) {
		/*//Create an array tool class object
		ArrayUtils au = new ArrayUtils();//Method area: ArrayUtils bytecode file heap memory: ArrayUtils object
		//Because there is directivity between au object and main(), au object will be considered as garbage data only when main() is out of the stack
		au.printArr(11,22,33);
		au.printArr(11,22,33,44);
		au.printArr(11,22,33,44,55);*/

		ArrayUtils.printArr(11,22,33); //Method area: ArrayUtils bytecode file
		ArrayUtils.printArr(11,22,33,44);
		ArrayUtils.printArr(11,22,33,44,55);
	}
}

Considerations for static methods

1. When a class needs to declare a large number of tool methods, while declaring these tool methods as static, it also needs to declare the constructor of the class as private. The outside world can no longer create objects and call the tool methods directly through the class name

2. Relationship between instance members and static members: instance members cannot be called in static methods, because static methods are loaded with class loading, and instance members are loaded with object creation. There is a possibility that instance members may not be loaded when static methods are loaded (class loading takes precedence over instance loading)

  • Invoke instance members in instance methods: true

  • Calling static members in instance methods: true

  • Calling static members in static methods: true

  • Invoke instance members in static methods: false

3. this keyword (and super keyword) cannot be used in static methods

public class StaticDemo05 {
	public static void main(String[] args) {
		//System.out.println(this);
	}

	//Example method
	public void method01 () {
		//method02();
	}

	//Example method
	public void method02 () {
		method03();
	}

	//Static method
	public static void method03 () {
		//method04();
	}

	//Static method
	public static void method04 () {
		//method01();
	}
}

Static block code

  • Location: member (outside method in class)

  • Format:

    ​ static {

    ​ }

  • characteristic:

    • 1. Load with class loading
    • 2. Load only once
  • effect:

    • 1. Encapsulate tool classes to initialize some variables
    • 2. Initialize static user-defined constants (explained in day11)
  • matters needing attention:

    • 1. Instance member cannot be called in static code block
    • 2. this keyword (and super keyword) cannot be used in static code blocks
public class Utils {
	int num = 10;

	static {
		System.out.println("Static block code");
		//System.out.println(this);
	}

	{
		System.out.println("Constructor code block");
	}
}

public class StaticDemo06 {
	public static void main(String[] args) {
		//Create tool class object
		new Utils();
		new Utils();
	}
}

Single case design mode

  • Single instance: a single instance

  • Algorithm: an optimization scheme for a process

  • Design pattern: a set of special solutions to solve a problem

  • Framework: semi finished product project

Singleton design pattern: a set of solutions for creating unique objects

Classification:

  • Immediate load mode (starving)
  • Delayed loading mode (lazy)

To load mode now:

  • 1. Privatization constructor
  • 2. Declare and initialize a unique object at the member position in the class
  • 3. In order to be accessible from the outside, the unique object is modified statically
  • 4. For the security of the unique object, the encapsulation idea is added and the unique object is privatized
  • 5. Provide external methods for "obtaining" unique objects

Delay loading mode steps:

  • 1. Privatization constructor
  • 2. Declare a unique object at the member position in the class
  • 3. In order to be accessible from the outside, the unique object is modified statically
  • 4. For the security of the unique object, the encapsulation idea is added and the unique object is privatized
  • 5. Provide external methods for "obtaining" unique objects. When obtaining for the first time, you need to create objects
public class CEO {
	//2. Create a unique object at the member position in the class
	//3. In order to be accessible from the outside, the unique object is modified statically
	//4. For the security of the unique object, the encapsulation idea is added and the unique object is privatized
	private static CEO ceo = new CEO();

	//1. Privatization constructor
	private CEO () {}

	//5. Provide external methods for "obtaining" unique objects
	public static CEO getCEO () {
		return ceo;
	}
}

public class Boss {
	//2. Declare a unique object at the member position in the class
	//3. In order to be accessible from the outside, the unique object is modified statically
	//4. For the security of the unique object, the encapsulation idea is added and the unique object is privatized
	private static Boss boss;

	//1. Privatization constructor
	private Boss () {}

	//5. Provide external methods for "obtaining" unique objects. When obtaining for the first time, you need to create objects
	public static Boss getBoss () {
		if (boss == null) {
			boss = new Boss();
		}
		return boss; 
	}
}

public class StaticDemo07 {
	public static void main(String[] args) {
		System.out.println(Boss.getBoss());
		System.out.println(Boss.getBoss());
		System.out.println(Boss.getBoss());
	}
}

import keyword

com.atguigu.imp.demo01.ImportDemo01.class

com. atguigu. imp.demo02. Student. Class (standard class)

  • Meaning: import package, import the classes under other packages into the current package

  • Format:

    import. * package name;

    Import all classes in the specified package

    import package name Class name;

    Imports the class specified in the specified package

  • Location:

    package > import > class

API documentation

com.atguigu.api.APIDemo.class

JDK_API_1.6_zh_ chinese. CHM

  • Review: classification of classes:

    • Custom class

    • Classes provided by API

  • Object oriented learning tips:

  1. See if there is a class that can help us do things. If so, if not, customize it
  2. Select the appropriate constructor to create the object of the class
  3. Complete the requirements through object calling methods
  • API documents can be queried through "class file name"

Class files: class,enum,interface

  • How to query API documents:
    • Characteristics of class
    • Class location
      • Note: if the class used is in Java Under Lang package, there is no need to import package. In addition, all other packages need to be imported, including Java Lang sub packages need to be guided
    • Class constructor
    • Class method

Overview of Scanner class

  • Class features: text scanner tool class for basic data types and string types

  • Class location: Java util

  • Class constructor: public Scanner(InputStream source)

    • Construct a new Scanner whose generated values are scanned from the specified input stream
    • Argument: system In (keyboard entry through console)
  • Class method

    public byte nextByte()

    Scan the next mark of the input information into a byte.

    public short nextShort()

    Scan the next mark of the input information into a short.

    public int nextInt()

    Scan the next mark of the input information as an int.

    public long nextLong()

    Scan the next mark of the input information as a long.

    public float nextFloat()

    Scan the next mark of the input information as a float.

    public double nextDouble()

    Scan the next mark of the input information into a double.

    public boolean nextBoolean()

    Scans the input tag interpreted as a Boolean value and returns that value.

    public String next()

    Find and return the next complete tag from this scanner.

    public String nextLine()

    This scanner executes the current line and returns skipped input information.

    public void close()

    Turn off this scanner.

be careful:

  1. The data type entered must correspond to the receiving type one by one
  2. The entered data must be within its value range
public class ScannerDemo01 {
	public static void main(String[] args) {
		//Create Scanner object
		Scanner sc = new Scanner(System.in);

		//Enter int type data with keyboard
		System.out.println("Please enter an integer on the keyboard:");
		int num = sc.nextInt();
		System.out.println("num = " + num);

		//close resource
		sc.close();
	}
}
  • Use the Scanner object to complete the input of string type

  • Disadvantages of next() and nextLine():

    Disadvantages of next(): it will not be scanned in case of blank symbols

    Disadvantages of nextLine(): because the method of scanning basic data types and "carriage return and line feed" are not recognized during next() scanning, non nextLine() cannot exist in front of nextLine()

public class ScannerDemo02 {
	public static void main(String[] args) {
		//Create Scanner object
		Scanner sc = new Scanner(System.in);

		//Keyboard entry
		System.out.println("Please enter your age on the keyboard");
		int age = sc.nextInt();
		System.out.println("age = " + age);
		System.out.println("Please enter your name on the keyboard:");
		String name = sc.nextLine();
		System.out.println("name = " + name);


		//close resource
		sc.close();
	}
}

Math class

  • Characteristics of class

    Mathematical tools

  • Class location

    ​ java.lang

  • Class constructor

    Constructor Privatization (methods can only be called by class name)

  • Class method

    ​ public static double random()

    Returns a double value with a positive sign, which is greater than or equal to 0.0 and less than 1.0.

  • Tips for generating random integers within the specified range:

    ​ (int)(Math.random() * a + b)

    a: number of range data

    b: starting number of the range

public class MathDemo01 {
	public static void main(String[] args) {
		//Requirement: randomly generate integers in the range of 0-99
		System.out.println((int)(Math.random() * 100));
		//Requirement: randomly generate integers in the range of 1-100
		System.out.println((int)(Math.random() * 100 + 1));
		//Requirement: randomly generate integers in the range of 5-8
		System.out.println((int)(Math.random() * 4 + 5));
		//Requirement: randomly generate integers in the range of 8-15
		System.out.println((int)(Math.random() * 8 + 8));
	}
}

Case: guessing numbers games

analysis:

1. Randomly generate an integer between 1 and 100

2. Enter an integer on the keyboard

3. Compare the data:

Enter data > random data

Tip: guess big

Input data < random data

Tip: guess small

Input data = random data

Tip: you guessed right

4. Considering that you don't know how many rounds of data you can guess correctly, choose the while loop and end the loop after you guess correctly

public class MathDemo02 {
	public static void main(String[] args) {
		method03();
	}

	public static void method03 () {
		//1. Randomly generate an integer between 1 and 100
		int num = (int)(Math.random() * 100 + 1);
		//Create Scanner object
		Scanner sc = new Scanner(System.in);

		int start = 1;
		int end = 100;

		//4. Considering that you don't know how many rounds of data you can guess correctly, choose the while loop and end the loop after you guess correctly
		while (true) {
			//2. Enter an integer on the keyboard
			System.out.println("Please enter a" + start + "-" + end + "Integer between ranges");
			int guessNum = sc.nextInt();

			//Make robustness judgment for the data entered by the keyboard
			if (guessNum < start || guessNum > end) {
				System.out.println("Data input error,Please re-enter");
				continue;
			}

			//3. Compare the data
			if (guessNum > num) {
				System.out.println("Your guess is too big,Please re-enter...");
				end = guessNum - 1;
			} else if (guessNum < num) {
				System.out.println("Your guess is too small,Please re-enter...");
				start = guessNum + 1;
			} else {
				System.out.println("congratulations,You guessed right,You can buy lottery tickets when you go home in the evening~~~");
				break;
			}
		}

		//close resource
		sc.close();
	}

	public static void method02 () {
		//1. Randomly generate an integer between 1 and 100
		int num = (int)(Math.random() * 100 + 1);

		//Create Scanner object
		Scanner sc = new Scanner(System.in);

		int start = 1;
		int end = 100;

		//4. Considering that you don't know how many rounds of data you can guess correctly, choose the while loop and end the loop after you guess correctly
		while (true) {
			//2. Enter an integer on the keyboard
			System.out.println("Please enter a" + start + "-" + end + "Integer between ranges");
			int guessNum = sc.nextInt();
			//3. Compare the data
			if (guessNum > num) {
				System.out.println("Your guess is too big,Please re-enter...");
				end = guessNum - 1;
			} else if (guessNum < num) {
				System.out.println("Your guess is too small,Please re-enter...");
				start = guessNum + 1;
			} else {
				System.out.println("congratulations,You guessed right,You can buy lottery tickets when you go home in the evening~~~");
				break;
			}
		}

		//close resource
		sc.close();
	}

	public static void method01 () {
		//1. Randomly generate an integer between 1 and 100
		int num = (int)(Math.random() * 100 + 1);

		//Create Scanner object
		Scanner sc = new Scanner(System.in);

		//4. Considering that you don't know how many rounds of data you can guess correctly, choose the while loop and end the loop after you guess correctly
		while (true) {
			//2. Enter an integer on the keyboard
			System.out.println("Please enter a 1-100 Integer between ranges");
			int guessNum = sc.nextInt();
			//3. Compare the data
			if (guessNum > num) {
				System.out.println("Your guess is too big,Please re-enter...");
			} else if (guessNum < num) {
				System.out.println("Your guess is too small,Please re-enter...");
			} else {
				System.out.println("congratulations,You guessed right,You can buy lottery tickets when you go home in the evening~~~");
				break;
			}
		}

		//close resource
		sc.close();
	}
}

Arrays class

  • Characteristics of class

    Tool class of array

  • Class location

    java.util

  • Class constructor

    Constructor privatization

  • Class method

    public static String toString(int[] a)

    Returns a string representation of the contents of the specified array.

    public static int[] copyOf(int[] original,int newLength)

    Copies the specified array, intercepts or fills with 0 if necessary, so that the copy has the specified length.

    public static void sort(int[] a)

    Sorts the specified int array in ascending numerical order.

Arrays. Comparison rules for sort():

1. Basic data type array

Sort the data in ascending order according to the size of seven data types

Boolean types cannot use arrays Sort

2. String type array

Sort according to Unicode code table

3. Custom type object array

If you want to sort, you need to write comparison rules for them

Comparison rule (comparator)

  • Natural sequence comparator comparable < T >

  • Custom sequential comparator comparator < T >

public class ArraysDemo {
	public static void main(String[] args) {
		//Create an array of basic data types
		int[] arr01 = {44,33,22,11,55};
		//Create an array of string types
		String[] arr02 = {"bca","abc","bac","cba","cab","acb"};
		//Create an array of student types
		Student s1 = new Student("Cui Xiaorong", 18);
		Student s2 = new Student("Zhang Xiaofang", 18);
		Student s3 = new Student("An Xiaoni", 18);
		Student s4 = new Student("Zhang Xiaochi", 18);
		Student s5 = new Student("Li Xiaomeng", 18);
		Student[] arr03 = {s1,s2,s3,s4,s5};

		//Print the array as a string
		System.out.println(Arrays.toString(arr01));
		System.out.println(Arrays.toString(arr02));
		System.out.println(Arrays.toString(arr03));
		System.out.println("======================================");

		//Copy a new array of the specified length from the original array
		int[] newArr = Arrays.copyOf(arr01, 10);
		System.out.println(Arrays.toString(newArr));
		System.out.println("======================================");

		//Sort an array
		Arrays.sort(arr01);
		System.out.println(Arrays.toString(arr01));

		Arrays.sort(arr02);
		System.out.println(Arrays.toString(arr02));

		Arrays.sort(arr03);
		System.out.println(Arrays.toString(arr03));
	}
}
Student Standard class

Keywords: Java Back-end JavaSE

Added by michaellunsford on Fri, 11 Feb 2022 20:58:12 +0200