JAVA--常用类

一、Java API概述

API_常用类

API(Application Programmering Interface)应用程序编程接口,是指java语言中提供的类和接口

API—>API文档 文档中对java语言中提供的类和接口的功能进行说明.

二、基本数据类型包装类

(一)基本类型---->8种

byte,short···

基本类型就是通过这8个关键字来进行声明,举个例子,

int a = 10;a的值就是10,结构简单,然而Java语言是一个面向对象的语言,但是Java中的基本数据类型却是不面 向对象的,这在实际使用时存在很多的不便,为了解决这个不足,在设计类时为每个基本数据类型设计了一个对应的类进行代表,这样八个和基本数据类型对应的类统称为包装类。

包装类(像Integer)这些类封装了一个相应的基本数据类型数值,并提供一些列操作方法。

关键字包装类名
byteByte
shortShort
charCharacter
intInteger
longLong
floatFloat
doubleDouble
booleanBoolean

(二)包装类型(这里以int为例)

Integer类最大最小值属性

public static final int   MAX_VALUE = 0x7fffffff;
public static final int   MIN_VALUE = 0x80000000;

构造方法

public Integer(int a){
    this.value = value;
}
public Integer(String a){
    
}

比较方法

static int compareTo(Integer a);

boolean equals(Object);

int max(int a,int b);

int min(int a,int b);

public class Integer1 {
    public static void main(String[] args) {
        /*
        Integer类,就是为基本类型int提供操作的一个类
        以下均调用Integer类中的方法
         */
        System.out.println(Integer.MAX_VALUE);
        System.out.println(Integer.BYTES);
        System.out.println(Integer.SIZE);
        /*
        //以下均为转换方法,10进制整型分别转为
        // 2进制字符串型,8进制字符串型,16进制字符串型
        System.out.println(Integer.toBinaryString(3));
        System.out.println(Integer.toOctalString(9));
        System.out.println(Integer.toHexString(15));
        //
        int c = Integer.parseInt("100");//字符串转整型(int)
        //System.out.println(c+5);
        Integer d = Integer.valueOf(10);// 把基本类型转换为包装类型
        //System.out.println(d+20);
        Integer e = Integer.valueOf("100");//把字符串数字转换为包装类型
        //System.out.println(e+22);
        */
        Integer.max(5,8);
        //通过构造方法,将字符串数字,基本类型值,包装到一个包装类对象中,使用面向对象方式进行操作
        Integer integer = new Integer("5");
        //System.out.println(integer+5);
        Integer integer1 = new Integer(5);
        //System.out.println(integer1+1);
        System.out.println(integer==integer1);
        //false  比较的是对象地址(十六进制数是否相等)
        System.out.println(integer.equals(integer1));
        //true 比较的对象中的内容 Integer中已经重写了equals()
        System.out.println(integer.compareTo(integer1));
        // 比较对象中的内容大小  0-相等 1-大于 -1:小于
        int a =  integer.intValue();
        //返回的是包装类型中的原始基本值
        //long b =  integer.longValue();
    }
}

转换方法

static toBinaryString(int i);

static String toHexString(int i);

static String toOctalString(int i);

int intValue();

static int parseInt(String s);

String toString();

static Integer valueOf(int i)

static Integer valueOf(String s)

​ 有些是静态的,通过类名直接调用
​ 有些是非静态的,需要通过包装对象去调用

(三)装箱和拆箱

装箱

​ 自动将基本数据类型转换为包装器类型

​ 装箱的时候自动调用的是Integer的valueOf(int)方法

拆箱

​ 自动将包装器类型转换为基本数据类型

​ 拆箱的时候自动调用的是Integer的intValue方法

//装箱 

int a = 12; 

Integer b = Integer.valueOf(a); 

//拆箱 

int c = b.intValue();
int a = 12; 

//自动装箱 

Integer b = a; 

//自动拆箱 

int c = b;
public class Integer4 {
    public static void main(String[] args) {
        /*
        把基本类型,直接赋给引用类型,进行包装,产生了一个Integer类的对象.
        称为自动装箱.
        Integer a = 127;  默认会调用 Integer Integer.valueOf(int i){ }
        在Integer类中为了节省空间,对-128--+127之间的255个对象进行缓存(数组)
        在-128 +127之间的时候,直接从数组获取,如果值相同的时候,取到的对象是相同的.
        如果不在-128 +127之间, 每次都会创建一个新的对象
        public static Integer valueOf(int i) {
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                  return IntegerCache.cache[i + (-IntegerCache.low)];
                    return new Integer(i);
                }
         [-128,-127,-126.....120,121,122..127]
         */
        Integer a = 127;
        Integer b = 127;
        System.out.println(a==b);//true
        System.out.println(a.equals(b));//true

        Integer e = 128;
        Integer f = 128;
        System.out.println(e==f);//false
        System.out.println(e.equals(f));//true

        Integer c = new Integer(127);
        Integer d = new Integer(127);
        System.out.println(c==d);//false  c,d都是new的,两个对象地址不同
        System.out.println(c.equals(d));//true
    }
}

三、Object

(一)引入

Object类是所有Java类的父类(基类)

一切对象都实现这个类的方法

如果说一个类没有用extends关键字指明其父类,默认继承Object类

public class Person { 

}
/*等同于
public class Person extends Object{
    
}
*/

(二)toString方法

Object类中定义有public String toString()方法,其返回值是 String

类型,描述当前对象的有关信息。

比如直接运行如下代码

System.out.println(person); 

看似输出对象,可实际输入的却是一个字符串,原因是:在输出对象时,会默认调用类中的toString()方法,如果没有该方法,则会调用父类中的toString()方法,而在Object类中该方法为

public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

对象存储在堆(内存)中,也就是说,会输出“该类的类名+@+对象的内存地址”

而我们想看对象中的值时,子类与父类实现上就会有所不同,即子类中重写toString(方法以达到预期要求。

(三)equals方法

== 比较引用类型时,实际上是比较对象在内存中的地址是否一致,如:

public boolean equals(Object obj) {
        return (this == obj);
    }

但大多数情况下我们需要比较对象中的内容

因此,我们必须重写Object类中的equals()方法,用来比较对象中的内容是否一致。像String类,Integer类···等,都重写了这一方法,如:

public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

当我们自己定义类,在比较时,一定要注意,是否重写了equals()方法,如果没有重写,则调用父类(Object)对地址进行比较,进而影响判断。

Ep:创建一个Person类,判断Person下俩个对象是否相等而重写equals()方法

public boolean equals(Object object){
        Person another = (Person)object;
        if(this == object){
            return true;
        }
        if(this.num==another.num&&this.name.equals(another.name)){
            return true;
        }
        return false;
    }

通过这一操作,即可完成预期的效果。

四、Arrays类

Arrays类是用于操作数组工具类,里面定义了常见操作数组的静态方法。

java.util.Arrays类

equals 方法

比较两个非同一数组是否相等,而数组本身的equals判断另一个数组是否它本身。

参数类型可以是基本数据类型,也可以是引用数据类型。

相等true不等false

(一)sort -排序 作用于数组的所有元素

import java.util.Arrays;

public class ArraysDemo2 {
    public static void main(String[] args) {
        int  [] a = {5,6,7,1,2,3,4};
       // Arrays.sort(a);// 对整个数组进行排序
        System.out.println(Arrays.toString(a));
        Arrays.sort(a,2,5);
        //d对数组进行排序 同样 [2,5) 前闭后开
        System.out.println(Arrays.toString(a));

        String []  arrays = {"b","c","d","a","g","s"};
        Arrays.sort(arrays);
        System.out.println(Arrays.toString(arrays));

    }
}

自定义对象排序

自定义类实现Comparable接口

重写compareTo方法

(二)binarySearch -使用二分搜索算法搜索指定数组

import java.util.Arrays;
// java.util.Arrays  包含许多数组操作的方法

public class ArraysDemo1 {
    public static void main(String[] args) {
        int []a = {1,2,3,4,5};
        int []b = {12,3,4,5,5,5};
        boolean res = Arrays.equals(a,b);
        // 比较俩数组中的内容是否一致,一一对比
        System.out.println(res);
        System.out.println(Arrays.toString(b));
        //可以自己实现
        int re= Arrays.binarySearch(a,6);
        //二分查找,要求数组有序排列
        int r = Arrays.binarySearch(b,2,4,5);
        //[2,4) 前闭后开
        System.out.println(r);
        System.out.println(re);
    }
}

(三)toString() 方法

返回指定数组内容的字符串表示形式。

基本数组,字符串表示形式由数组的元素列表组成,括在[],相邻元素 用“ , ”(逗号加空格)分隔

package com.ffyc.javaAPI.day1.arraysdemo;

public class Student implements Comparable<Student>{
    private int num;
    private  String name ;

    public Student(int num, String name) {
        this.num = num;
        this.name = name;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String toString(){
        return "Student{" +
                "num=" + num +
                ", name='" + name + '\'' +
                '}';
    }

   @Override
   public int compareTo(Student o){
        return this.num-o.num;//定义的是通过学号进行排序
   }
   /*
   compareTo 提供自定义排序比较规则的方法,
   此方法会在sort()方法的源码中调用
   返回值为整数
    */
}


import java.util.Arrays;

public class ArraysDemo2 {
    public static void main(String[] args) {
        /*
        int  [] a = {5,6,7,1,2,3,4};
       // Arrays.sort(a);// 对整个数组进行排序
        System.out.println(Arrays.toString(a));
        Arrays.sort(a,2,5);
        //d对数组进行排序 同样 [2,5) 前闭后开
        System.out.println(Arrays.toString(a));

        String []  arrays = {"b","c","d","a","g","s"};
        Arrays.sort(arrays);
        System.out.println(Arrays.toString(arrays));

         */
        Student student1 = new Student(101, "jim1");
        Student student2 = new Student(102, "jim2");
        Student student3 = new Student(103, "jim3");
        Student student4 = new Student(104, "jim4");
        Student[] students = new Student[4];
        students[0] = student4;
        students[1] = student2;
        students[2] = student3;
        students[3] = student1;
            /*
              使用 Arrays.sort(); 对我们自定义的数组对象进行排序
               Animal a = new Cat()
               Dog dog = (Animal)a; 类型比匹配问题
             */
        Arrays.sort(students);
        System.out.println(Arrays.toString(students));
        //这里对toString方法进行重写
    }
}

(四)Arrays.copyOf()数组扩容

package com.ffyc.javaAPI.day1.arraysdemo;

import java.util.Arrays;

public class ArraysDemo3 {
    public static void main(String[] args) {
        //扩容
        int [] a = {1,2,3,4,5,6,74,89,};
        /*
        int []b = new int [a.length*2];
        for(int i=0;i<a.length;i++){
            b[i]=a[i];
        }
        System.out.println(Arrays.toString(b));
        //自己实现
         */
        /*
        返回一个数组包含原数组中的内容,Arrays。copyOf(原数组,新数组长度);
        创建一个指定容量新数组,并把原来数组的内容复制到新数组中
         */
        int []b = Arrays.copyOf(a,a.length*2);
        System.out.println(Arrays.toString(b));
    }
}

五、String类/StringBuffer类/StringBuilder类

(一)String类的概述

是什么?

字符串是由多个字符组成的一串数据(字符序列)的字符串常量,java中所有字符串都是String类的实例

创建形式:

String s = "abc";

字符串:一串字符,字符串是由多个单个的字符组成的,

​ 只不过对外表示为一个整体的串

​ String s = “abc”;//地称实际还是一个一个的独立的字符

每一个单独的字符,在计算机中都是一个一个独立的,对应有一个编码表,

底层存储是一个数组 “abc”---->[“a”,“b”,“c”]

java中所有的字符串都是String类的对象,像"abc","fhs"都是String的对象,创建后值不能更改

String s1 = new String(“abc”);

在java中还可以进行

s1+=“de”;

s1+=“fgh”;

s1+=“ijk”;

看似s1的值被改变了,实际上,在底层程序中,s1+=“de”;则是在内存中重新创建了一个String对象,只不过将新的值赋给新创建的对象,用s1指向了该对象,原来的s1被java系统垃圾回收了,后面的类似.

(二)String对象的创建

1.字符串创建概述

如何创建字符串对象:

两种方法都会创建对象

1.String s1 = “abc”;

//隐式创建,会先去字符串常量池中检测,有没有对应的字符串对应,如果没有就会在字符串常量池中创建一个字符串对象,如果有误则会让s1指向这个字符串对象的地址

2.String s2 =new String(“def”);

//new 会创建新对象,每次创建的对象地址都是不一样的

Ep:

public class Stringdemo2 {
    public static void main(String[] args) {
        String s1 = "abc";//隐式创建,会首先在字符串常量池中检索是否有字符串对应,如果没有就会在字符串常量池中创建一个对象
        String s2 = "abc";//显然s2字符串与s1相对应,java会让s2指向s1的地址
        System.out.println(s1==s2);//true
        String s3 = new String("abc");
        String s4 = new String("abc");
        System.out.println(s3==s4);//false
        /*
        s3与s4都是String类的对象,分别指向不同的内存地址
         */
    }
}

2.String类中的构造方法

String();//无参构造

String(String s);//有参 String类型的参数

String(byte[] b);// 把byte数组转为字符串

String(char[] c); //把char数组转为String字符串

Ep:

package com.ffyc.javaAPI.day1.stringdemo;

import java.util.Arrays;

public class Stringdemo3 {
    public static void main(String[] args) {
        String s0 = new String();
        String s1 = new String("abc");
        byte [] bytes = "abc".getBytes();
        //getBytes方法将字符串转换为byte类型的数组
       // 编码
    System.out.println(Arrays.toString(bytes));
        //解码
        //Arrays.toString(bytes)方法将byte数组又转换为字符串
        String s3 = new String(bytes);
        System.out.println(s3);
        char [] chars = "bca".toCharArray();
        Arrays.sort(chars);
        String s = new String(chars);
        System.out.println(s);
    }
}

String(StringBuffer sb);

String(StringBuilder sb);

3.String类中的判断方法

boolean equals(Object obj) ;

boolean equalsIgnoreCase(String str) ;

boolean contains(String str) ;

boolean isEmpty() ;

boolean startsWith(String prefix) ;

boolean endsWith(String suffix);

boolean compareTo(String anotherString);

package com.ffyc.javaAPI.day1.stringdemo;

public class Stringdemo4 {
    public static void main(String[] args) {
        /*
        判断功能
    boolean equals(Object obj)//判断字符串是否一致
    boolean equalsIgnoreCase(String str)//判断字符串是否相等,忽略大小写
    boolean contains(String str)//判断字符串中是否包含指定子串
    boolean isEmpty()//判断字符串是否为空
    boolean startsWith(String prefix)//判断字符串是否以指定子串开始
    boolean endsWith(String suffix)//判断字符串是否以指定子串结束
    boolean compareTo(String anotherString)//两个字符串之间按照编码大小进行比较
         */
        String s = "abc";
        System.out.println(s.equals("abc"));
        System.out.println(s.equalsIgnoreCase("Abc"));
        System.out.println(s.contains("a"));
        System.out.println(s.isEmpty());
        System.out.println(s.startsWith("s"));
        System.out.println(s.endsWith("c"));
        System.out.println("a".compareTo("c"));
    }
}

4.String类中的获取方法

int length() ;

char charAt(int index) ;

int indexOf(String str) ;

int indexOf(String str,int fromIndex) ;

String substring(int start) ;

String substring(int start,int end);

    public static void main(String[] args) {
            /*
          获取功能
            int length()   //获取字符串长度
            char charAt(int index)  //获取指定位置的字符(与数组用法相似)
            int indexOf(String str)  //获取指定字符首次出现的位置
            int indexOf(String str,int fromIndex) //从指定的位置开始查找字符首次出现的位置
            String substring(int startIndex)  //截取字符串,从指定的位置开始,截取到最后一位
            String substring(int startIndex,int endindex) //截取字符串,从指定的位置开始,到指定位置结束  前闭后开
          */
        String s = "abcdefghi"; //[a,b,c,d,e,f,g,h,i]
                  //012345678
        System.out.println(s.length());
        // 9
        char c  = s.charAt(2);
        // c
        System.out.println(c);

        int index =  s.indexOf("c");
        System.out.println(index);
        // 2  c首次出现的索引,没有则输出-1
        int index1 =  s.indexOf("c", index+1);
        System.out.println(index1);
        // 第二次出现的索引,
        String sub = s.substring(2);
        //sub是一个新的字符串,s本身不变
        System.out.println(sub);
        //从第二位开始截取到最后一位
        String sub1 = s.substring(2,8);
        //从指定位置开始截取到指定位置,前闭后开
        System.out.println(sub1);
        System.out.println(s);


    }
}

5.String类中的转换功能

byte[] getBytes() ;

char[] toCharArray();

static String valueOf(char[] chs) ;

String toLowerCase() ;

String toUpperCase() ;

String concat(String str) ;

Stirng[] split(分割符);

import java.util.Arrays;

public class Stringdemo6 {
    public static void main(String[] args) {
        /*
                转换功能
                byte[] getBytes();  //将字符串转为byte数组
                char[] toCharArray();  //将字符串转为char数组
                static String valueOf(char[] chs); //将char数组转为字符串
                String toLowerCase();  //英文字母转小写
                String toUpperCase(); //英文字母转大写
                String concat(String str); //连接另一个字符串,返回一个新的字符串
                Stirng[] split(分割符); //按照指定的规则,将字符串拆分为数组
          */

        String s = "abcDEF";
        
        System.out.println(s.toLowerCase());
        //转小写
        System.out.println(s.toUpperCase());
        // 转大写
        String s1 = "sbl";
        /*
        s+=s1;
        s+=10;
        //除了字符串类型还可以连接其他类型
         */
        String s2 = s.concat(s1);
        //只能连接字符串
        System.out.println(s2);
        System.out.println(s1);
        System.out.println(s);

        String s3 = "ab,cde,ef,gh";  //[ab, cde, ef, gh]
        //正则表达式  规则表达式
        String[]  sarray =   s3.split(",");
        //以指定字符(一般是规定的字符)将字符串在底层分割为多个子串数组
        System.out.println(Arrays.toString(sarray));
    }
}

6.String类中的替换功能

String replace(char old,char new) ;

String replace(String old,String new);

replaceAll(String regex, String replacement) ;

replaceFirst(String regex, String replacement);

去除字符串两空格String trim()

public class Stringdemo7 {
    public static void main(String[] args) {
        /*
        ● 替换功能
          String replace(char old,char new)
          String replace(String old,String new)
          replaceAll(String regex, String replacement)
          replaceFirst(String regex, String replacement)
        ● 去除字符串两空格
          String trim()
         */
        String a = "asdfghjklsdfghjkl";
        System.out.println(a);
        String a1 = a.replace("s","b");
        System.out.println(a1);
        String a2 = a.replaceAll("sd","AA");//新字符替换指定所有子串,使用正则表达式匹配
         //                        "正则表达式"
        System.out.println(a2);
        String a3 = a.replaceFirst("sd","aa");//新字符替换指定所有子串,使用正则表达式匹配
        //                               "正则表达式"
        System.out.println(a3);
        String aa  = "  a  d  d  ";
        System.out.println(aa.length());
        String  b  = aa.trim();//去两端空格
        System.out.println(b);
        System.out.println(b.length());
        String s2  = " ab cd ";
        System.out.println( s2.replaceAll("\\s", ""));
                             //                  "正则表达式"         "这里并非正则表达式"
        //去所有空格
    }
}

(三)正则表达式

正则表达式
Regular Expression,在代码中常简写为regex、regexp或RE
即使用一些特定的字符来指定规则,然后用规则去匹配字符串
学习正则表示中常用的一些字符
使用字符串对象中的内容,去与指定的正则表达式匹配,匹配成功返回true,否则 返回false
s.matches(“正则表达式”);

public class Stringdemo8 {

    public static void main(String[] args) {
        //匹配数字
        String s = "13566556565";
        //boolean res  = s.matches("[0-9]");//限制在[0,9]一位数字
        //boolean res  = s.matches("[1,2,3,4]");//指定的数字且仅仅一位
        //boolean res  = s.matches("\\d");// "\d" == [0-9]  "\"转义符
        //boolean res  = s.matches("\\D");//"\D"匹配非数字类型   "\"转义符
        //boolean res  = s.matches("[0-9]?");// "?" 必须为[0,9]且出现一次或一次也没有
        //boolean res  = s.matches("[0-9]*");// "*" 必须为[0,9]且出现0次或多次
        //boolean res  = s.matches("[0-9]+");// "+" 必须为[0,9]且出现1次或多次
        //boolean res  = s.matches("[0-9]{6}");// "{n}"必须为[0,9]且字符串必须为指定长度
        //boolean res  = s.matches("[0-9]{6,}");// "{n,}"  长度至少为n
        //boolean res  = s.matches("[0-9]{6,9}");// "{n,m}"  长度至少为n,最大为m
        //boolean res  = s.matches("[1][3,5,7,8,9]\\d{9}");//
          //                     "手机号第一位 手机号第二位 手机号后九位 "
          //                      必须为1   必须在3.5.7.8.9中间  后面为九位
        boolean res  = s.matches("[1-9][0-9]{5,12}");//qq  数字 6 -13  第一位不能以0开头

        System.out.println(res);

    }
}
public class Stringdemo9 {

    public static void main(String[] args) {
         //字母字符
        String s = "13555556666@139.com";
        //boolean res  = s.matches("[a-z]+");//小写字母
        //boolean res  = s.matches("[A-Z]+");//大写字母
        //boolean res  = s.matches("[A-z]+");//不限大小写字母
        //boolean res  = s.matches("[a-z,A-Z]+");同样是不限制大小写字母的写法
        //boolean res  = s.matches("\\w+");//[a-z,A-Z,0-9,_]//无限制的任意字符
        //boolean res  = s.matches("[\\u4e00-\\u9fa5]+");//匹配汉字

        //邮箱规则?  有字母, 数字   @ qq/163/sina,yahu .com/com.cn
        boolean res = s.matches("\\w{6,15}@\\w{2,6}\\.(com|com\\.cn)");
        //                   "\\"转义符          "."可以匹配任意字符,因此再次需要转义" 
        System.out.println(res);
    }
}

(四)StringBuffer类

String 对象的值是不可改变的,需要经常拼接字符串时,就会创建多个字符串对象,造成浪费
创建大量的字符串对象,造成浪费

如果某些场景下,需要大量的拼接字符串时,就可以使用StringBuffer

StringBuffer: 线程安全 可变

public class StringBufferdemo {
        public static void main(String[] args) {
        /*
            String 对象的值是不可改变的,需要经常拼接字符串时,就会创建多个字符串对象,造成浪费
            String s = "aaa";
                    s+="ss"
                    s+="ss" +i
                    创建大量的字符串对象,造成浪费

             如果某些场景下,需要大量的拼接字符串时,就可以使用StringBuffer
             StringBuffer:  线程安全 可变

                    capacity  = 16
              new StringBuffer() //默认底层数组容量是16
                  StringBuffer(20) 指定底层数组容量  20
                  StringBuffer("abcd"); 容量= 内容长度+16
                  char[] value; 没有被final修饰,可以改变
         */
            StringBuffer s = new StringBuffer("abcd");//20  4+16
            s.append("efg"); //在末尾添加字符串,没有创建新的StringBuffer和底层数组对象
            s.append("efg");//当底层数组容量(20)满了,才会创建一个新的数组对象赋给value数组
            s.append("efg");
            s.append("efg");
            s.insert(1, "XX");//在指定的位置插入指定的字符串
            s.deleteCharAt(1);
            System.out.println(s);
            //  aXbcdefgefgefgefg
            s.delete(1,5); //删除指定区间的字符串  前闭后开
            System.out.println(s);
            //  aefgefgefgefg
            s.replace(2,5,"AA");//替换字符串  前闭后开
            System.out.println(s);
            //  aeAAfgefgefg
            s.reverse();//反转字符串
            System.out.println(s);
            //  gfegfegfAAea
            String s1  = s.substring(2,8);//截取时,返回一个新的字符串
            System.out.println(s1);//             前闭后开
            //  egfegf
            System.out.println(s);//原字符串不变
            //  gfegfegfAAea

            //StringBuffer ---> String
            // new String(s);// 把StringBuffer转为String类型
            // new StringBuffer(str); //  把String 类型转为StringBuffer类型
        }
}

(五)StringBuilder类

与StringBuffer类似只不过多线程不安全

与StringBuffer类似
StringBuilder: 线程不安全 可变的字符串

public class StringBuilderdemo {
        public static void main(String[] args) {
        /*
             与StringBuffer类似
             StringBuilder:  线程不安全 可变的字符串
             StringBuffer
         */
            //方法 一致
            StringBuffer s0 = new StringBuffer();
            s0.append("abc");
            System.out.println(s0);
            //  abc
            StringBuilder ss = new StringBuilder();
            ss.append("abc");
            System.out.println(ss);
            //  abc
            StringBuilder s = new StringBuilder("abcd");
            s.append("abc");
            s.append("abc");
            System.out.println(s);
            //  abcdabcabc
            s.insert(1,"123456");
            System.out.println(s);

        }
}

(六)String类、StringBuffer类、StringBuilder类区别

StringBuffer 是线程安全的 这个类中的方法上加了一个synchronized(同步锁)关键字,
StringBuilder 类中的方法没有加synchronized关键字,是多线程不安全

​ 不同点: StringBuffer是线程安全的
​ StringBuilder是线程不安全的(适合单线程情况)

​ 共同点:都是可变字符串对象

​ 底层都有一个char数组

​ char[] value; 创建之初,会创建一个指定容量的数组,增删改查都是在此数组上操作.

​ 数组如果空间不够,会新创建一个数组,Arrays.copyOf();

​ 最终实现,调用的都是AbstractStringBuilder父类中方法实现.

String,StringBuffer 和 StringBuilder区别
String 值不可改变 适用于少量拼接的
StringBuffer 可变 多线程安全的 适用于大量拼接的
StringBuilder 可变 多线程不安全的 适用于大量拼接的

六、Math类/Random类

(一)Math类

java.lang.Math提供了一系列静态方法用于科学计算;其方法的参数和

返回值类型一般为double型。

abs 绝对值

sqrt 平方根

pow(double a, double b) a的b次幂

max(double a, double b)

min(double a, double b)

random() 返回 0.0 到 1.0 的随机数

long round(double a) double型的数据a转换为long型(四舍五入)

public class Mathdemo {
        public static void main(String[] args) {
         /*
            Math类: 提供了许多关于数学运算的方法 例如平方根,四舍五入,三角函数
        ava.lang.Math提供了一系列静态方法用于科学计算;其方法的参数和
        返回值类型一般为double型。
        abs 绝对值
        sqrt 平方根
        pow(double a, double b) a的b次幂
        max(double a, double b)
        min(double a, double b)
        random() 返回 0.0 到 1.0 的随机数
        long round(double a) double型的数据a转换为long型(四舍五入)
          */

            System.out.println(Math.PI);
            System.out.println(Math.abs(-9));
            System.out.println(Math.sqrt(9));
            //public static native double pow(double a, double b);
            //native修饰的方法是本地方法(操作系统中的方法),没有方法体,java没有实现,直接调用C/C++系统
            System.out.println(Math.pow(2,3));
            System.out.println(Math.random());//返回0-1之间的随机数
            System.out.println(Math.round(5.4));//四舍五入
            System.out.println(Math.floor(5.9));//向下取整
            System.out.println(Math.ceil(5.1));//向上取整
            System.out.println(Math.max(2,5));//取较大值

        }
}

(二)Random类

Random类概述

此类用于产生随机数

构造方法

public Random()

成员方法

public int nextInt()

public int nextInt(int n)

package com.ffyc.javaAPI.day1.Random;

import java.util.Random;

public class Randomdemo {
    /*
       Random 用来提供随机数的类
     */
    public static void main(String[] args) {
        Random random = new Random();
        System.out.println(random.nextInt());//-56406944  160620115 返回的是int范围内的一个随机数
        System.out.println(random.nextLong());//-1767876175151788793  6032446241876459086返回的是long范围内的一个随机数
        //bound: n  [0,n-1]之间的随机数
        System.out.println(random.nextInt(35)+1);//0-34 1-35
        //33选 5
    }
}

七、Date类/Calendar类/ SimpleDateFormat类

(一)Date类

Date类代表当前系统时间

import java.util.Date;
//    java.util.Date
public class datedemo {

    public static void main(String[] args) {
        Date date =  new Date();
        System.out.println(date);// toString()--->Wed Dec 28 20:23:11 CST 2022
        System.out.println(date.getYear()+1900);
        System.out.println(date.getMonth()+1);//0,1,2,3,4,5,6,7,8,9...
        System.out.println(date.getDate());
        System.out.println(date.getDay());
        System.out.println(date.getHours());
        System.out.println(date.getMinutes());
        System.out.println(date.getSeconds());
        //返回的是自 1970.1.1 0:0:0 至今(程序运行的时间) 之间的毫秒差
        System.out.println(date.getTime()); //1672230632035L
    }
}

(二)Calendar类

Calendar类是一个抽象类

import java.util.Calendar;
import java.util.GregorianCalendar;

public class
calendardemo {
    public static void main(String[] args) {
        /*
        Calendar日历类,提供更为丰富的日历操作方法
        返回的是Calendar这个抽象类的子类对象
        //Calendar calendar = Calendar.getInstance();
         */
        Calendar calendar = new GregorianCalendar();
        //                  创建子类对象 格里高利历(公历)
        System.out.println(calendar);
        //java.util.GregorianCalendar[time=1681992531228,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=31,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2023,MONTH=3,WEEK_OF_YEAR=16,WEEK_OF_MONTH=4,DAY_OF_MONTH=20,DAY_OF_YEAR=110,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=8,HOUR_OF_DAY=20,MINUTE=8,SECOND=51,MILLISECOND=228,ZONE_OFFSET=28800000,DST_OFFSET=0]
        System.out.println(calendar.get(Calendar.YEAR));
        System.out.println(calendar.get(Calendar.MONTH)+1);
        System.out.println(calendar.get(Calendar.DATE));
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR));
        System.out.println(calendar.get(Calendar.WEEK_OF_YEAR));
        System.out.println(calendar.get(Calendar.DAY_OF_WEEK));
        System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
    }
}

(三)SimpleDateFormat

SimpleDateFormat 日期格式化类

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class simpledateformatdemo {
    public static void main(String[] args) throws ParseException {
        /*
           SimpleDateFormat  简单的日期格式化类

           java中表示日期:  new Date();new GregorianCalendar();
           在前端需要显示时,需要把java中的date对象,转为指定格式的字符串

           Date date = new Date();
           String s = date.getYear()+"-"+date.getMonth();
            拼接 不灵活
         */

        /*
        //把日期对象转为指定格式的字符串
        Date date = new Date();
        SimpleDateFormat simpleDateFormat =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
        //                                                        指定格式:2023-04-20 20:15:01 星期四
        String str = simpleDateFormat.format(date);
        System.out.println(str);

         */
        /*
           把字符串转为日期对象
           2001-1-1从前端获取都是String,如果需要获取年,月非常麻烦
           解决,把字符串日期转为date对象,就可以以面向对象的方式操作了
         */
        String birthdayStr = "2001-1-1";
        SimpleDateFormat simpleDateFormat =  new SimpleDateFormat("yyyy-MM-dd");
        Date date = simpleDateFormat.parse(birthdayStr);
        System.out.println(date.getYear()+1900);
        System.out.println(date.getMonth()+1);
        System.out.println(date.getDate());
    }
}

八、BigInteger/BigDecimal

(一)BigInteger

在 Java 中,有许多数字处理的类,比如 Integer类,但是Integer类有一定的

局限性。int 的最大值为 2^31-1

BigInteger类型的数字范围较Integer,Long类型的数字范围要大得多,它支

持任意精度的整数,也就是说在运算中 BigInteger 类型可以准确地表示任何

大小的整数值而不会丢失任何信息。

BigInteger类位于java.math包中

基本运算方法

add(),subtract(),multiply(),divide()


import java.math.BigInteger;

public class BigIntegerdemo {
    public static void main(String[] args) {
        BigInteger a = new BigInteger("1111111111111111111111111111111111111111");
        BigInteger b = new BigInteger("1111111111111111111111111111111111111111");
        BigInteger c = a.add(b);
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
    }
}

(二)BigDecimal

在计算机中不论是float 还是double都是浮点数,而计算机是二进制的,浮点数会失去 一定的精确度

根本原因是:十进制值通常没有完全相同的二进制表示形式;十进制数的二进制表示形式可 能不精确。只能无限接近于那个值.

double a = 1.0-0.9;

double b = 0.8-0.7;

System.out.println(a==b); // false

Java在java.math包中提供的API类BigDecimal

基本运算方法

add(),subtract(),multiply(),divide()


import java.math.BigDecimal;

public class BigDecimaldemo {
    public static void main(String[] args) {
        double a = 1.0-0.9;
        double b = 0.8-0.7;
        System.out.println(a);
        System.out.println(b);
        System.out.println(a==b);

        BigDecimal n1 = new BigDecimal("1.999999999999999999999999999999999999999999999999999999999999");
        BigDecimal n2 = new BigDecimal("0.888888888888888888888888888888888888888888888888888888888888");
        BigDecimal n3 = n1.subtract(n2);
        System.out.println(n3);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值