08 String类、static、Arrays类、Math类

String类、static、Arrays类、Math类

一、字符串

1. 字符串概述和特点

  • 概念:
    • java.lang.String类代表字符串。
    • 程序当中所有的双引号字符串,都是String类的对象(就算没有new,也照样是)。
  • 特点:
    • 字符串的内容永不可变。
    • 因为字符串永不可变,所以字符串是可以共享使用的。
    • 字符串效果相当于是char[]字符数组,但是底层原理是byte[]字节数组。

2. 字符串的构造方法和直接创建

  • 三种构造方法

    • public String():创建一个空白字符串,不含有任何内容。
    • public String(char[] array):根据字符数组的内容,来创建对应的字符串。
    • public String(byte[] array):根据字节数组的内容,来创建对应的字符串。
  • 一种直接创建

    • String str = "Hello";
    public class Demo01String {
        public static void main(String[] args) {
            //无参构造
            String str1 = new String();
            System.out.println("第一个字符串为:" + str1); // 第一个字符串为:
    
            //使用字符数组来创建字符串
            char[] ch = {'A', 'B', 'C'};
            String str2 = new String( ch );
            System.out.println("第二个字符串为:" + str2); // 第二个字符串为:ABC
    
            //使用字节数组来创建字符串
            byte[] bt = {97, 98, 99};
            String str3 = new String( bt );
            System.out.println("第三个字符串为:" + str3); // 第三个字符串为:abc
    
            //直接创建
            String str4 = "Hello,World!";
            System.out.println("第四个字符串为:" + str4); // 第四个字符串为:Hello,World!
        }
    }
    

3. 字符串的常量池

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

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

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

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

  • 注意:
    • 对于引用类型来说,==进行的是地址值的比较。
    • 双引号直接写的字符串在常量池当中,new的不在池中。

4. 字符串的比较相关方法

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

    • public boolean equals(Object obj)参数可以是任何对象,只有参数是一个字符串并且内容相同时才会返回true;否则返回false
    • public boolean equalsIgnoreCase(String str)忽略大小写,进行内容比较。
  • 注意

    • 任何对象都可以使用object接收。
    • equals方法具有对称性,也就是a.equals(b)b.equals(a)效果一样。
    • 如果比较双方一个常量一个变量,推荐把常量字符串写在前面。如"abc".equals(str);
    public class StringEquals {
        public static void main(String[] args) {
            String str1 = "abc";
            String str2 = "abc";
            char[] chars = {'a','b','c'};
            String str3 = new String(chars);
    
            System.out.println(str1.equals(str2)); // true
            System.out.println(str2.equals(str3)); // true
            System.out.println(str1.equals("abc")); //true
            System.out.println("abc".equals(str3)); // true
    
            String str4 = null;
            System.out.println("abc".equals(str4)); // 推荐 false
            //System.out.println(str4.equals("abc")); // 不推荐 程序报错:空指针异常
    
            String str5 = "Abc";
            System.out.println(str5.equals(str1)); // false
            System.out.println(str5.equalsIgnoreCase(str1)); // true
        }
    }
    

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

  • public int length()获取字符串中含有的字符的个数,拿到字符串的长度。

  • public String concat(String str)将当前字符串和参数字符串拼接成为新的字符串返回。

  • public char charAt(int index)获取指定索引位置的单个字符(索引从0开始)。

  • public int indexOf(String str)查找参数字符串在原本字符串当中首次出现的索引位置,如果没有返回-1值。

    public class StringGet {
        public static void main(String[] args) {
            String str1 = "shvbhfsvghdgjf";
            System.out.println("字符串的长度为:" + str1.length()); //字符串的长度为:14
    
            String str2 = "Hello";
            String str3 = "World";
            String str4 = str2.concat(str3);
            System.out.println("拼接后的字符串为:" + str4); // 拼接后的字符串为:HelloWorld
    
            String str5 = "zhuguli";
            char ch = str5.charAt(3);
            System.out.println("索引处为3的字符为:" + ch); // 索引处为3的字符为:g
    
            String str6 = "HelloHello";
            int index1 = str6.indexOf("llo");
            System.out.println("子字符串第一次出现的索引值为:" + index1); // 子字符串第一次出现的索引值为:2
            int index2 = str6.indexOf("ool");
            System.out.println("子字符串第一次出现的索引值为:" + index2); // 子字符串第一次出现的索引值为:-1
        }
    }
    

6. 字符串的截取方法

  • public String substring(int index)截取从参数位置一直到字符串末尾,返回新字符串。
  • public String substring(int begin, int end)截取从begin开始,一直到end结束,中间的字符串。
    • [begin, end)包含左边,不包含右边。
public class Substring {
    public static void main(String[] args) {
        String str = "HelloWorld";
        String substring1 = str.substring(5); // world
        System.out.println(substring1);
        String substring2 = str.substring(2, 5); // llo
        System.out.println(substring2);
    }
}

7. 字符串的转换相关方法

  • public char[] toCharArray() 将当前字符串拆分成为字符数组作为返回值。

  • public byte[] getBytes() 获得当前字符串底层的字节数组。

  • public String replace(CharSequence oldString, CharSequence newString) 将所有出现的老字符串替换成为新的字符串,返回替换之后的结果新字符串。

    CharSequence意思就是可以接受字符串类型。

public class StringConvert {
    public static void main(String[] args) {
        
      String str1 = "HelloWorld!";
        char[] chars = str1.toCharArray();
        System.out.println(chars.length);
        for (int i = 0; i < chars.length; i++) {
            System.out.println(chars[i]);
        }
      
        String str2 = "abcde";
        byte[] bytes = str2.getBytes();
        System.out.println(bytes.length);
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);
        }
      
        String str3 = "how do you do?";
        String newStr3 = str3.replace("o", "*");
        System.out.println(str3);
        System.out.println(newStr3);
    }
}

8. 字符串的分割方法

  • public String[] split(String regex)按照参数的规则,将字符串切分成为若干部分。
  • 注意事项
    • split方法的参数实际上第一个“正则表达式”,这里先做了解。
    • 若要按照英文句点“.”进行切分,必须写成"\\."
public class StringSplit {
    public static void main(String[] args) {
        String str1 = "aaa,bbb,ccc";
        String[] strings1 = str1.split(",");
        for (int i = 0; i < strings1.length; i++) {
            System.out.println(strings1[i]);
        }
        System.out.println("==========");
        String str2 = "aaa.bbb.ccc";
        String[] strings2 = str2.split("\\.");
        for (int i = 0; i < strings2.length; i++) {
            System.out.println(strings2[i]);
        }
    }
}

9. 字符串练习

//1.定义一个方法,把数组[1,2,3]按照指定格式拼接成一个字符串。
//格式参照如下:[word1#word2#word3]
public class StringPrac01 {
    public static void main(String[] args) {
        int[] arrays = {1, 2, 3};
        System.out.print("[");
        for (int i = 0; i < arrays.length; i++) {
            if (i != arrays.length-1) {
                System.out.print(("word" + arrays[i]).concat("#"));
            }else {
                System.out.println(("word" + arrays[i]).concat("]"));
            }
        }
    }
}

//2.键盘输入一个字符串,并且统计其中各种字符出现的次数。
//种类:大写字母、小写字母、数字、其他
import java.util.Scanner;

public class StringPrac02 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串为:");
        String str = sc.next();
        System.out.println("输入的字符串为:" + str);
        char[] chars = str.toCharArray();
        int count1=0, count2=0, count3=0, count4=0;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] >= 'A' && chars[i] <= 'Z'){
                count1++;
            }else if (chars[i] >= 'a' && chars[i] <= 'z') {
                count2++;
            }else if (chars[i] >= '0' && chars[i] <= '9') {
                count3++;
            }else {
                count4++;
            }
        }
        System.out.println("字符串中大写字母的个数为:" + count1);
        System.out.println("字符串中小写字母的个数为:" + count2);
        System.out.println("字符串中数字的个数为:" + count3);
        System.out.println("字符串中其他字符的个数为:" + count4);
    }
}

二、static

1. 概述

  • 一旦使用了**static关键字**,那么这样的内容不再属于对象自己,而是属于类的,所以凡是本类的对象,都共享同一份

2. 静态static关键字修饰成员变量

  • 如果一个成员变量使用了static关键字,那么这个变量不再属于对象自己,而是属于所在的类。多个对象共享同一份数据。
public class Student {
    private String name;
    private int age;
    static String classroom;   // 静态成员变量,属于类
    private static int id = 0; // 每当new一个新对象时,计数器++

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

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

    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 static int getId() {
        return id;
    }

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

public class UseStudent {
    public static void main(String[] args) {
        Student stu1 = new Student("朱古力", 18);
        stu1.classroom = "101班";
        // 姓名:朱古力,年龄:18,班级:101班,学号:1
        System.out.println("姓名:" + stu1.getName() + ",年龄:" + stu1.getAge()
                + ",班级:" + stu1.classroom + ",学号:" + stu1.getId());  
			  
        Student stu2 = new Student("猪猪侠", 20);
        // 姓名:猪猪侠,年龄:20,班级:101班,学号:2
        System.out.println("姓名:" + stu2.getName() + ",年龄:" + stu2.getAge()
                + ",班级:" + stu2.classroom + ",学号:" + stu2.getId()); 
    }
}

3. 静态static关键字修饰成员方法

  • 一旦使用了static修饰成员方法,那么这就成为了静态方法。静态方法不属于对象,而是属于类的。
  • 如果没有static关键字,那么必须首先创建对象,然后通过对象才能使用它。
  • 如果有了static关键字,那么不需要创建对象,直接就能通过类名称来使用它。
  • 无论是成员变量,还是成员方法。如果有了static,都推荐使用类名称进行调用。
    • 静态变量:类名称.静态变量;
    • 静态方法:类名称.静态方法();
  • 注意事项:
    • 静态不能直接访问非静态。
      • 原因:因为内存中是“先”有的静态内容,“后”有的非静态内容。
    • 静态方法中不能使用this关键字。
      • 原因:this代表当前对象,通过谁调用方法,谁就是当前对象。
public class MyClass {

    //成员变量
    private int num;
    //静态变量
    private static int numStatic;

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

public class UseMyClass {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        //通过对象调用成员方法
        obj.method();
        //通过对象调用静态方法
        obj.methodStatic();  // 正确,但不推荐使用 这种写法在编译之后也会被javac翻译成"类名称.静态方法名"
        //通过类调用静态方法
        MyClass.methodStatic(); // 正确 推荐使用

        //对于本来类中的静态方法,可以省略类名称
        myMethod();
        UseMyClass.myMethod(); // 完全等效
    }

    public static void myMethod() {
        System.out.println("自己的方法。");
    }
}

4. 静态static的内存图

  • 注意:根据类名称访问静态成员变量的时候,全程和对象没有关系,只和类有关系。

5. 静态代码块

  • 静态代码块的格式

    public class 类名称 {
      static {
        //静态代码块的内容
      }
    }
    
  • 特点:当第一次用到本类时,静态代码块执行唯一的一次。

  • 静态内容总是优先于非静态,所以静态代码块比构造方法先执行。

  • 静态代码块的**典型用途:**用来一次性的对静态变量进行赋值。

    public class Person {
        static {
            System.out.println("执行静态代码块");
        }
        public Person() {
            System.out.println("执行构造方法");
        }
    }
    
    public class UsePerson {
        public static void main(String[] args) {
            Person person1 = new Person();  // 执行静态代码块
                                            // 执行构造方法
            Person person2 = new Person();  // 执行构造方法
        }
    }
    

三、数组工具类Arrays

  • java.util.Arrays;是一个与数组有关的工具类,里面提供了大量的静态方法,用来实现数组常见的操作。
  • public ststic String toString(数组)将参数数组变成字符串(按照默认格式:[元素1,元素2...]
  • public static void sort(数组)按照默认升序对数组元素进行排序。
    • 如果是数值,默认按照升序。
    • 如果是字符串,默认按照字母升序。
    • 如果是自定义的类型,那么这个自定义的类需要有Comparable或者Comparator接口的支持。(先做了解)
import java.util.Arrays;

public class ArraysStudy {
    public static void main(String[] args) {
        int[] array1 = {1,2,3,4,5};
        System.out.println(Arrays.toString(array1)); // [1, 2, 3, 4, 5]

        int[] array2 = {5,3,8,1,4,0};
        Arrays.sort(array2);
        System.out.println(Arrays.toString(array2)); // [0, 1, 3, 4, 5, 8]

        String[] array3 = {"aaa","ccc","bbb","abc","aab"}; 
        Arrays.sort(array3);
        System.out.println(Arrays.toString(array3)); // [aaa, aab, abc, bbb, ccc]
    }
}
  • 练习

    //请使用Arrays相关的API,将一个随机字符串中的所有字符升序排列,并倒序打印
    import java.util.Arrays;
    
    public class ArraysPrac {
        public static void main(String[] args) {
            String str = "hdhvsgygdsbAGTdcfsSDfrsdc";
            System.out.println("原字符串为:" + str);
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            System.out.print("处理后的字符串为:");
            for (int i = chars.length - 1; i >= 0; i--) {
                System.out.print(chars[i] + " ");
            }
        }
    }
    

四、数学工具类Math

  • java.lang.Math类是数学相关的工具类,里面提供了大量的静态方法,完成与数学运算相关的操作。
  • public static double abs(double num)获取绝对值,有多种重载
  • public static double ceil(double num)向上取整
  • public static double floor(double num)向下取整
  • public static long round(double num)四舍五入
  • Math.PI代表近似的圆周率常量(double)
import java.lang.Math;
public class MathStudy {
    public static void main(String[] args) {
        //获取绝对值
        System.out.println(Math.abs(1.23)); // 1.23
        System.out.println(Math.abs(-1.23)); // 1.23

        //向上取整
        System.out.println(Math.ceil(1.1)); // 2.0
        System.out.println(Math.ceil(1.6)); // 2.0

        //向下取整
        System.out.println(Math.floor(1.1)); // 1.0
        System.out.println(Math.floor(1.6)); // 1.0

        //四舍五入
        System.out.println(Math.round(1.1)); // 1
        System.out.println(Math.round(1.6)); // 2

        //圆周率
        System.out.println(Math.PI); // 3.141592653589793
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值