JAVA basics-Chapter 8 String class, static keyword, Arrays class, Math class

Today's content

String类
static关键字
Arrays类
Math类

teaching objectives

能够使用String类的构造方法创建字符串对象
能够明确String类的构造方法创建对象,和直接赋值创建字符串对象的区别
能够使用文档查询String类的判断方法
能够使用文档查询String类的获取方法
能够使用文档查询String类的转换方法
能够理解static关键字
能够写出静态代码块的格式
能够使用Arrays类操作数组
能够使用Math类进行数学运算

The first chapter String class

1. 1 Overview of the String class

Overview

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

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

Features

  1. The string is unchanged: the value of the string cannot be changed after creation.
2. 因为String对象是不可变的,所以它们可以被共享。
3. "abc" 等效于 char[] data={ 'a' , 'b' , 'c' }。

1. 2 Use steps

View class

java.lang.String :此类不需要导入。
查看构造方法
public String() :初始化新创建的 String对象,以使其表示空字符序列。
public String(char[] value) :通过当前参数中的字符数组来构造新的String。
public String(byte[] bytes) :通过使用平台的默认字符集解码当前参数中的字节数组来构造新的
String。
构造举例,代码如下:

1. 3 common methods

Method of judging function

String s 1  = "abc";
s 1  += "d";
System.out.println(s 1 ); // "abcd"
// 内存中有"abc","abcd"两个对象,s 1 从指向"abc",改变指向,指向了"abcd"。
String s 1  = "abc";
String s 2  = "abc";
// 内存中只有一个"abc"对象被创建,同时被s 1 和s 2 共享。

E.g:

String str = "abc";
相当于:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
// String底层是靠字符数组实现的。

// No parameter construction

String str = new String();
// 通过字符数组构造
char chars[] = {'a', 'b', 'c'};
String str 2  = new String(chars);
// 通过字节数组构造
byte bytes[] = {  97 ,  98 ,  99  };
String str 3  = new String(bytes);
public boolean equals (Object anObject) :将此字符串与指定对象进行比较。
public boolean equalsIgnoreCase (String anotherString) :将此字符串与指定对象进行比较,忽略大小
写。
方法演示,代码如下:
Object 是” 对象”的意思,也是一种引用类型。作为参数类型,表示任意对象都可以传递到方法中。

How to get features

public int length () :返回此字符串的长度。
public String concat (String str) :将指定的字符串连接到该字符串的末尾。
public char charAt (int index) :返回指定索引处的 char值。
public int indexOf (String str) :返回指定子字符串第一次出现在该字符串内的索引。
public String substring (int beginIndex) :返回一个子字符串,从beginIndex开始截取字符串到字符
串结尾。
public String substring (int beginIndex, int endIndex) :返回一个子字符串,从beginIndex到
endIndex截取字符串。含beginIndex,不含endIndex。

Method demonstration, the code is as follows:

public class String_Demo 01  {
public static void main(String[] args) {
// 创建字符串对象
String s 1  = "hello";
String s 2  = "hello";
String s 3  = "HELLO";
// boolean equals(Object obj):比较字符串的内容是否相同
System.out.println(s 1 .equals(s 2 )); // true
System.out.println(s 1 .equals(s 3 )); // false
System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
//boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写
System.out.println(s 1 .equalsIgnoreCase(s 2 )); // true
System.out.println(s 1 .equalsIgnoreCase(s 3 )); // true
System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
}
}
public class String_Demo 02  {
public static void main(String[] args) {
//创建字符串对象
String s = "helloworld";
// int length():获取字符串的长度,其实也就是字符个数
System.out.println(s.length());
System.out.println("‐‐‐‐‐‐‐‐");
// String concat (String str):将将指定的字符串连接到该字符串的末尾.
String s = "helloworld";
String s 2  = s.concat("**hello itheima");

How to convert functions

public char[] toCharArray () :将此字符串转换为新的字符数组。
public byte[] getBytes () :使用平台的默认字符集将该 String编码转换为新的字节数组。
public String replace (CharSequence target, CharSequence replacement) :将与target匹配的字符串使
用replacement字符串替换。

Method demonstration, the code is as follows:

System.out.println(s 2 );// helloworld**hello itheima
// char charAt(int index):获取指定索引处的字符
System.out.println(s.charAt( 0 ));
System.out.println(s.charAt( 1 ));
System.out.println("‐‐‐‐‐‐‐‐");
// int indexOf(String str):获取str在字符串对象中第一次出现的索引,没有返回‐ 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):从start开始截取字符串到字符串结尾
System.out.println(s.substring( 0 ));
System.out.println(s.substring( 5 ));
System.out.println("‐‐‐‐‐‐‐‐");
// String substring(int start,int end):从start到end截取字符串。含start,不含end。
System.out.println(s.substring( 0 , s.length()));
System.out.println(s.substring( 3 , 8 ));
}
}
public class String_Demo 03  {
public static void main(String[] args) {
//创建字符串对象
String s = "abcde";
// char[] toCharArray():把字符串转换为字符数组
char[] chs = s.toCharArray();
for(int x =  0 ; x < chs.length; x++) {
System.out.println(chs[x]);
}
System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
// byte[] getBytes ():把字符串转换为字节数组
byte[] bytes = s.getBytes();
for(int x =  0 ; x < bytes.length; x++) {
System.out.println(bytes[x]);
}
System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
// 替换字母it为大写IT
CharSequence 是一个接口,也是一种引用类型。作为参数类型,可以把String对象传递到方法中。

How to divide the function

public String[] split(String regex) :将此字符串按照给定的regex(规则)拆分为字符串数组。

Method demonstration, the code is as follows:

1. 4 String class exercises

Concatenated string

Define a method to concatenate the array {1, 2, 3} into a string according to the specified format. The format is as follows: [word 1 #word 2 #word 3 ].

String str = "itcast itheima";
String replace = str.replace("it", "IT");
System.out.println(replace); // ITcast ITheima
System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
}
}
public class String_Demo 03  {
public static void main(String[] args) {
//创建字符串对象
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
}
}
}
public class StringTest 1  {
public static void main(String[] args) {
//定义一个int类型的数组
int[] arr = { 1 ,  2 ,  3 };
//调用方法
String s = arrayToString(arr);
//输出结果
System.out.println("s:" + s);
}
/*
* 写方法实现把数组中的元素按照指定的格式拼接成一个字符串
* 两个明确:
* 返回值类型:String
* 参数列表:int[] arr
*/
public static String arrayToString(int[] arr) {
// 创建字符串s

Count the number of characters

Enter a character on the keyboard, and count the number of uppercase and lowercase letters and numbers in the string

Chapter 2 static keyword

String s = new String("[");
// 遍历数组,并拼接字符串
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;
}
}
public class StringTest 2  {
public static void main(String[] args) {
//键盘录入一个字符串数据
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串数据:");
String s = sc.nextLine();
//定义三个统计变量,初始化值都是 0
int bigCount =  0 ;
int smallCount =  0 ;
int numberCount =  0 ;
//遍历字符串,得到每一个字符
for(int x= 0 ; x<s.length(); x++) {
char ch = s.charAt(x);
//拿字符进行判断
if(ch>='A'&&ch<='Z') {
bigCount++;
}else if(ch>='a'&&ch<='z') {
smallCount++;
}else if(ch>=' 0 '&&ch<=' 9 ') {
numberCount++;
}else {
System.out.println("该字符"+ch+"非法");
}
}
//输出结果
System.out.println("大写字符:"+bigCount+"个");
System.out.println("小写字符:"+smallCount+"个");
System.out.println("数字字符:"+numberCount+"个");
}
}

Chapter 2 static keyword

2. 1 Overview

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

2. 2 Definition and usage format

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 this type of variable, but it can also be operated on without creating an object of this type.

类变量:使用 static关键字修饰的成员变量。

Definition format:

For example:

For example, when a new basic class opens, students report. Now I want to assign a student ID (sid) for every new student who registers. Starting from the first student, the sid is
1, and so on. The student ID must be unique, continuous, and consistent with the number of students in the class, so that you can know the student
ID to be assigned to the next new student . In this way, we need a variable that is not related to each individual student object, but related to the number of students in the entire class.

So, we can define a static variable numberOfStudent like this, the code is as follows:

static 数据类型 变量名;
static int numberID;
public class Student {
private String name;
private int age;
// 学生的id
private int sid;
// 类变量,记录学生数量,分配学号
public static int numberOfStudent =  0 ;
public Student(String name, int age){
this.name = name;
this.age = age;
// 通过 numberOfStudent 给学生分配学号
this.sid = ++numberOfStudent;
}
// 打印属性值
public void show() {
System.out.println("Student : name=" + name + ", age=" + age + ", sid=" + sid );
}
}

Static method

When static modifies a member method, the method is called a class method. The static method has static in the declaration, it is recommended to use the class name to call, without
creating the object of the class. The calling method is very simple.

类方法:使用 static关键字修饰的成员方法,习惯称为静态方法。

Definition format:

Example: Define a static method in the Student class

Note 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.

静态方法中,不能使用this关键字。
小贴士:静态方法只能访问静态成员。

Call format

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

format:

public class StuDemo {
public static void main(String[] args) {
Student s 1  = new Student("张三",  23 );
Student s 2  = new Student("李四",  24 );
Student s 3  = new Student("王五",  25 );
Student s 4  = new Student("赵六",  26 );
s 1 .show(); // Student : name=张三, age= 23 , sid= 1
s 2 .show(); // Student : name=李四, age= 24 , sid= 2
s 3 .show(); // Student : name=王五, age= 25 , sid= 3
s 4 .show(); // Student : name=赵六, age= 26 , sid= 4
}
}
修饰符 static 返回值类型 方法名 (参数列表){
// 执行语句
}
public static void showNum() {
System.out.println("num:" + numberOfStudent);
}

Call the demo, the code is as follows:

2. 3 static principle diagram

static 修饰的内容:
是随着类的加载而加载的,且只加载一次。
存储于一块固定的内存区域(静态区),所以,可以直接被类名调用。
它优先于对象存在,所以,可以被所有对象共享。

2. 4 static code block

静态代码块:定义在成员位置,使用static修饰的代码块{ }。
位置:类中方法外。
执行:随着类的加载而执行且执行一次,优先于main方法和构造方法的执行。

format:

// Access class variables

Class name. Class variable name;

// call static method

Class name. Static method name (parameter);

public class StuDemo 2  {
public static void main(String[] args) {
// 访问类变量
System.out.println(Student.numberOfStudent);
// 调用静态方法
Student.showNum();
}
}

Role: to initialize and assign values ​​to class variables. Usage demonstration, the code is as follows:

Tips:

static 关键字,可以修饰变量、方法和代码块。在使用的过程中,其主要目的还是想在不创建对象的情况
下,去调用方法。下面将介绍两个工具类,来体现static 方法的便利。

Chapter 3 Arrays Class

3. 1 Overview

java.util.Arrays This 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 Methods of manipulating arrays

public static String toString(int[] a) :返回指定数组内容的字符串表示形式。
public class ClassName{
static {
// 执行语句
}
}
public class Game {
public static int number;
public static ArrayList<String> list;
static {
// 给类变量赋值
number =  2 ;
list = new ArrayList<String>();
// 添加元素到集合中
list.add("张三");
list.add("李四");
}
}
public static void main(String[] args) {
// 定义int 数组
int[] arr = { 2 , 34 , 35 , 4 , 657 , 8 , 69 , 9 };
// 打印数组,输出地址值
System.out.println(arr); // [I@ 2 ac 1 fdc 4
// 数组内容转为字符串
String s = Arrays.toString(arr);
// 打印字符串,输出内容
System.out.println(s); // [ 2 ,  34 ,  35 ,  4 ,  657 ,  8 ,  69 ,  9 ]
}
public static void sort(int[] a) :对指定的 int 型数组按数字升序进行排序。

3. 3 exercises

Please use Arrays related APIs to sort all characters in a random string in ascending order and print them in reverse order.

Chapter 4 Math Class

4.1 Overview

The java.lang.Math class contains methods for performing basic mathematical operations, such as elementary exponents, logarithms, square roots, and trigonometric functions. A tool
like this, all methods are static methods, and no object is created, so it is very simple to call.

4. 2 Basic calculation methods^

public static double abs(double a) :返回 double 值的绝对值。
public static double ceil(double a) :返回大于等于参数的最小的整数。
public static void main(String[] args) {
// 定义int 数组
int[] arr = { 24 ,  7 ,  5 ,  48 ,  4 ,  46 ,  35 ,  11 ,  6 ,  2 };
System.out.println("排序前:"+ Arrays.toString(arr)); // 排序前:[ 24 ,  7 ,  5 ,  48 ,  4 ,  46 ,  35 ,  11 ,  6 ,
2 ]
// 升序排序
Arrays.sort(arr);
System.out.println("排序后:"+ Arrays.toString(arr));// 排序后:[ 2 ,  4 ,  5 ,  6 ,  7 ,  11 ,  24 ,  35 ,  46 ,
48 ]
}
public class ArraysTest {
public static void main(String[] args) {
// 定义随机的字符串
String line = "ysKUreaytWTRHsgFdSAoidq";
// 转换为字符数组
char[] chars = line.toCharArray();
// 升序排序
Arrays.sort(chars);
// 反向遍历打印
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
}
}
}
double d 1  = Math.abs(‐ 5 ); //d 1 的值为 5
double d 2  = Math.abs( 5 ); //d 2 的值为 5
public static double floor(double a) :返回小于等于参数最大的整数。
public static long round(double a) :返回最接近参数的 long。(相当于四舍五入方法)

4. 3 exercises

Please use Math-related APIs to calculate how many integers are between -10. 8 and 5.9 with absolute values ​​greater than 6 or less than 2.1?

double d 1  = Math.ceil( 3. 3 ); //d 1 的值为  4. 0
double d 2  = Math.ceil(‐ 3. 3 ); //d 2 的值为 ‐ 3. 0
double d 3  = Math.ceil( 5. 1 ); //d 3 的值为  6. 0
double d 1  = Math.floor( 3. 3 ); //d 1 的值为 3. 0
double d 2  = Math.floor(‐ 3. 3 ); //d 2 的值为‐ 4. 0
double d 3  = Math.floor( 5. 1 ); //d 3 的值为  5. 0
long d 1  = Math.round( 5. 5 ); //d 1 的值为 6. 0
long d 2  = Math.round( 5. 4 ); //d 2 的值为 5. 0
public class MathTest {
public static void main(String[] args) {
// 定义最小值
double min = ‐ 10. 8 ;
// 定义最大值
double max =  5. 9 ;
// 定义变量计数
int count =  0 ;
// 范围内循环
for (double i = Math.ceil(min); i <= max; i++) {
// 获取绝对值并判断
if (Math.abs(i) >  6  || Math.abs(i) <  2. 1 ) {
// 计数
count++;
}
}
System.out.println("个数为: " + count + " 个");
}
}

Guess you like

Origin blog.csdn.net/weixin_43419256/article/details/108198455