Chapter08【String类、static、Arrays类、Math类】

Chapter08【String类、static、Arrays类、Math类】

第一章 String类

1.概述

java.lang.String 类代表字符串

API(开发文档)当中说:Java程序中所有字符串字面值(如“abc”)都作为此例的实例实现。

其实就是说:程序中所有的双引号字符串,都是String类的对象。(就算没有new也照样是)

2.字符串的特点

  1. 字符串的内容永不可改变。【重点】
  2. 正是因为字符串用不可改变,所以字符串是可以共享使用的。
  3. 字符串的效果上相当于char[]字符数组,但是底层原理是byte[] 字节数组。

3.创建字符串 3 + 1种方式

3种构造方法

  1. 空参构造

    public String():创建一个空白的字符串不含有任何内容

    //小括号留空,说明字符串什么内容都没有
    String str1 = new String();
    
  2. 根据字符数组创建字符串

    public String(char[] array);根据字符数组内容,来创建对应的字符串。

    char[] charArray = {'A','B','C'};
    String str2 = new String(charArray);
    
  3. 根据字节数组创建字符串

    public String(byte[] array);根据字节数组内容,来创建对应的字符串。

    byte[] byteArray = {'97','98','99'};
    String str3 = new String(byteArray);
    

1种直接创建

String str = "hello";//右边直接双引号

注意:直接写上双引号,就是字符串对象。

4.字符串常量池

字符串常量池:在程序中直接写上的双引号字符串,就在字符串常量池中。new的不在池中。

对于基本类型来说,== 是进行数值的比较。

对于引用类型来说,==是进行【地址值】的比较。

public static void main(String[] args){
    String str1 = "abc";
    String str2 = "abc";
    
    char[] charArray = {'a','b','c'};
    String str3 = new String(charArray);
    
    System.out.println(str1 == str2);//truw
    System.out.println(str1 == str3);//false
    System.out.println(str2 == str3);//false
}

5.字符串比较的方法

== 是进行对象地址值的比较,如果确实需要字符串的内容比较,可以使用两个方法:

  • public boolean equals(Object obj);将此字符串与指定对象进行比较,参数可以是任何对象,只有参数是一个字符串并且内容相同返回为true,否则返回false。

    • 注意事项
      • 任何对象都能用object进行接收。
      • equals方法具有对成型,也就是a.equals(b)和b.equals(a)效果一样。
      • 如果比较双方一个常量一个变量,推荐把常量字符串写在前面。
        • 推荐 :"abc".equals(str)
        • 不推荐:str.equsls("abc")

    代码如下:

    public static void mian(String[] args){
        String str1 = "hello";
        String str2 = "hello";
        char[] charArray = {'h','e','l','l','o'};
        String str3 = new String(charArray);
        
        System.out,println(str1.equals(str2));//true
        System.out,println(str2.equals(str3));//true
        System.out,println(str1.equals(str3));//true
        System.out,println("hello".equals(str1));//true
        
        String str4 = "Hello";
        System.out,println(str1.equals(str4));//false
        
        String str5 = null;
        System.out,println("ABC".equals(str5));//推荐 false
        System.out,println(str5.equals("abc"));//不推荐 报错 空指针异常NullPointerException
    }
    
  • 忽略大小写,进行内容比较

    public boolean equalsIgnoreCase(String str);

public static void main(String[] args){
    String strA = "Java";
        String strB = "java";
        //区分大小写
        System.out.println(strA.equals(strB));//false
        //不区分大小写
        System.out.println(strA.equalsIgnoreCase(strB));//true

        //注意  只有英文字母区分大小写,其他的不区分大小写
        System.out.println("abc二123".equalsIgnoreCase("abc贰123"));

}

6.字符串获取的相关方法

1.获取字符串的长度

public int length();

//方法一
String str1 = "adgaxvdrghagsdfg";
int length = str1.length();
System.out.println("字符串的长度是:"+length);
//方法二
int length = "asdfgagsdfd".length();
System.out.println("字符串的长度是"+length)

2.将指定字符串连接到该字符串的末尾

public String concat(String str);

String str1 = "hello";
String str2 = "world";
String str3 = str1.concat(str2);
System.out.println(str3)//helloworld

3.获取指定索引位置的单个字符

索引从0开始

public char charAt(int index)

char ch = "hello".charAt(2);
System.out.println("在2号索引位置的字符是:"+ch);//l

4.返回指定字符串第一次出现该字符串内的索引

如果没有返回-1 值

public int indexOf(String str);

String original = "helloworld";
int index = original.indexOf("llo");
System.out.println("第一次的索引值是:"+index);

5.返回一个子字符串

从beginIndex开始截取字符串到字符串结尾

public String substring(int beginIndex);

String str1 = "helloworld";
String str2 = str1.substring(5);
System.out.println(str2);//world

6.指定截取

返回一个子字符串,从beginIndex到 endIndex截取字符串。含beginIndex,不含endIndex

public String subString(int beginIndex,int endIndex);

String str1 = "hellowrld";
String str2 = str1.substring(4,7);
System.out.println(str2);//owo

PS:

下面这种写法,字符串的内容仍然是没有改变的。

下面有两个字符串:"hello"、"java"

str1当中保存的是地址值

本来地址值是hello的0x666

后来地址值变成了java的0x999

String str1 = "hello";
System.out.println(str1);//hello
str1 = "java";
System.out.println(str1);//java

7.转换功能的方法

1.将字符串拆分称为字符数组作为返回值

public char[] toCharArray().

public static void main(String[] args){
    //转换成字符数组
    char[] chars = "hello".toCharArray();
    Sysetm,out.println(chars[0]);//h
}

2.获取当前字符串底层的字节数组。如 a -- 97

public byte[] getBytes();

byte[] bytes = "abc".getBytes();
for(int i = 0;i< bytes.length;i++){
    System.out.println(bytes[i]);
}

3.字符串内容替换

public String replace (CharSequence target,CharSequence replacement) :将与target匹配的字符串使 用replacement字符串替换。

String lang1 = "会不会玩啊~你大爷的!你大爷的!!!";
String lang2 = lang1.replace("你大爷的","****");
System.out.println(str2);

8.分割字符串

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

注意事项:

split方法的参数其实是一个“正则表达式”。

如果按照英文句点切割必须写成"."(两个反斜杠)

String[] str1 = "ccc,ddd,eee";
String[] array1 = str1.split(",");
for(int i = 0,i<array.length;i++){
    System.out.println(array1);
}

String[] str1 = "ccc.ddd.eee";
String[] array1 = str1.split("\.");
for(int i = 0,i<array.length;i++){
    System.out.println(array1);
}

9.String类的练习

1.题目:定义一个方法,把数组{1,2,3}按照指定个格式拼接成一个字符串。格式参照如下:[word1#word2#word3]。

知识点:指定格式拼接字符串
定义一个方法,把数组{1,2,3}按照指定个格式拼接成一个字符串。格式参照如下:[word1#word2#word3]。
思路:
1.自定义一个int【】数组,内容1,2,3
2.定义一个方法,将数组编程字符串
三要素:
返回值类型:String
方法名称:fromArrayToString
参数列表:int[]
3.格式:[word1#word2#word3]
用到:for循环、字符串拼接、每个数组元素之前都有一个word字样、分隔使用的是#、区分一下最后一个不是
4.调用方法,得到返回值,并打印结果字符串

public static void mian(String[] args){
    int[] array = {1,2,3};
    String result =arrayToString(array);
    System.out.println(result);
}
public static String arrayToString(int[] array){
    String str = "[";
    for(int i= 0;i < array.length;i++){
        if(i == array.length -1){
            str += "word"+array[i]+"]";
        }else{
            str += "word"+array[i]+"#"
        }   
    }
	return str;
}

2.题目:键盘录入一个字符,统计字符串中大小写字母及数字字符个数

public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    System.out.print("请输入字符串:");
    String input = sc.next();//获取键盘输入的一个字符串
    
    int countUpper =0;//大写字母
    int countLower =0;//小写字母
    int countNumber = 0;//数字
    int countOther = 0;//其让他字符
    
    char[] charArray = input.toCharArray();
    for(int i = 0;i< charArray.length;){
        char ch = charArray[i];
        if('A'<= ch && ch <= 'Z'){
        countUpper++;
        }
    }else if('a'<= ch && ch <='z'){
        countLower++;
    }else if('0' <= ch && ch <='z'){
        countNumber++;
    }else{
        countOther++;
    }
} 

 System.out.println("大写字母有:"+countUpper);
        System.out.println("小写字母有:"+countLower);
        System.out.println("数字有:"+countNumber);
        System.out.println("其他字符有"+countOther);

第二章 Static关键字

2.1概述

若一个成员变量使用了static关键字,那么这个变量属于所在类。多个对象共享一份数据。

2.2 定义和使用格式

当static修饰成员变量的时候,该变量称为类变量。该类的每一个对象都共享同一个变量值。任何对象都可以调用该类变量的值,但也可以在不创建该类对象的情况下对类变量进行操作。

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

定义格式:

static 数据类型 变量名;

举例:

static int numberID;

代码如下:

比如说,基础班新班开班,学员报到。现在想为每一位新来报到的同学编学号(sid),从第一名同学开始,sid为 1,以此类推。学号必须是唯一的,连续的,并且与班级的人数相符,这样以便知道,要分配给下一名新同学的学号是多少。这样我们就需要一个变量,与单独的每一个学生对象无关,而是与整个班级同学数量有关。

所以,我们可以这样定义一个静态变量numberOfStudent,代码如下:

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

public static void mina(String[] args){
    Student s1 = new Student("黑猫警长",12);
    Student s2 = new Student("金刚葫芦娃",22);
    Student s3 = new Student("喜洋洋",11);
    Student s4 = new Student("懒洋洋",10);
    
    s1.show();//学生:黑猫警长,年龄:12,学号:1
    s2.show();//学生:金刚葫芦娃,22,学号:2
    s3.show();
    s4.show();
}

静态方法

当static修饰成员方法时,该方法称为类方法。或静态方法

静态方法在声明中有static,建议使用类名来调用,不需要创建类的对象。

注意事项:

1.静态不能直接访问非静态

原因:因为内存中【先】有的静态内容,【后】有的非静态内容。

“先人不知道后人,后人知道先人”

2.静态方法中不能用this。

原因:this代表当前对象,通过谁调用的方法,谁就是当前对象。

代码如下

public class MyClass {
    int num;//成员变量
    static int numStatic;//静态变量

    //成员方法
    public void method(){
        System.out.println("这是一个成员方法。");
        //成员方法可以访问成员变量
        System.out.println(num);
        //成员方法可以访问静态变量
        System.out.println(numStatic);
    }

    //静态方法
    public static void methodStatid() {
        System.out.println("这是一个静态方法。");
        //静态方法可以访静态变量
        System.out.println(numStatic);
        //静态不能直接方法非静态【重点】
    //    System.out.println(num);//错误写法

        //静态方法中不能使用this关键字
     //   System.out.println(this);//错误写法
    }
}

    public static void main(String[] args) {
        MyClass obj = new MyClass();//首先创建对象
        //然后才能使用没有static关键字的内容
        obj.method();

        //对于静态方法来说,可以通过对象名进行调用,也可以通过类名称来调用
        obj.methodStatid();//不推荐,这种写法在编译后也会被javac翻译成为”类名称.静态方法“
        MyClass.methodStatid();//正确  推荐
    }

2.3 静态原理图解

static修饰的内容:

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

2.4 静态代码块

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

格式:

public static ClassNume{
    static{
        //静态代码块
    }
}

作用:给类变量进行初始化赋值。

代码如下:

public class Person{
    static {
        System.out.println("静态代码块执行了!");
    }
    public static Person(){
          System.out.println("构造方法执行了~");
    }
}

public static void main(String[] args){
    Person one = new Person();
    Person two = new Person();
}

/*
运行结果:
静态代码块执行了!
构造方法执行了~
构造方法执行了~
*/

小贴士:

static 关键字,可以修饰变量、方法和代码块。在使用的过程中,其主要目的还是想在不创建对象的情况 下,去调用方法。

第三章 Arrays类

3.1 概述

java.util.Arrays 此类包含用来操作数组的各种方法,比如排序和搜索等。其所有方法均为静态方法。

3.2 操作数组的方法

1.将参数数组变成字符串

public static String toString(数组);

public static void mian(String[] args){
    //定义一个int数组
    int[] arr = {1,3,5,6};
    //打印数组,输出地址值
   System.out.println(arr);//[I@2ac1fdc4
  	//将数组内容转换称为字符串
    String s = Arrays.toString(arr);
    //打印字符串,输出内容
    System.out.println(s);//[1,3,5,6]
    
}

2.对指定的类型数组按升序进行排序

public static void sort(数组);

备注:

  1. 如果是数值,sort默认按照升序从小到大
  2. 如果是字符串,sort默认按照字母的升序
  3. 如果是自定义的类型,那么这个自定义的类需要有Comparable或者Comparator接口的支持
int[] array1 = {1,5,3,2,6};
Arrays.sort(array1);
System.out.println(array1);//[I@1b6d3586
System.out.println(Arrays.toString(array1));//[1,2,3,5,6]

String[] array2 = {"cc","bb","ee"};
Arrays.sort(array2);
System.out.println(array2);//[I@1b6d3586
System.out.println(Arrays.toString(array2));//[bb,cc,ee]

3.3 练习

请使用 Arrays 相关的API,将一个随机字符串中的所有字符升序排列,并倒序打印

public static void main(String[] args){
    //定义随机字符串
    String str = "asf25612gprkvxc";
    //转换成为字符数组
    char[] chars = str.toCharArray();
    //升序排列
    Arrays.sort(chars);
    //反向遍历
    for(int i = chars.length-1;i>=0;i--){
        System.out.println(char[i]);
    }
}

第四章 Math类

4.1 概述

java.lang.Math 类包含用于执行基本的数学运算的方法,如初等指数、对数、平方根和三角函数。

类似这样的工具类,其所有方法均为静态方法,并且不会创建对象,调用起来很简单。

4.2 基本运算

1.获取绝对值

有多种重载。

public static double abs(double num);

System.out.println(Math.abs(3.16));//3.16
System.out.println(Math.abs(-3.16));//3.16

2.向上取整

public static double ceil(double num);

System.out.println(Math.ceil(3.1));//4.0
System.out.println(Math.ceil(3.0));//3.0

3.向下取整

public static double floor(double num);

System.out.println(Math.floor(3.99));//3.0
System.out.println(Math.floor(-3.01));//-4.0

4.四舍五入

public static double round(double num);

System.out.println(Math.round(3.36));//3.0
System.out.println(Math.round(3.69));//4.0

5.Math.PI代表近似的圆周率

4.3 练习

请使用 Math 相关的API,计算在 -10.8 到 5.9 之间,绝对值大于 6 或者小于 2.1 的整数有多少个?

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++ ){
        //获取绝对值并判断
        double abs = Math.abs(i);
        if(abs >6 || abs < 2.1){
            System.out.print(abs);
            count++;
        }
    }
    System.out.println("个数为:"+count);
}
原文地址:https://www.cnblogs.com/anke-z/p/12379898.html