day08 [String class, static keyword, Array class, Math class]
Today's Content
-
String class
-
static keyword
-
Array class
-
Math class
target
-
Ability to create string objects using String class constructors
-
Ability to specify the construction method of String class to create objects, and direct assignment to create string objects
-
Judgment method of using document to query String class
-
A method for obtaining String classes by querying documents
-
Conversion methods that can query String classes using documents
-
Ability to understand static keywords
-
Formats that can write static code blocks
-
Ability to manipulate arrays using the Arrays class
-
Ability to use Math classes for mathematical operations
Chapter 1 String Classes
1.1 Overview of String Classes
Summary
The java.lang.String class represents a string. All string literals (such as "abc") in Java programs can be considered instances of implementing such a class.
Class String includes methods for checking individual strings, such as comparing strings, searching for strings, extracting substrings, and creating copies of strings with all characters translated into uppercase or lowercase.
Characteristic
- String unchanged: The value of the string cannot be changed after creation.
String s1 = "abc"; s1 += "d"; System.out.println(s1); // "abcd" // There are "abc" and "abcd" objects in memory. s1 points from "abc" to "abcd".
- String objects can be shared because they are immutable.
String s1 = "abc"; String s2 = "abc"; // Only one "abc" object in memory is created and shared by s1 and s2.
- "A B c" is equivalent to char [] data ={'a','b','c'}.
For example: String str = "abc"; //Amount to: char data[] = {'a', 'b', 'c'}; String str = new String(data); // The bottom of String is implemented by character arrays.
1.2 Use steps
-
view classes
- java.lang.String: This class does not need to be imported.
-
View the Construction Method
- public String(): Initializes the newly created String object to represent a sequence of empty characters.
- public String(char[] value): Constructs a new String from an array of characters in the current parameter.
- public String(byte[] bytes): Construct a new String by decoding the byte array in the current parameter using the default character set of the platform.
- Construct an example with the following code:
// Parametric structure String str = new String(); // Constructing by Character Array char chars[] = {'a', 'b', 'c'}; String str2 = new String(chars); // Construct by byte array byte bytes[] = { 97, 98, 99 }; String str3 = new String(bytes);
1.3 Common Methods
The Method of Judging Function
-
public boolean equals (Object anObject): Compare this string with the specified object.
-
Public Boolean equals IgnoreCase (String anotherString): Compare this string with the specified object, ignoring case.
Method demonstration, code as follows:
public class String_Demo01 { public static void main(String[] args) { // Create string objects String s1 = "hello"; String s2 = "hello"; String s3 = "HELLO"; // boolean equals(Object obj): Compare strings with the same content System.out.println(s1.equals(s2)); // true System.out.println(s1.equals(s3)); // false System.out.println("-----------"); //Boolean equals IgnoreCase (String str): Compare strings with the same content, ignoring case and case System.out.println(s1.equalsIgnoreCase(s2)); // true System.out.println(s1.equalsIgnoreCase(s3)); // true System.out.println("-----------"); } }
Object means "object" and is also a reference type. As a parameter type, any object can be passed to the method.
A Method of Capturing Functions
-
public int length (): Returns the length of this string.
-
public String concat (String str): Connects the specified string to the end of the string.
-
Public char at (int index): Returns the char value at the specified index.
-
public int indexOf (String str): Returns the index in which the specified substring first appears in the string.
-
public String substring (int beginIndex): Returns a substring that starts with beginIndex and intercepts the string to the end of the string.
-
public String substring (int beginIndex, int endIndex): Returns a substring and intercepts the string from beginIndex to endIndex. Contains beginIndex, not endIndex.
Method demonstration, code as follows:
public class String_Demo02 { public static void main(String[] args) { //Create string objects String s = "helloworld"; // int length(): Gets the length of the string, which is actually the number of characters System.out.println(s.length()); System.out.println("--------"); // String concat (String str): Connects the specified string to the end of the string. String s = "helloworld"; String s2 = s.concat("**hello itheima"); System.out.println(s2);// helloworld**hello itheima // CharAt (int index): Gets the character at the specified index System.out.println(s.charAt(0)); System.out.println(s.charAt(1)); System.out.println("--------"); // int indexOf(String str): Gets the index that STR first appears in a string object without returning - 1 System.out.println(s.indexOf("l")); System.out.println(s.indexOf("owo")); System.out.println(s.indexOf("ak")); System.out.println("--------"); // String substring(int start): Intercept strings from start to end of strings System.out.println(s.substring(0)); System.out.println(s.substring(5)); System.out.println("--------"); // String substring(int start,int end): A string is intercepted from start to end. Including start, excluding end. System.out.println(s.substring(0, s.length())); System.out.println(s.substring(3,8)); } }
Method of Transforming Functions
- public char[] toCharArray (): Converts this string to a new character array.
- public byte[] getBytes (): Convert the String encoding to a new byte array using the platform's default character set.
- public String replace (CharSequence target, CharSequence replacement): Replace strings that match the target with replacement strings.
Method demonstration, code as follows:
public class String_Demo03 { public static void main(String[] args) { //Create string objects String s = "abcde"; // char[] toCharArray(): Converts strings to character arrays char[] chs = s.toCharArray(); for(int x = 0; x < chs.length; x++) { System.out.println(chs[x]); } System.out.println("-----------"); // byte[] getBytes (): Converts strings to byte arrays byte[] bytes = s.getBytes(); for(int x = 0; x < bytes.length; x++) { System.out.println(bytes[x]); } System.out.println("-----------"); // Replace the letter it with capital IT String str = "itcast itheima"; String replace = str.replace("it", "IT"); System.out.println(replace); // ITcast ITheima System.out.println("-----------"); } }
CharSequence is an interface and a reference type. As a parameter type, you can pass String objects to methods.
Method of Segmenting Function
- public String[] split(String regex): Split this string into an array of strings according to a given regex (rule).
Method demonstration, code as follows:
public class String_Demo03 { public static void main(String[] args) { //Create string objects String s = "aa|bb|cc"; String[] strArray = s.split("|"); // ["aa","bb","cc"] for(int x = 0; x < strArray.length; x++) { System.out.println(strArray[x]); // aa bb cc } } }
1.4 String class exercises
Stitching strings
Define a method that splits the array {1,2,3} into a string in a specified format. The format is as follows: [word1#word2#word3].
public class StringTest1 { public static void main(String[] args) { //Define an array of int types int[] arr = {1, 2, 3}; //Call method String s = arrayToString(arr); //Output results System.out.println("s:" + s); } /* * Writing implements splicing elements of an array into a string in a specified format * Two definitions: * Return value type: String * List of parameters: int[] arr */ public static String arrayToString(int[] arr) { // Create string s String s = new String("["); // Traversing arrays and splicing strings for (int x = 0; x < arr.length; x++) { if (x == arr.length - 1) { s = s.concat(arr[x] + "]"); } else { s = s.concat(arr[x] + "#"); } } return s; } }
Statistical Character Number
Keyboard input a string, count the number of upper and lower case letters and numeric characters in the string
public class StringTest2 { public static void main(String[] args) { //Keyboard input a string data Scanner sc = new Scanner(System.in); System.out.println("Please enter a string data:"); String s = sc.nextLine(); //Define three statistical variables with initialization values of 0 int bigCount = 0; int smallCount = 0; int numberCount = 0; //Traverse the string to get each character for(int x=0; x<s.length(); x++) { char ch = s.charAt(x); //Judging by Characters if(ch>='A'&&ch<='Z') { bigCount++; }else if(ch>='a'&&ch<='z') { smallCount++; }else if(ch>='0'&&ch<='9') { numberCount++; }else { System.out.println("This character"+ch+"illegal"); } } //Output results System.out.println("Capital letters:"+bigCount+"individual"); System.out.println("Lower-case characters:"+smallCount+"individual"); System.out.println("Digital characters:"+numberCount+"individual"); } }
Chapter II static Keyword
2.1 Overview
As for the use of the static keyword, it can be used to modify member variables and member methods. The modified members belong to the class, not just to an object. That is to say, since it belongs to a class, it can be invoked without creating objects.
2.2 Definition and use format
Class variables
When static modifies a member variable, it 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 it can also operate on the class variable without creating the class object.
- Class variables: Member variables modified with the static keyword.
Definition format:
static data type variable name;
Give an example:
static int numberID;
For example, new classes in basic classes start and students report. Now I want to number every new student (sid), starting with the first student, sid is 1, and so on. The number must be unique, continuous and consistent with the number of students in the class, so as to know what number to assign to the next new student. So we need a variable, independent of each student, but related to the number of students in the whole class.
So we can define a static variable numberOfStudent as follows:
public class Student { private String name; private int age; // Student id private int sid; // Class variables, record the number of students, assign student numbers public static int numberOfStudent = 0; public Student(String name, int age){ this.name = name; this.age = age; // Distribution of student numbers through numberOf Student this.sid = ++numberOfStudent; } // Print attribute values public void show() { System.out.println("Student : name=" + name + ", age=" + age + ", sid=" + sid ); } } public class StuDemo { public static void main(String[] args) { Student s1 = new Student("Zhang San", 23); Student s2 = new Student("Li Si", 24); Student s3 = new Student("Wang Wu", 25); Student s4 = new Student("Zhao Liu", 26); s1.show(); // Student: name = Zhang San, age=23, sid=1 s2.show(); // Student: name = Lisi, age=24, sid=2 s3.show(); // Student: name = Wang Wu, age=25, sid=3 s4.show(); // Student: name = Zhao Liu, age=26, sid=4 } }
Static method
When static modifies member methods, this method is called class methods. Static methods have static in the declaration. It is recommended that class names be used to invoke them instead of creating class objects. The invocation is very simple.
- Class methods: Membership methods modified with static keywords are commonly referred to as static methods.
Definition format:
Modifier static return value type method name (parameter list){ // Execution statement }
Examples: Defining static methods in Student classes
public static void showNum() { System.out.println("num:" + numberOfStudent); }
-
Notes for static method calls:
- Static methods can directly access class variables and static methods.
- Static methods cannot directly access ordinary member variables or member methods. Conversely, member methods can directly access class variables or static methods.
- In static methods, this keyword cannot be used.
Tip: Static methods can only access static members.
Call format
Members modified by static can and recommend direct access through class names. Although static members can also be accessed by object names, the reason is that multiple objects belong to a class and share the same static member, but it is not recommended that warning messages appear.
Format:
// Access class variables Class name. Class variable name; // Calling static methods Class name. Static method name (parameter);
Call the demo, the code is as follows:
public class StuDemo2 { public static void main(String[] args) { // Access class variables System.out.println(Student.numberOfStudent); // Calling static methods Student.showNum(); } }
2.3 Static Principle Diagram
static modification:
- It is loaded as the class is loaded, and only once.
- Stored in a fixed memory area (static area), so it can be called directly by the class name.
- It takes precedence over object existence, so it can be shared by all objects.
[External Link Picture Transfer Failure (img-GFfpNxAC-1566559502055)(img/1.jpg)]
2.4 Static Code Block
-
Static code block: defined at the member location, code block {} decorated with static.
- Location: Outside of the method in the class.
- Execution: Executes once as the class is loaded, taking precedence over the execution of the constructor.
Format:
public class ClassName{ static { // Execution statement } }
Function: Initialize and assign class variables. Usage demonstration, code as follows:
public class Game { public static int number; public static ArrayList<String> list; static { // Assignment of class variables number = 2; list = new ArrayList<String>(); // Add elements to collections list.add("Zhang San"); list.add("Li Si"); } }
Tips:
Static keywords can modify variables, methods, and code blocks. In the process of using, its main purpose is to call methods without creating objects. Two tool classes are introduced below to illustrate the convenience of the static method.
Chapter III Arrays Classes
3.1 Overview
The java.util.Arrays class contains various methods for manipulating arrays, such as sorting and searching. All of its methods are static methods, which are very simple to call.
3.2 Operational Array Method
- Public static String to String (int [] a): Returns a string representation of the contents of the specified array.
public static void main(String[] args) { // Define an int array int[] arr = {2,34,35,4,657,8,69,9}; // Print arrays, output address values System.out.println(arr); // [I@2ac1fdc4 // Converting Array Content to String String s = Arrays.toString(arr); // Print string, output content System.out.println(s); // [2, 34, 35, 4, 657, 8, 69, 9] }
- public static void sort(int[] a): Sorts the specified int array in ascending numerical order.
public static void main(String[] args) { // Define an int array int[] arr = {24, 7, 5, 48, 4, 46, 35, 11, 6, 2}; System.out.println("Before sorting:"+ Arrays.toString(arr)); // Before sorting: [24, 7, 5, 48, 4, 46, 35, 11, 6, 2] // Ascending order Arrays.sort(arr); System.out.println("After sorting:"+ Arrays.toString(arr));// After sorting: [2, 4, 5, 6, 7, 11, 24, 35, 46, 48] }
3.3 Exercise
Use the Array related API to sort all the characters in a random string in ascending order and print them in reverse order.
public class ArraysTest { public static void main(String[] args) { // Define random strings String line = "ysKUreaytWTRHsgFdSAoidq"; // Convert to character array char[] chars = line.toCharArray(); // Ascending order Arrays.sort(chars); // Reverse traversal printing for (int i = chars.length-1; i >= 0 ; i--) { System.out.print(chars[i]+" "); // y y t s s r q o i g e d d a W U T S R K H F A } } }
Chapter IV Math Classes
4.1 Overview
The java.lang.Math class contains methods for performing basic mathematical operations, such as elementary exponents, logarithms, square roots, and triangular functions. Tool classes like this, all of which are static methods and do not create objects, are very simple to call.
4.2 Basic Operations
- public static double abs(double a): Returns the absolute value of the double value.
double d1 = Math.abs(-5); //The value of d1 is 5 double d2 = Math.abs(5); //The value of d2 is 5
- public static double ceil(double a): Returns the smallest integer greater than or equal to the parameter.
double d1 = Math.ceil(3.3); //The value of d1 is 4.0 double d2 = Math.ceil(-3.3); //The value of d2 is - 3.0 double d3 = Math.ceil(5.1); //The value of d3 is 6.0
- public static double floor(double a): Returns an integer less than or equal to the maximum parameter.
double d1 = Math.floor(3.3); //The value of d1 is 3.0 double d2 = Math.floor(-3.3); //The value of d2 is - 4.0 double d3 = Math.floor(5.1); //The value of d3 is 5.0
- public static long round(double a): returns the long closest to the parameter. (equivalent to rounding)
long d1 = Math.round(5.5); //The value of d1 is 6.0 long d2 = Math.round(5.4); //The value of d2 is 5.0
4.3 Exercise
How many integers with absolute values greater than 6 or less than 2.1 are calculated between - 10.8 and 5.9 using Math-related API s?
public class MathTest { public static void main(String[] args) { // Define the minimum double min = -10.8; // Define maximum double max = 5.9; // Define variable count int count = 0; // Scope Cycle for (double i = Math.ceil(min); i <= max; i++) { // Obtain absolute value and judge if (Math.abs(i) > 6 || Math.abs(i) < 2.1) { // count count++; } } System.out.println("Number: " + count + " individual"); } }