[String class, static keyword, Arrays class, Math class]

Keywords: Java Back-end

Java Foundation

Chapter 8 String class, static keyword, Arrays class, Math class
(most of the commonly used methods are listed in the article. For details of other methods, please refer to the API document)

String class

Overview of String class

summary

The java.lang.String class represents a string. All string literals (such as "abc") in Java programs can be regarded as instances of implementing this class.

The class String includes methods for checking individual strings, such as comparing strings, searching strings, extracting substrings, and creating copies of strings with all characters translated to uppercase or lowercase.

characteristic

  1. String unchanged: the value of the string cannot be changed after creation.
String s1 = "abc";
s1 += "d";
System.out.println(s1); // "abcd"
// There are two objects "abc" and "abcd" in memory. s1 points to "abc" from "abc" to "abcd".
  1. Because String objects are immutable, they can be shared.
String s1 = "abc";
String s2 = "abc";
// Only one "abc" object in memory is created and shared by s1 and s2.
  1. "abc" 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 layer of String is realized by character array.

Use steps

view classes

  • java.lang.String: this class does not need to be imported.

View construction method

  • public String(): initializes the newly created String object to represent a null character sequence.
  • public String(char[] value): construct a new String through the character array in the current parameter.
  • public String(byte[] bytes): construct a new String by decoding the byte array in the current parameter using the platform's default character set.

For example, the code is as follows:

// Nonparametric structure
String str = new String();
// Constructed from a character array
char chars[] = {'a', 'b', 'c'};
String str2 = new String(chars);
// Constructed by byte array
byte bytes[] = { 1, 2, 3 };
String str3 = new String(bytes);

common method

Method of judging function

  • public boolean equals (Object anObject): compares this string with the specified object.
    Object means "object" and is also a reference type. As a parameter type, it means that any object can be passed to the method.
  • Public Boolean equalsignorecase (string otherstring): compares this string with the specified object, ignoring case.

Method demonstration, the code is as follows:

public class String_Demo01 {
	public static void main(String[] args) {
		// Create string object
		String s1 = "a";
		String s2 = "a";
		String s3 = "A";
		// boolean equals(Object obj): compare whether the contents of strings are the same
		System.out.println(s1.equals(s2)); // true
		System.out.println(s1.equals(s3)); // false
		System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
		//boolean equalsIgnoreCase(String str): compare whether the contents of strings are the same, ignoring case
		System.out.println(s1.equalsIgnoreCase(s2)); // true
		System.out.println(s1.equalsIgnoreCase(s3)); // true
		System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
	}
}

Method of obtaining function

  • public int length(): returns the length of this string.
  • public String concat (String str): connect the specified string to the end of the string.
  • public char charAt (int index): returns the char value at the specified index.
  • public int indexOf (String str): returns the index of the specified substring that appears in the string for the first time.
  • public String substring (int beginIndex): returns a substring, intercepting the string from beginIndex to the end of the string.
  • public String substring (int beginIndex, int endIndex): returns a substring and intercepts the string from beginIndex to endIndex. Including beginIndex and excluding endIndex.

The method is as follows:

public class String_Demo02 {
	public static void main(String[] args) {
		//Create string object
		String s = "hello";
		// 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): concatenates the specified string to the end of the string
		String s = "hello";
		String s2 = s.concat("word");
		System.out.println(s2);// helloworld
		// char 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): get the index of the first occurrence of str in the string object, and return - 1
		System.out.println(s.indexOf("l"));
		System.out.println(s.indexOf("o"));
		System.out.println(s.indexOf("e"));
		System.out.println("‐‐‐‐‐‐‐‐");
		// String substring(int start): intercept the string from start to the end of the string
		System.out.println(s.substring(0));
		System.out.println(s.substring(5));
		System.out.println("‐‐‐‐‐‐‐‐");
		// String substring(int start,int end): intercepts a string from start to end. Including start, excluding end.
		System.out.println(s.substring(0, s.length()));
		System.out.println(s.substring(0,3));
	}
}

Methods of converting functions

  • public char[] toCharArray(): convert this string to a new character array.
  • public byte[] getBytes(): use the default character set of the platform to convert the String encoding into a new byte array.
  • public String replace (CharSequence target, CharSequence replacement): replace the string matching the target with the replacement string.

The method is demonstrated as follows:

public class String_Demo03 {
	public static void main(String[] args) {
		//Create string object
		String s = "joker";
		// char[] toCharArray(): convert string to character array
		char[] chs = s.toCharArray();
		for(int x = 0; x < chs.length; x++) {
			System.out.println(chs[x]);
		}
		System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
		// byte[] getBytes(): convert string to byte array
		byte[] bytes = s.getBytes();
		for(int x = 0; x < bytes.length; x++) {
			System.out.println(bytes[x]);
		}
		System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
		// Replace letter K with capital K
		String str = "itcast itheima";
		String replace = str.replace("k", "K");
		System.out.println(replace); // joKer
		System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
	}
}

CharSequence is an interface and a reference type. As a parameter type, you can pass a String object into a method.

Method of dividing function

  • public String[] split(String regex): splits this string into a string array according to the given regex (rule).

The method is demonstrated as follows:

public class String_Demo03 {
	public static void main(String[] args) {
		//Create string object
		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
		}
	}
}

static keyword

summary

About the use of static keyword, it can be used to modify member variables and member methods. The modified member belongs to a class, not just an object. In other words, since it belongs to a class, it can be called without creating an object.

Define and use formats

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.

  • Class variable: a member variable modified with the static keyword.

Define format:

static Data type variable name;

give an example:

static int numberID;

Static method

When static modifies a member method, the method is called a class method. Static methods have static in the declaration. It is recommended to call them with the class name instead of creating the object of the class. The call method is very simple.

  • Class method: a member method modified with the static keyword, which is customarily called a static method.

Define format:

Modifier  static Return value type method name (parameter list){
	// Execute statement
}

The code is as follows (example):

public static void Hello() {
	System.out.println("Hello");
}

Precautions for static method invocation:

  • 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.
  • this keyword cannot be used in static methods.
    Static methods can only access static members.

Call format

Members modified by static can and are recommended to be accessed directly through the class name. Although static members can also be accessed through object names, because multiple objects belong to the same class and share the same static member, it is not recommended and a warning message will appear.
Format:

// Access class variables
 Class name.Class variable name;

// Call static method
 Class name.Static method name(parameter);

Static principle diagram

static modification:

  • It is loaded as the class is loaded, and it is loaded only once.
  • It is stored in a fixed memory area (static area), so it can be called directly by the class name.
  • It takes precedence over objects, so it can be shared by all objects.

Static code block

Static code block: a code block {} defined at the member position and decorated with static.

  • Location: outside the method in the class.
  • Execution: it is executed once as the class is loaded, which takes precedence over the execution of main method and constructor method.

Format:

public class ClassName{
	static {
		// Execute statement
	}
}

The code is as follows (example):

public class Game {
	public static int number;
	public static ArrayList<String> list;
	static {
		// Assign values to class variables
		number = 2;
		list = new ArrayList<String>();
		// Add element to collection
		list.add("Xiang taro");
		list.add("Philip");
	}
}

static keyword, which can modify variables, methods, and code blocks. In the process of using, the main purpose is to call methods without creating objects.

Arrays class

summary

The java.util.Arrays class contains various methods for manipulating arrays, such as sorting and searching. All its methods are static methods, which are very simple to call.

Methods of manipulating arrays

public static String toString(int[] a): returns the string representation of the specified array content.
The code is as follows (example):

public static void main(String[] args) {
	// Define int array
	int[] arr = {2,34,35,4,657,8,69,9};
	// Print the array and output the address value
	System.out.println(arr); // [I@2ac1fdc4
	// Convert array contents to strings
	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): sort the specified int array in ascending numerical order.

The code is as follows (example):

public static void main(String[] args) {
	// Define 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 sort
	Arrays.sort(arr);
	System.out.println("After sorting:"+ Arrays.toString(arr));// After sorting: [2, 4, 5, 6, 7, 11, 24, 35, 46,
	48]
}

Math class

summary

The java.lang.Math class contains methods used to perform basic mathematical operations, such as elementary exponents, logarithms, square roots, and trigonometric functions. For tool classes like this, all of their methods are static methods, and they do not create objects, which is very simple to call.

Method of basic operation

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 method)

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

Please use Math related API s to calculate the number of integers with absolute values greater than 6 or less than 2.1 between - 10.8 and 5.9. The code is as follows (example):

public class MathTest {
	public static void main(String[] args) {
		// Define minimum
		double min = ‐10.8;
		// Define maximum
		double max = 5.9;
		// Define variable count
		int count = 0;
		// Cycle in range
		for (double i = Math.ceil(min); i <= max; i++) {
			// Get absolute value and judge
			if (Math.abs(i) > 6 || Math.abs(i) < 2.1) {
				// count
				count++;
			}
		}
		System.out.println("The number is: " + count + " individual");
	}
}

Posted by squariegoes on Sun, 28 Nov 2021 03:55:48 -0800