java基础之常用类

常用类

Object类

是类结构层次的根类(超类—>父类),所有的类都默认继承自Object

使用JDK提供的API文档学习常用类中的常用功能

API:Application Programming Interface:应用程序接口开发文档

getClass方法

Object功能类的getClass()方法

public final Class getClass();//表示正在运行的类  (就是字节码文件对象)

先去使用Class类(反射的时候去使用):

功能:public String getName():获取当前类的全限定名称(包名.类名)

Object类中的getClass()/finalize()/hashCode()以及以后常用类。功能中如果native关键字:本地方法,非java语言底层实现

面试题:

获取一个类的字节码文件对象有几种方式?

三种
第一种:通过Object类的getClass()—>Class :正在运行的java类: class 包名.类名
第二种:任意Java类型的class属性----获取当前类的字节码文件对象Class
第三种:Class里面forName(“类的全限定名称(包名.类名)”) ; (使用最多)

public class ObjectTest01 {

    public static void main(String[] args) throws ClassNotFoundException {
        //创建一个学生类对象
        Student s = new Student();
        Class c1 = s.getClass();
        System.out.println(c1);//HemoWork.day15.ObjectTest.Student    class 包.类名
        Class c2 = s.getClass();
        System.out.println(c2);//HemoWork.day15.ObjectTest.Student   class 包名.类名
        System.out.println(c1 == c2);
        //==在基本数据类型里面:比较的是数据值相同,在引用类型:比较的是两个对象的地址值是否相同
        
        // ①Class ---->HemoWork.day15.ObjectTest.Student
        String name1 = c1.getName();
        String name2 = c2.getName();
        System.out.println(name1);
        System.out.println(name2);

        //Class类中public static Class forName(String classname): 后期反射中使用
        Class c3 = Class.forName("HemoWork.day15.ObjectTest.Student");//③Class里面forName("类的全限定名称(包名.类名)") ;
        System.out.println(c1 == c3);
        System.out.println(c2 == c3);
        
        Class c4 = Student.class; //②任意Java类型的class属性----获取当前类的字节码文件对象Class
        System.out.println(c4);
        System.out.println(c1 == c4);
        System.out.println(c2 == c4);
        System.out.println(c3 == c4);
    }
}

class Student {
    public static void get() {
        System.out.println("get student");
    }
}

toString方法

Object的public String toString();

返回对象的字符串表示形式。结果应该是一个简明扼要的表达,容易让人阅读。建议所有子类覆盖此方法。

大部分的常用类或者后面的集合都会重写Object类的toString()

public class ObjectDemo {
    public static void main(String[] args) {

        //通过有参构造方法创建一个学生对象
        Student s = new Student("高圆圆",42) ;
        //直接输出对象名称 --->会默认调用它的父类:Object的toString方法
        System.out.println(s);//com.qf.object_06.Student@1540e19d
        System.out.println("-----------------------------------");

		/*
          Object类的toString方法的原码
          public String toString() {
                  return getClass().getName() + "@" + Integer.toHexString(hashCode());
          }
         
          Integer类:int类型的包装类类型
          public static String toHexString(int i) :将整数转换成16进制数据结果以String类型展示
         */
        						        /*System.out.println(s.getClass().getName()+"@"+Integer.toHexString(s.hashCode()));
        System.out.println(s.toString());*/
        System.out.println(s.toString());
        
    }
}

equals方法&hashCode方法

Object类的equals方法

public boolean equals(Object obj){}//判断当前obj对象是否和当前对象想等

Object类中的equals的源码:

public boolean equals(Object obj) {
         return (this == obj);  return s1 == s2 ;  // ==:引用类型:比较的是地址值是否相同
}
面试题

equals和==的区别?

==: 连接的基本数据类型,比较的是数据值否相同

==: 连接的是引用类型,比较的是地址值是否相同

equals方法:如果使用Object默认的:底层用==,默认比较的还是两个对象的地址值是否相同,

         Student s1  = new Student("文章",35) ;
         Student s2  = new Student("文章",35) ;

s1和s2虽然地址值不同,他们的成员的内容相同,认为他是同一个人,但是如何让s1.equals(s2)为true:针对equals来说比较的是成员信息内容是否相同;

重写Object的equals方法同时还需要重写hashCode,内容相同,还需要比较哈希码值相同

重写之后,就比较的是成员信息的内容是否相同!

Object类的hashCode方法

public int hashCode()://(了解)获取对象的一个哈希码值 (本质不是地址值,可以把它理解为地址值)----跟哈希表有关系(HashMap)

一般情况:不同的对象获取的哈希码值是不同的 ,(但是中文字符,可能内容不一样,但是哈希码值不同!)

public class ObjectDemo {
    public static void main(String[] args) {
        int a = 10 ;
        int b = 15 ;
        System.out.println(a==b);//==链接的基本数据类型:比较的是数据值否相同
        System.out.println("--------------------------------------------");

        Student s1 = new Student("文章",35) ;
        System.out.println(s1);
        Student s2 = new Student("文章",35) ;
        System.out.println(s2);
        System.out.println(s1 == s2);

        System.out.println("--------------------------------------");

        //public boolean equals(Object obj)//Object obj = new Student() ;多态
        System.out.println(s1.equals(s2));
        //没有重写之前:执行的是Object类的equals()
        //重写之后,就比较的是对象的成员信息是否一致!

        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
        System.out.println("文章".hashCode());
        System.out.println("---------------------------------------------");

//      String类型(大部分常用类都会重写equals)重写Object的equals方法,所以比较内容是否相同
        String str1 = "hello" ;
        String str2 = "hello" ;
        System.out.println(str1.equals(str2));
        String str3 = "world" ;
        String str4  = new String("world") ;

        System.out.println(str3.equals(str4));

    }
}

clone方法

protected Object clone() throws CloneNotSupportedException;
//创建对象并返回该对象的副本,这个方法会抛出一个异常,throws:表示的是可能出现异常,针对调用者必须进行处理

要使用clone方法,当前某个对象所在的类必须实现"标记接口"Cloneable(没有字段(成员变量),也没有成员方法)

实现这个接口,那么就可以使用Object的clone()方法

public class ObjectDemo {
    public static void main(String[] args) throws CloneNotSupportedException{
        
        //创建学生对象
        Student s1 = new Student("高圆圆",42) ;
        System.out.println(s1);
        System.out.println(s1.getName()+"---"+s1.getAge());

        System.out.println("-----------------------------------");
        //调用克隆方法clone()
        Object obj = s1.clone(); //浅克隆:将s1地址值赋值给Objet
        //向下转型
        Student s2 = (Student) obj;
        System.out.println(s2);
        System.out.println(s2.getName()+"---"+s2.getAge());

        System.out.println("-----------------------------------");
        //传统方式
        Student s3 = s1 ;
        System.out.println(s3.getName()+"---"+s3.getAge());

    }
}

Scanner类

Scanner类:文本扫描器 java.util.Scaner ;

构造方法:

public Scanner(InputStream source);//创建一个文本扫描器

//形式参数是一个抽象类,在System类中
public final static InputStream in = null;

//本地方法(非Java语言实现)
private static native void setIn0(InputStream in);//底层方法一定会创建系统资源---->读取用户输入的字符(整数,字符串...)

Scanner类提供判断功能:防止出现输入的类型和结果类型不匹配!

	public boolean hasNextXXX():判断下一个录入的是否为指定的XXX类型
	XXX nextXXX() 获取功能
eg.
	public boolean hasNextInt()
	int nextInt()

如果先录入int,在录入String,录入的字符串数据被漏掉

解决方案;
1)直接使用next();
2)在使用nextLine()之前,在创建Scanner对象即可。

eg.拥有登录功能的猜数字游戏:

import java.util.Scanner;

public class Game {
    public static void main(String[] args) {

        Game game = new Game();
        game.Start();

    }

    //登录
    public void Start() {

        String Username = "admin";
        String Password = "admin";

        int count = 3;

        while (count > 0) {

            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入账号:");
            String name = scanner.nextLine();
            System.out.println("请输入密码");
            String pwd = scanner.nextLine();

            if (name.equals(Username) && pwd.equals(Password)) {
                System.out.println("登录成功!");
                guess();
                break;
            } else {
                System.out.println("您输入的账号或密码有误,请重新输入。");
                System.out.println("您还有" + count + "次机会");
                count--;
            }

        }

    }

    //猜数字
    public void guess() {
        int b = (int) (Math.random() * 100 + 1);

        Scanner scanner = new Scanner(System.in);

        int count = 0;

        while (true) {

            System.out.println("请输入一个数字:");
            int a = scanner.nextInt();

            if (a > b) {
                System.out.println("猜大了");
            } else if (a < b) {
                System.out.println("猜小了");
            } else {
                System.out.println("猜对了!");
                System.out.println("用了"+(count+1)+"次就猜对啦!");
                break;
            }
            count ++;

        }
    }

}

String类

概念

字符串是一个常量,一旦被赋值了,其值(地址值)不能被更改

推荐的使用方式:

String 变量名 = "xxxx" ;//xxxx代表 的当前String的实例

String类常用的功能:

int length();//获取字符串长度
public String(byte[] bytes,字符集);//使用指定的字符集,将字节数组构造成一个字符串
public String(byte[] bytes,int offset,int length);//将指定的部分字节数组转换成字符串	参数1:字节数组对象,参数2;  指定的角标值;  参数3:指定长度
public String(char[] value);//将字符数组构造成一字符串
public String(char[] value,int offset,int count);//将部分字符数组转换成字符串
public String(String original)//构造一个字符串,参数为字符串常量
面试题1:

在数组中有没有length方法?在String类中有没有length方法?在集合中有没有length方法?

数组中没有length方法,有length属性

int[] arr = new int[3] ;
arr.length;

String类中有length()

集合中没有length(),有size()获取元素数

构造方法:

public String();//空参构造:空字符序列
public String(byte[] bytes);//将一个字节数组构造成一个字符串,使用平台默认的字符集(utf-8:一个中文对应三个字节) 解码
//编码和解码---保证字符集统一
//编码:将一个能看懂的字符串--->字节               
//解码:将看不懂的字节---->字符串                  

eg.

public class StringTest01 {
    public static void main(String[] args) throws UnsupportedEncodingException {

        String country = "中国";
        byte[] bytes = country.getBytes();
        System.out.println(Arrays.toString(bytes));

        String s = new String(country);
        System.out.println(s);

    }
}

运行结果

[-28, -72, -83, -27, -101, -67]
中国

面试题2:

String s1 = “hello” ;
String s2 = new String(“hello”) ;
在内存中分别创建了几个对象?

第一个创建了一个对象,直接在常量池创建,开辟常量池空间
第二个:创建了两个对象,一个堆内存中开辟空间,一个指向常量池(不推荐)

public class StringTest02 {
    public static void main(String[] args) {

        String s1 = "hello" ;
        String s2 = new String("hello") ;
        System.out.println(s1 == s2);//false
        System.out.println(s1.equals(s2));  //true   只管内容相同

    }
}
== 和equals

==:连接引用类型比较的是地址值

equals:默认比较地址值,但是String类重写equals方法,所以内容是否相同

字符串变量相加,常量池中先开空间,再拼接

字符串常量相加,先相加,然后看结果是否在常量池中存在;如果存在,直接返回当前地址值,如果不存在,在常量池开辟空间!

转换功能(重点)

byte[] getBytes() ;//将字符串转换成字节数组 (编码)
                   //如果方法为空参,使用平台默认的编码集进行编码(utf-8:一个中文对应三个字节)
byte[] getBytes(String charset);//使用指定的字符集进行编码
解码的过程:将看不懂的字节数----->String
String(byte[] bytes);//使用默认字符集进行解码
String(byte[] bytes,指定字符集)

编码和解码必须要保证字符集统一

字符集:

​ gbk :一个中文两个字节(中国中文编码表)
​ gb2312:gbk升级版(含义有一个中文字符:中国的中文编码表)
​ iso-8859-1:拉丁文码表
​ utf-8:任何的浏览器—>都支持 utf-8格式 (后期统一个)
​ unicode:国际编码表
​ JS:日本国际 电脑系统 一个字符集

Arrays静态功能:

public static String toString(int/byte/float/double...[] a);//将任意类型的数组---->String
public char[] toCharArray();//将字符串转换成字符数组
public String toString();//返回自己本身---"当前字符串的内容"
public String toUpperCase();//将字符串转换成大写
public String toLowerCase();//将字符串转换成小写
将字符串反转
//键盘录入字符串,将字符串进行反转(使用功能改进)  String转换功能
import java.util.Scanner;

public class Test02_2 {
    public static void main(String[] args) {

        //创建键盘录入对象
        Scanner sc = new Scanner(System.in);

        //提示并录入数据
        System.out.println("请您输入一个字符串:");
        String line = sc.nextLine();

        //调用功能
        String result = reverse(line);
        System.out.println(result);
    }

    //定义字符串反转功能

    public static String reverse(String s) {

        //定义一个结果变量
        String result = "";
        //将字符串转换成char[]
        char[] chs = s.toCharArray(); //转换功能
        for (int x = chs.length - 1; x >= 0; x--) {
            result += chs[x];
        }
        return result;
    }
    
}

运行结果:

请您输入一个字符串:
aeqwe]
]ewqea

判断功能

常用方法:

public boolean equals(Object anObject):比较两个字符的内容是否相同 (区分大小写)
public boolean equalsIgnoreCase(String anotherString):比较两个字符串是否相同(不区分大小写)
public boolean startsWith(String prefix):判断字符串是否以指定的内容开头
public boolean endsWith(String suffix):判断字符串是否以指定的内容结尾

boolean isEmpty()  判断字符串是否为空 :若为空,则返回true;否则返回false

String s = "" ;// 空字符串 ,存在String对象 ""
String s = null ; 空值 (空对象) null:引用类型的默认值

获取功能(重点)

常用方法:

int length();///获取字符串长度
public char charAt(int index);//获取指定索引处的字符
public String concat(String str);//将指定的字符串和当前字符串进行拼接,获取一个新的字符串
public int indexOf(int ch);//返回指定字符第一次出现的索引值
public int lastIndexOf(int ch);//返回值指定字符最后一次出现的索引值
public String[] split(String regex);//拆分功能:通过指定的格式将字符串---拆分字符串数组
public String substring(int beginIndex);//从指定位置开始默认截取到末尾,角标从0开始
public String substring(int beginIndex,int endIndex);//从指定位置开始,截取到位置结束(包前不包右),只能取到endIndex-1处
public static String valueOf(boolean/int/long/float/double/char...Object b);//万能方法,将任意类型转换String类型
String数组的遍历
public class StringTest {
    public static void main(String[] args) {
        
        //创建一个字符串
        String str = "helloJavaEE" ;
        //最原始的做法
        System.out.println(str.charAt(0));
        System.out.println(str.charAt(1));
        System.out.println(str.charAt(2));
        System.out.println(str.charAt(3));
        System.out.println(str.charAt(4));
        System.out.println(str.charAt(5));
        System.out.println(str.charAt(6));
        System.out.println(str.charAt(7));
        System.out.println(str.charAt(8));
        System.out.println(str.charAt(9));
        System.out.println(str.charAt(10));
        System.out.println("------------------------------");

        //使用String类的转换功能
        char[] chs = str.toCharArray(); //String---->字符数组toCharArray()--->char[]
        for(int x = 0 ; x < chs.length ; x ++){
            char ch = chs[x] ;
            System.out.println(ch);
        }
        
    }
}

StringBuffer类

字符串缓冲区 ---->类似于String,但是不一样 (可变的字符序列)

StringBuffer的构造方法:

public StringBuffer();//空参构造,创建一个空字符序列的字符串缓冲去  (推荐)
public StringBuffer(int capacity);//构造一个字符串缓冲区对象,指定容量大小
public StringBuffer(String str);//指定字符序列,长度加上初始容量16(总容量)

获取功能:

public int length();//获取字符数(长度)
public int capacity();//获取字符串缓冲区容量

添加功能

StringBuffer  append(任何类型) ;//将内容追加到字符串缓冲区中 (在字符串缓冲区的最后一个字符序列的末尾追加),返回值是字符串缓冲区本身...
public StringBuffer insert(int offset,String str);//插入:在指定位置处插入指定的内容

删除功能

public StringBuffer deleteCharAt(int index);//删除指定索引处的缓冲区的字符序列,返回字符串缓冲区本身
public StringBuffer delete(int start,int end);//删除从指定位置到指定位置结束的字符序列(包含end-1处的字符),返回字符串缓冲区本身

类型的相互的转换(String和StringBuffer的转换)

//String---->StringBuffer
//StringBuffer---->String
public class StringBufferDemo3 {
    public static void main(String[] args) {

        //String---->StringBuffer
        String s = "hello" ;
      
        //方式1:StringBuffer有参构造方法
        StringBuffer sb = new StringBuffer(s) ;
        System.out.println(sb);

        System.out.println("---------------------------");

        //方式2:StringBuffer的无参构造方法 结合append(String str)
        StringBuffer sb2 = new StringBuffer() ;
        sb2.append(s) ;//追加功能
        System.out.println(sb2);

        //StringBuffer---->String
        StringBuffer buffer = new StringBuffer("helloJavaee") ;//创建字符串缓冲区对象
        
        //方式1:String类型的构造方法
        //public String(StringBuffer buffer)
        String  str = new String(buffer) ;
        System.out.println(str);
        
        System.out.println("-------------------------------------------");

        //方式2:StringBuffer的public String toString()方法
        String str2 = buffer.toString();
        System.out.println(str2);

    }
}

字符反转

import java.util.Scanner;

public class Test02 {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入一个字符串:");
        String s = scanner.nextLine();
        //转成StringBuffer类型
        StringBuilder s1 = new StringBuilder(s);
       
        StringBuilder s2 = s1.reverse();//反转
        System.out.println("反转后为:");
        System.out.println(s2);

    }

}

运行结果:

请输入一个字符串:
sadhjghjkasds
反转后为:
sdsakjhgjhdas

截取功能

public String substring(int start):从指定位置开始,默认截取到末尾,返回值是新的字符串
public String substring(int start,int end):从指定位置开始到指定end-1结束进行截取,返回的新的字符串

替换功能

StringBuffer的替换功能
public StringBuffer replace(int start,       //起始索引
                            int end,         //结束索引(end-1)
                            String str)      //替换的内容

面试题

1、StringBuffer和数组的区别?

数组:

①只能存储同一种数据类型容器
②数组可以存储基本类型,也可以存储引用类型

③数组的最大特点:长度固定
静态初始化int[] arr = {元素1,元素2,元素3…} ;/动态初始化 int[] arr = new int[长度];
String[] strArray = {“xx”,“xx”,“xx”} ;

StringBuffer:

①支持可变的字符序列
②里面存储可以存储任意类型的元素

append(int/char/double/float/Obejct/String)
isnert(int offert,int/char/double/float/Obejct/String)

一般情况:开发中 将StringBuffer----->String

2、集合/数组的区别?(等会说)

主体不同:

1、数组:是有序的元素序列。将有限个类型相同的变量的集合命名。
2、集合:具有某种特定性质的具体的或抽象的对象汇总而成的集体。

特点不同:

1、数组:数组中的所有元素都具有相同类型。数组中的元素存储在一个连续性的内存块中,并通过索引来访问。
2、集合:给定一个集合,任给一个元素,该元素或者属于或者不属于该集合,二者必居其一,不允许有模棱两可的情况出现。

规则不同:

1、数组:不给可初始化的数组赋初值,则全部元素均为0值。只能给元素逐个赋值,不能给数组整体赋值。
2、集合:集合中,每个元素的地位都是相同的,元素之间是无序的。集合上可以定义序关系,定义了序关系后,元素之间就可以按照序关系排序。

3、StringBuffer,StringBuilder和String的区别?

String:字符串是一个常量,一旦被赋值,其值不能更改/作为形式参数属于特殊的引用类型,形式参数的改变不会实际参数

StringBuffer:可变的字符序列,线程安全的类,但执行效率低(线程角度)

StringBuilder:可变的字符序列,和StringBuffer具有相互兼容的api,单线程程序中(只考虑执行效率,不考虑安全问题)

Integer类

int类型的包装类类型(引用类型),包含了int类型的原始数据值

基本类型四类八种都会 对应的各自的引用类型

需要基本类型和String类型之间转换:需要中间桥梁(基本类型对应的包装类类型)

整数类型引用类型引用类型(默认值都是null)
byteByte
shortShort
intInteger
longLong
浮点类型
floatFloat
doubleDouble
字符类型
charCharacter
布尔类型
booleanBoolean

需求:

     public static String toBinaryString(int i);//将整数---->二进制 的字符串
     public static String toOctalString(int i);//将整数---->八进制的字符串
     public static String toHexString(int i);//将整数---->十六进制数据


     public static final int MAX_VALUE;//int的最大值
     public static final int MIN_VALUE;//int的最小值

构造方法

Integer(int value):可以将int类型保证为Integer类型
Integer(String s) throws NumberForamtException:  抛出一个数字格式化异常

注意事项:当前字符串如果不是能够解析的整数的,就会出现数字格式化异常,s必须为 数字字符串

public class IntegerDemo2 {
    public static void main(String[] args) {

        //创建Integer类对象
        int i = 100 ;
        Integer integer = new Integer(i) ;
        System.out.println(integer);
        
        //创建一个字符串
        String s  = "50" ;
        Integer integer2 = new Integer(s) ;
        System.out.println(integer2);
    }
}

自动拆装箱

Integer x = 100; // x里面并不是保存100,保存的是100这个对象的内存地址。
Integer y = 100;
System.out.println(x == y); // true
 
Integer x = 128;
Integer y = 128;
System.out.println(x == y); // false

int和String的转换

int---->String

int i = 10;
//方法一
// Integer类的静态功能
String s1= Integer.toString(i);
//方法二
//底层使用的方法public static String toString(int i)
Integer integer1 = new Integer(i);
String s2 = integer1.toString();

String—>int(使用居多)

String s3 = "10";
//方法一
//public static int parseInt(String s)throws NumberFormatException:数字字符串 (使用最多)
int i1 = Integer.parseInt(s3);//通过Integer的方法将s3转为int类型
//方法二
//Integer 的成员方法:int intValue()--->int
Integer integer2 = new Integer(s3);
int i2 = integer2.intValue();

Integer的内部缓存区

Integer在内存中有一个内存缓存区,存放-128~127之间的数字

Integer i1 = new Integer(127);
Integer i2 = new Integer(127);
System.out.println(i1 == i2);//false
System.out.println(i1.equals(i2));//true

Integer i3 = 127;
Integer i4 = new Integer(127);
System.out.println(i3 == i4);//false
System.out.println(i3.equals(i4));//true

Integer i5 = 128;
Integer i6 = new Integer(128);
System.out.println(i5 == i6);//false
System.out.println(i5.equals(i6));//true

Integer i7 = 127;
Integer i8 = 127;
System.out.println(i7 == i8);//true  IntegerCache:缓存区取出数据
System.out.println(i7.equals(i8));//true

Integer i9 = 128;
Integer i10 = 128;
System.out.println(i9 == i10);//false  return new Integer(128)
System.out.println(i9.equals(i10));//true

Character类

Charcater :char类型的包装类类型,

构造方法

public Character(char value)

主要功能

public static boolean isUpperCase(char ch):判断当前字符是否大写字母字符
public static boolean isLowerCAse(char ch):是否为小写字母字符
public static boolean isDigit(char ch):是否为数字字符

//String转换的功能很类似
public static char toLowerCase(char ch):将字符转换成小写
public static char toUpperCase(char ch):将字符转换成大写

eg.键盘录入一个字符串,有大写字母字符,数字字母字符,小写字母字符,不考虑其他字符,分别统计大写字母字符,小写字母字符,数字字符的个数!

public class Test01 {

    public static void main(String[] args) {

        String string = "Hello123World";

        Method1(string);
        Method(string);

    }

	//用哈希码
    public static void Method1(String string) {
        byte arr[] = string.getBytes();

        int a = 0;
        int b = 0;
        int c = 0;

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > 65 && arr[i] < 90) {
                a++;
            } else if (arr[i] > 97 && arr[i] < 122) {
                b++;
            } else {
                c++;
            }
        }

        System.out.println("大写字符:" + a + ",小写字符:" + b + ",数字:" + c);

    }

	//用方法
    public static void Method(String string) {

        char[] arr = string.toCharArray();

        int a = 0;
        int b = 0;
        int c = 0;

        for (int i = 0; i < arr.length; i++) {
            Character character = new Character(arr[i]);
            // Character 的方法
            if (Character.isUpperCase(character)) {//isUpperCase判断是否是大写字母
                a++;
            } else if (Character.isLowerCase(character)) {//isLowerCase判断是否是小写字母
                b++;
            } else {//isDigit判断是否是数字
                c++;
            }
        }

        System.out.println("大写字符:" + a + ",小写字符:" + b + ",数字:" + c);

    }

}

运行结果:

大写字符:2,小写字符:8,数字:3
大写字符:2,小写字符:8,数字:3

Calendar类

提供一些诸如 获取年,月,月中的日期 等等字段值。属于抽象类,不能实例化

如果一个类没有抽象方法,这个类可不可以定义为抽象类?

可以,为了不能实例化,通过子类间接实例化

不能实例化:

public static Calendar getInstance();//     静态功能,返回值是它自己本身

成员方法:

public int get(int field):根据给定日历字段----获取日历字段的值(系统的日历)
public abstract void add(int field,int amount):给指定的日历字段,添加或者减去时间偏移量
                     参数1:日历字段
                     参数2:偏移量

eg.

import java.util.Calendar;
import java.util.Scanner;

public class CalenderTest {
    public static void main(String[] args) {

        //创建日历类对象
        //获取系统的年月日
        Calendar calendar = Calendar.getInstance();

        //获取年
        //public static final int YEAR
        int year = calendar.get(Calendar.YEAR);

        //获取月:
        //public static final int MONTH:0-11之间
        int month = calendar.get(Calendar.MONTH);

        //获取月中的日期
        //public static final int DATE
        //public static final int DAY OF MONTH : 每个月的第一天1
        int date = calendar.get(Calendar.DATE);

        System.out.println("当前日历为:" + year + "年" + (month + 1) + "月" + date + "日");

        System.out.println("------------------------------------------------");
        
        //获取3年前的今天
        //给year设置偏移量
        //public abstract void add(int field,int amount);
        calendar.add(Calendar.YEAR, -3);
        //获取
        year = calendar.get(Calendar.YEAR);
        System.out.println("当前日历为:" + year + "年" + (month + 1) + "月" + date + "日");

        
        //5年后的十天前
        calendar.add(Calendar.YEAR, +5);
        calendar.add(Calendar.DAY_OF_YEAR, -10);

        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        date = calendar.get(Calendar.DATE);
        System.out.println("当前日历为:" + year + "年" + (month + 1) + "月" + date + "日");

        
        //需求:键盘录入一个年份,算出任意年份的2月份有多少天 (不考虑润月)
        Scanner sc =new Scanner(System.in);
        System.out.println("请输入年份");
        int year1 =sc.nextInt();

        //设置日历对象
        Calendar c = Calendar.getInstance();
        c.set(year1,2,1);//三月一号
        //把时间往前推移一天就是二月的最后一天
        c.add(Calendar.DATE,-1);
        System.out.println(c.get(Calendar.DATE));

    }
}

运行结果:

当前日历为:2021年7月30日

当前日历为:2018年7月30日

当前日历为:2023年7月20日

请输入年份

2000

29

Date类

表示特定瞬间,精确到毫秒!
它还允许格式化和解析日期字符串

构造方法:

public Date():当前系统时间格式
public Date(long date):参数为 时间毫秒值---->Date对象  (197011...)

Date<==>String 格式化过程

DateForamt:抽象类,提供具体的日期/格式化的子类:SimpleDateFormat
format(Date对象)—>String

SimpleDateFormat:构造函数
public SimpleDateFormat():使用默认模式
public SimpleDateFormat(String pattern):使用指定的模式进行解析或者格式 (推荐)

参数:

模式代码表示
“yyyy”
“MM”
“dd”
小时“HH”
“mm”
“ss”
毫秒“SSSS”

String:日期文本----->Date

解析过程

public Date parse(String source)throws ParseException;
//如果解析的字符串的格式和 public SimpleDateFormat(String pattern)的参数模式不匹配的话,就会出现解析异常!

封装成功工具类DateUtils: 构造方法私有,功能都是静态
eg.

public class DateTest {

    public static void main(String[] args) throws ParseException {

        Date date = new Date();

        System.out.println(date.toString());

        //负责日期格式化(把时间转成字符串)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");

        String nowTimeStr = sdf.format(date);
        System.out.println(nowTimeStr);

        //把字符串转成时间
        String time = "2020-01-01 10:00:00 888";
        //注意:指定的日期和给的格式必须一致,不然会有异常
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        Date date1 = sdf2.parse(time);
        System.out.println(date1);

        //返回1970.1.1到当前时间的毫秒数
        long beginTime = System.currentTimeMillis();
        print();
        long endTime = System.currentTimeMillis();
        //计算以上方法运行所需的时间
        System.out.println("以上方法耗时"+(endTime-beginTime)+"毫秒");

    }

    //统计一个方法执行所需的时长
    public static void print(){
        for (int i = 0; i < 1000; i++) {
        }
    }

}

运行结果:

Fri Jul 30 21:15:02 CST 2021
2021-07-30 21:15:02 240
Wed Jan 01 10:00:00 CST 2020
以上方法耗时0毫秒

Random类

伪随机数生成器

构造方法

public Random(); //产生一个随机生成器对象,通过成员方法随机数每次没不一样的(推荐)
public Random(long seed) ;//参数为long类型的值(随机数流:种子),每次通过成员方法获取随机数产生的随机数相同的

获取随机数的成员方法
public int nextInt();//获取的值的范围是int类型的取值范围(-2的31次方到2的31次方-1)
public int nextInt(int n);//获取的0-n之间的数据 (不包含n)

产生随机数:

/*Math类的random方法*/
public static double random();

/*Random类:也能够去使用*/
//无参构造方法  + 成员方法
public Random():+ public int nextInt(int n)

eg.

public class RandomTest01 {

    public static void main(String[] args) {
        Random();
    }

    //生成五个不重复的随机数,重复的话重新生成,最终生成的5个随机数放到数组中
    public static void Random() {

        //建立List集合
        ArrayList<Integer> arrayList = new ArrayList<>(15);

        while (arrayList.size() < 15) {
            //创建随机数对象,且获取随机数
            int num = (new Random()).nextInt(31);

            //判断此随机数是否为偶数,且大于0
            if (num % 2 == 0 && num != 0) {
                //判断集合中有没有这个数字
                if (!arrayList.contains(num)) {
                    //将数字赋值到列表中
                    arrayList.add(num);
                }
            }

        }
        //遍历
        System.out.println(arrayList);

    }
}

运行结果:

[14, 10, 24, 2, 16, 6, 18, 22, 26, 8, 30, 4, 28, 20, 12]

Math类

针对数学运算的工具类,提供了很多方法

public static int abs(int  a):绝对值方法
public static double ceil(double a):向上取整
public static double floor(double a):向下取整
public static int max(int a,int b):获取最大值
public static int min(int a,int b):获取最小值
public static double pow(double a,double b):a的b次幂
public static double random():[0.0,1.0):随机数
public static long round(double a):四舍五入
public static double sqrt(double a):开平方根

Math类中的功能都是静态的,里面构造方法私有了!

一般情况:工具类中构造方法都是会私有化(自定义的工具类),提供对外静态的公共访问方法
(Java设计模式:单例模式)

JDK5的静态导入特性,必须方法静态的(导入到方法的级别)

Math类的功能都是静态的,就可以使用静态导入

import static 包名.类名.方法名;
public class MathDemo {
    public static void main(String[] args) {
        //abs()
        System.out.println(Math.abs(-100));
        // public static double ceil(double a):向上取整
        System.out.println(Math.ceil(13.56));
       // public static double floor(double a):向下取整
        System.out.println(Math.floor(12.45));
        // public static int max(int a,int b):获取最大值
        System.out.println(Math.max(Math.max(10,30),50));//方法嵌套
        //public static double pow(double a,double b):a的b次幂
        System.out.println(Math.pow(2,3));
        //ublic static long round(double a):四舍五入
        System.out.println(Math.round(13.78));

        //  public static double sqrt(double a):开平方根
        System.out.println(Math.sqrt(4));

    }
}

运行结果:

100
14.0
12.0
50
8.0
14
2.0

BigDecimal类

小数要进行精确计算,还可以计算的同时保留小数点后的有效位数

构造方法

public BigDecimal(String value):数字字符串

成员方法:

public BigDecimal add(BigDecimal augend)public BigDecimal subtract(BigDecimal subtrahend)public BigDecimal multiply(BigDecimal multiplicand)public BigDecimal divide(BigDecimal divisor):public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode)
          参数1:商
          参数2:小数点后保留的有效位数
          参数3:舍入模式 :四舍五入

eg.

public class Test{
    public static void main(String[] args) {
        //System.out.println(1.01 / 0.36);

        //创建BigDecimal对象
        BigDecimal bg1 = new BigDecimal("1.01") ;
        BigDecimal bg2 = new BigDecimal("0.36") ;

        BigDecimal bg3 = new BigDecimal("10.0") ;
        BigDecimal bg4 = new BigDecimal("5.05") ;

        System.out.println(bg1.add(bg2));
        System.out.println(bg1.subtract(bg2));
        System.out.println(bg1.multiply(bg2));
        // System.out.println(bg3.divide(bg4));//不保留(整除)
        System.out.println(bg3.divide(bg4,3,BigDecimal.ROUND_HALF_UP));//四十五入

    }
}

运行结果:

1.37
0.65
0.3636
1.980

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值