1、包裝類(將基本數據類型轉化爲對象,實際就是實現包裝類、基本數據類型、字符串三者轉化。)
注:只有int和char的包裝類名稱不同
//把基本數據類型轉成對象
Integer int1 = Integer.valueOf(10);//也可=new Integer(10)不推薦
// Integer對象轉化成int
int newint = int1.intValue();
//jdk1.5之後自動裝箱、拆箱
Integer a = 1234; // 自動裝箱,編譯器默認調用上面轉換的方法
int a = b; //自動拆箱,編譯器默認調用上面的轉換方法
//註釋: 包裝類在自動裝箱時爲了提高效率,對於-128~127之間的值會進行緩存處理。Integer出來的對象是同一個對象。超過範圍後,則不再是。
// 字符串轉化成Integer對象
Integer int2 = Integer.parseInt("123");//也可=new Integer(“123”)不推薦
// Integer對象轉化成字符串
String str1 = int2.toString();//或者直接+“”
// 一些常見int類型相關的常量
System.out.println("int能表示的最大整數:" + Integer.MAX_VALUE);
//注:其他相似
2、時間處理相關類
2.1Date類,import java.util.Date;多數方法都被替代,一般不常用
//Date(n)中有參數,則1970.1.1+n毫秒
Date date = new Date();
System.out.println(date);//=>Wed May 27 17:44:10 CST 2020
System.out.println(date.getTime());//=>1590572650786//返回當前時間,自 1970 年 1 月 1 日 00:00:00至今
2.2DateFormat類
實現時間對象與字符串的轉化。DateFormat是抽象類,一般用其子類SimpleDateFormat。
//需要傳入格式化字符串:H小時數(0-23);h(1-23);E星期;D今年第幾天
//時間對象轉字符串
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//-:可換
String stringdate = date.format(new Date());
//字符串轉時間類型
Date date2 = date.parse("1999-9-09 12:00:00");
System.out.println(date2);
2.3Calendar
實現關於日期計算的相關功能,如:年、月、日、時、分、秒的展示和計算。Calendar 類是一個抽象類,一般用其子類GregorianCalendar。
//設置日期格式
Calendar calendar2 = new GregorianCalendar();
calendar.set(calendar.YEAR, 2020);
// 日期計算
GregorianCalendar calendar3 = new GregorianCalendar();
calendar3.add(Calendar.DATE,7); //增加7天
System.out.println(calendar3);
// 日曆對象和時間對象轉化
Date d = calendar3.getTime();
GregorianCalendar calendar4 = new GregorianCalendar();
calendar4.setTime(new Date());
//注意:日期爲1-7;週日在前面,週一、週二...
3、Math
//取整相關操作
System.out.println(Math.ceil(3.2));//=>4.0
System.out.println(Math.floor(3.2));//=>3.0
System.out.println(Math.round(3.2));//=>3
System.out.println(Math.round(3.8));//=>4
//絕對值、開方、a的b次冪等操作
System.out.println(Math.abs(-45));//=>45
System.out.println(Math.sqrt(64));//=>8.0
System.out.println(Math.pow(5, 2));//=>25
//隨機數
System.out.println(Math.random());// [0,1)
4、枚舉類
定義一組常量時,可以使用枚舉類型,一般配合case語句使用
enum 枚舉名 {
枚舉體(常量列表)
}
5、String類
在博客中有詳細介紹。
6、File類
同上。