Java常用API

目录

Math类

System类

Runtime类

Object类

Objects类

BigInteger类  

BigDecimal类

Date类

SimpleDateFormat类

Calendar类

JDK8新增时间类

ZoneId 时区类

Instant 时间戳类

ZoneDateTime 带时区的时间类

DateTimeFormatter 用于时间的格式化和解析

LocalDate、LocalTime、LocalDateTime

LocalDate 年、月、日

LocalTime 时、分、秒

LocalDateTime 年、月、日、时、分、秒

计算时间间隔类

Duration(秒,纳秒)

Period(年、月、日)

ChronoUnit(适用所有单位)

包装类

Integer类

基本类型转换为String

String转换成基本类型

Integer底层原理

习题

练习一

练习二

练习三

练习四

练习五


 

Math类

public static int abs(int a)					// 返回参数的绝对值
public static double ceil(double a)				// 返回大于或等于参数的最小整数
public static double floor(double a)			// 返回小于或等于参数的最大整数
public static int round(float a)				// 按照四舍五入返回最接近参数的int类型的值
public static int max(int a,int b)				// 获取两个int值中的较大值
public static int min(int a,int b)				// 获取两个int值中的较小值
public static double pow (double a,double b)	// 计算a的b次幂的值
public static double sqrt(double a)             // 开平方根
public static double cbrt(double a)             // 开立方根
public static double random()					// 返回一个[0.0,1.0)的随机值

System类

public static long currentTimeMillis()			// 获取当前时间所对应的毫秒值
public static void exit(int status)				// 终止当前正在运行的Java虚拟机,0表示正常退出,非零表示异常退出


// src: 	 源数组
// srcPos:  源数值的开始位置
// dest:    目标数组
// destPos: 目标数组开始位置
// length:   要复制的元素个数
public static native void arraycopy(Object src,  int  srcPos, Object dest, int destPos, int length); // 进行数值元素copy

Runtime类

public static Runtime getRuntime()		//当前系统的运行环境对象
public void exit(int status)			//停止虚拟机
public int availableProcessors()		//获得CPU的线程数
public long maxMemory()				    //JVM能从系统中获取总内存大小(单位byte)
public long totalMemory()				//JVM已经从系统中获取总内存大小(单位byte)
public long freeMemory()				//JVM剩余内存大小(单位byte)
public Process exec(String command) 	//运行cmd命令

Object类

public String toString()				//返回该对象的字符串表示形式(可以看做是对象的内存地址值)
public boolean equals(Object obj)		//比较两个对象地址值是否相等;true表示相同,false表示不相同
protected Object clone()    			//对象克隆

Objects类

public static String toString(Object o) 					// 获取对象的字符串表现形式
public static boolean equals(Object a, Object b)			// 比较两个对象是否相等
public static boolean isNull(Object obj)					// 判断对象是否为null
public static boolean nonNull(Object obj)					// 判断对象是否不为null

BigInteger类  

public BigInteger(int num, Random rnd) 		//获取随机大整数,范围:[0 ~ 2的num次方-1]
public BigInteger(String val) 				//获取指定的大整数
public BigInteger(String val, int radix) 	//获取指定进制的大整数
    
下面这个不是构造,而是一个静态方法获取BigInteger对象
public static BigInteger valueOf(long val) 	//静态方法获取BigInteger的对象,内部有优化

构造方法小结
如果BigInteger表示的数字没有超出long的范围,可以用静态方法获取。
如果BigInteger表示的超出long的范围,可以用构造方法获取。
对象一旦创建,BigInteger内部记录的值不能发生改变。
只要进行计算都会产生一个新的BigInteger对象 

public BigInteger add(BigInteger val)					//加法
public BigInteger subtract(BigInteger val)				//减法
public BigInteger multiply(BigInteger val)				//乘法
public BigInteger divide(BigInteger val)				//除法
public BigInteger[] divideAndRemainder(BigInteger val)	//除法,获取商和余数
public boolean equals(Object x) 					    //比较是否相同
public BigInteger pow(int exponent) 					//次幂、次方
public BigInteger max/min(BigInteger val) 				//返回较大值/较小值
public int intValue(BigInteger val) 					//转为int类型整数,超出范围数据有误

BigDecimal类

public BigDecimal add(BigDecimal value)				// 加法运算
public BigDecimal subtract(BigDecimal value)		// 减法运算
public BigDecimal multiply(BigDecimal value)		// 乘法运算
public BigDecimal divide(BigDecimal value)			// 触发运算
//divisor:			除数对应的BigDecimal对象;
//scale:				精确的位数;
//roundingMode:		取舍模式;
/* 取舍模式被封装到了RoundingMode这个枚举类中(关于枚举我们后期再做重点讲解),在这个枚举类中定义了很多种取舍方式。最常见的取舍方式有如下几个:
UP(直接进1) , FLOOR(直接删除) , HALF_UP(4舍五入),我们可以通过如下格式直接访问这些取舍模式:枚举类名.变量名 */
BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)

Date类

System.out.println(new Date());      //创建日期对象,自动赋值当前时间
System.out.println(new Date(0L));    //创建日期对象,自定义赋值时间,类型为Long,单位为ms毫秒
public long getTime()                //获取时间对象中的毫秒值
public void setTime(long time)       //修改时间对象中的毫秒值

代码示例

//需求1:打印时间原点开始一年后的时间
public static void main(String[] args) {

    Date d1 = new Date();
    long time = d1.getTime();
    time = time + 1000L * 60 * 60 * 24 * 365;
    d1.setTime(time);
    System.out.println(d1);  //Tue Aug 19 15:47:10 CST 2025
    
}

//需求2:定义任意两个Date对象,比较一下哪个时间在前,哪个时间在后
public static void main(String[] args) {

    Random r = new Random();

    Date d1 = new Date(Math.abs(r.nextInt()));
    Date d2 = new Date(Math.abs(r.nextInt()));
    long time1 = d1.getTime();
    long time2 = d2.getTime();
    if (time1 > time2)
        System.out.println("d1的时间在d2之后");
    else if (time1 < time2)
        System.out.println("d1的时间在d2之前");
    else
        System.out.println("d1与d2的时间一样");

}

SimpleDateFormat类

        由于DateFormat为抽象类,不能直接使用,所以需要常用的子类java.text.SimpleDateFormat。这个类需要一个模式(格式)来指定格式化或解析的标准。

常用的格式规则如下

//构造方法
public simpleDateFormat()                   // 默认格式
public simpleDateFormat(String pattern)     // 指定格式

//常用方法
public void applyPattern(String pattern)    // 设置/更改当前对象的日期格式
public String format(Date date)             // Date对象 ——→ 字符串
public Date parse(String source)            // 字符串 ——→ Date对象

代码示例

public static void main(String[] args) {

    //1.利用空参构造创建simpleDateFormat对象,默认格式
    SimpleDateFormat sdf1 = new SimpleDateFormat();
    Date d1 = new Date(0L);
    String str1 = sdf1.format(d1);
    System.out.println(str1); //70-1-1 上午8:00

    //2.利用带参构造创建simpleDateFormat对象,指定格式
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
    String str2 = sdf2.format(d1);
    System.out.println(str2); //1970年01月01日 08:00:00

}
// 需求:"2000-11-11"转换为”2000年11月11日“
public static void main(String[] args) throws ParseException {

    
    String str = "2000-11-11";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date date = sdf.parse(str);

    // 更改日期格式
    sdf.applyPattern("yyyy年MM月dd日");
    String res = sdf.format(date);
    System.out.println(res);

}

Calendar类

        java.util.Calendar类表示一个“日历类”,可以进行日期运算。它是一个抽象类,不能创建对象,我们可以使用它的子类:java.util.GregorianCalendar类。

有两种方式可以获取GregorianCalendar对象:
1. 直接创建GregorianCalendar对象;
2. 通过Calendar的静态方法getInstance()方法获取GregorianCalendar对象。

public static Calendar getInstance()           //获取一个子类GregorianCalendar对象

public final Date getTime()                    //获取日期对象
public final setTime(Date date)                //给日历设置日期对象

public long getTimeInMillis()                  //拿到时间毫秒值
public void setTimeInMillis(long millis)       //给日历设置时间毫秒值

public int get(int field)                      //取日历中的某个字段信息
public void set(int field,int value)           //修改日历的某个字段信息
public void add(int field,int amount)          //为某个字段增加/减少指定的值

field参数表示获取哪个字段的值, 可以使用Calender中定义的常量来表示。
Calendar.YEAR: 年
Calendar.MONTH:月
Calendar.DAY_OF_MONTH:月中的日期
Calendar.DAY_OF_WEEK:星期
Calendar.HOUR:小时
Calendar.MINUTE:分钟
Calendar.SECOND:秒

注意
Calendar中,月份字段范围为0-11,若取出月份值是0,则对应1月份,若取出月份值是1,则对应2月份,以此类推。
Calendar中,以周日作为一周中的第一天,若取出星期值是1,则对应星期日,若取出星期值是2,则对应星期一,以此类推。


JDK8新增时间类

ZoneId 时区类

static Set<string> getAvailableZoneIds()            //获取Java中支持的所有时区
static ZoneId systemDefault()                       //获取系统默认时区
static Zoneld of(string zoneld)                     //获取一个指定时区

代码示例

//1.获取所有的时区名称
Set<String> zoneIds = ZoneId.getAvailableZoneIds();
System.out.println(zoneIds.size());//600
System.out.println(zoneIds);// Asia/Shanghai

//2.获取当前系统的默认时区
ZoneId zoneId = ZoneId.systemDefault();
System.out.println(zoneId);//Asia/Shanghai

//3.获取指定的时区
ZoneId zoneId1 = ZoneId.of("Asia/Pontianak");
System.out.println(zoneId1);//Asia/Pontianak

Instant 时间戳类

static Instant now()                         //获取当前时间的Instant对象(标准时间)
static Instant ofXxxx(long epochMilli)       //根据(秒/毫秒/纳秒)获取Instant对象
ZonedDateTime atZone(ZoneIdzone)             //指定时区
boolean isxxx(Instant otherInstant)          //判断系列的方法
Instant minusXxx(long millisToSubtract)      //减少时间系列的方法
Instant plusXxx(long millisToSubtract)       //增加时间系列的方法

代码示例

//1.获取当前时间的Instant对象(标准时间)
Instant now = Instant.now();
System.out.println(now);

//2.根据(秒/毫秒/纳秒)获取Instant对象
Instant instant1 = Instant.ofEpochMilli(0L);
System.out.println(instant1);//1970-01-01T00:00:00z

Instant instant2 = Instant.ofEpochSecond(1L);
System.out.println(instant2);//1970-01-01T00:00:01Z

Instant instant3 = Instant.ofEpochSecond(1L, 1000000000L);
System.out.println(instant3);//1970-01-01T00:00:027

//3. 指定时区
ZonedDateTime time = Instant.now().atZone(ZoneId.of("Asia/Shanghai"));
System.out.println(time);


//4.isXxx 判断
Instant instant4=Instant.ofEpochMilli(0L);
Instant instant5 =Instant.ofEpochMilli(1000L);

//5.用于时间的判断
//isBefore:判断调用者代表的时间是否在参数表示时间的前面
boolean result1=instant4.isBefore(instant5);
System.out.println(result1);//true

//isAfter:判断调用者代表的时间是否在参数表示时间的后面
boolean result2 = instant4.isAfter(instant5);
System.out.println(result2);//false

//6.Instant minusXxx(long millisToSubtract) 减少时间系列的方法
Instant instant6 =Instant.ofEpochMilli(3000L);
System.out.println(instant6);//1970-01-01T00:00:03Z

Instant instant7 =instant6.minusSeconds(1);
System.out.println(instant7);//1970-01-01T00:00:02Z

ZoneDateTime 带时区的时间类

static ZonedDateTime now()                    //获取当前时间的ZonedDateTime对象
static ZonedDateTime ofXxxx(。。。)           //获取指定时间的ZonedDateTime对象
ZonedDateTime withXxx(时间)                   //修改时间系列的方法
ZonedDateTime minusXxx(时间)                  //减少时间系列的方法
ZonedDateTime plusXxx(时间)                   //增加时间系列的方法

代码示例 

//1.获取当前时间对象(带时区)
ZonedDateTime now = ZonedDateTime.now();
System.out.println(now);

//2.获取指定的时间对象(带时区)1/年月日时分秒纳秒方式指定
ZonedDateTime time1 = ZonedDateTime.of(2023, 10, 1,
                                       11, 12, 12, 0, ZoneId.of("Asia/Shanghai"));
System.out.println(time1);

//通过Instant + 时区的方式指定获取时间对象
Instant instant = Instant.ofEpochMilli(0L);
ZoneId zoneId = ZoneId.of("Asia/Shanghai");
ZonedDateTime time2 = ZonedDateTime.ofInstant(instant, zoneId);
System.out.println(time2);


//3.withXxx 修改时间系列的方法
ZonedDateTime time3 = time2.withYear(2000);
System.out.println(time3);

//4. 减少时间
ZonedDateTime time4 = time3.minusYears(1);
System.out.println(time4);

//5.增加时间
ZonedDateTime time5 = time4.plusYears(1);
System.out.println(time5);

DateTimeFormatter 用于时间的格式化和解析

static DateTimeFormatter ofPattern(格式)             //获取格式对象
String format(时间对象)                              //按照指定方式格式化

代码示例 

//获取时间对象
ZonedDateTime time = Instant.now().atZone(ZoneId.of("Asia/Shanghai"));

// 解析/格式化器
DateTimeFormatter dtf1=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm;ss EE a");

// 格式化
System.out.println(dtf1.format(time));

LocalDate、LocalTime、LocalDateTime

 


LocalDate 年、月、日

代码示例

//1.获取当前时间的日历对象(包含 年月日)
LocalDate nowDate = LocalDate.now();
//System.out.println("今天的日期:" + nowDate);
//2.获取指定的时间的日历对象
LocalDate ldDate = LocalDate.of(2023, 1, 1);
System.out.println("指定日期:" + ldDate);

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

//3.get系列方法获取日历中的每一个属性值//获取年
int year = ldDate.getYear();
System.out.println("year: " + year);
//获取月//方式一:
Month m = ldDate.getMonth();
System.out.println(m);
System.out.println(m.getValue());

//方式二:
int month = ldDate.getMonthValue();
System.out.println("month: " + month);


//获取日
int day = ldDate.getDayOfMonth();
System.out.println("day:" + day);

//获取一年的第几天
int dayofYear = ldDate.getDayOfYear();
System.out.println("dayOfYear:" + dayofYear);

//获取星期
DayOfWeek dayOfWeek = ldDate.getDayOfWeek();
System.out.println(dayOfWeek);
System.out.println(dayOfWeek.getValue());

//is开头的方法表示判断
System.out.println(ldDate.isBefore(ldDate));
System.out.println(ldDate.isAfter(ldDate));

//with开头的方法表示修改,只能修改年月日
LocalDate withLocalDate = ldDate.withYear(2000);
System.out.println(withLocalDate);

//minus开头的方法表示减少,只能减少年月日
LocalDate minusLocalDate = ldDate.minusYears(1);
System.out.println(minusLocalDate);


//plus开头的方法表示增加,只能增加年月日
LocalDate plusLocalDate = ldDate.plusDays(1);
System.out.println(plusLocalDate);

//-------------
// 判断今天是否是你的生日
LocalDate birDate = LocalDate.of(2000, 1, 1);
LocalDate nowDate1 = LocalDate.now();

MonthDay birMd = MonthDay.of(birDate.getMonthValue(), birDate.getDayOfMonth());
MonthDay nowMd = MonthDay.from(nowDate1);

System.out.println("今天是你的生日吗? " + birMd.equals(nowMd));//今天是你的生日吗?

LocalTime 时、分、秒

代码示例

// 获取本地时间的日历对象。(包含 时分秒)
LocalTime nowTime = LocalTime.now();
System.out.println("今天的时间:" + nowTime);

int hour = nowTime.getHour();//时
System.out.println("hour: " + hour);

int minute = nowTime.getMinute();//分
System.out.println("minute: " + minute);

int second = nowTime.getSecond();//秒
System.out.println("second:" + second);

int nano = nowTime.getNano();//纳秒
System.out.println("nano:" + nano);
System.out.println("------------------------------------");
System.out.println(LocalTime.of(8, 20));//时分
System.out.println(LocalTime.of(8, 20, 30));//时分秒
System.out.println(LocalTime.of(8, 20, 30, 150));//时分秒纳秒
LocalTime mTime = LocalTime.of(8, 20, 30, 150);

//is系列的方法
System.out.println(nowTime.isBefore(mTime));
System.out.println(nowTime.isAfter(mTime));

//with系列的方法,只能修改时、分、秒
System.out.println(nowTime.withHour(10));

//plus系列的方法,只能修改时、分、秒
System.out.println(nowTime.plusHours(10));

LocalDateTime 年、月、日、时、分、秒

// 当前时间的的日历对象(包含年月日时分秒)
LocalDateTime nowDateTime = LocalDateTime.now();

System.out.println("今天是:" + nowDateTime);//今天是:
System.out.println(nowDateTime.getYear());//年
System.out.println(nowDateTime.getMonthValue());//月
System.out.println(nowDateTime.getDayOfMonth());//日
System.out.println(nowDateTime.getHour());//时
System.out.println(nowDateTime.getMinute());//分
System.out.println(nowDateTime.getSecond());//秒
System.out.println(nowDateTime.getNano());//纳秒
// 日:当年的第几天
System.out.println("dayofYear:" + nowDateTime.getDayOfYear());
//星期
System.out.println(nowDateTime.getDayOfWeek());
System.out.println(nowDateTime.getDayOfWeek().getValue());
//月份
System.out.println(nowDateTime.getMonth());
System.out.println(nowDateTime.getMonth().getValue());

LocalDate ld = nowDateTime.toLocalDate();
System.out.println(ld);

LocalTime lt = nowDateTime.toLocalTime();
System.out.println(lt.getHour());
System.out.println(lt.getMinute());
System.out.println(lt.getSecond());

计算时间间隔类

Duration:用于计算两个“时间”的间隔(秒,纳秒)
Period:用于计算两个“日期”的间隔(年、月、日)
ChronoUnit:用于计算两个“日期”的间隔(适用所有单位)

Duration(秒,纳秒)

代码示例

// 本地日期时间对象。
LocalDateTime today = LocalDateTime.now();
System.out.println(today);

// 出生的日期时间对象
LocalDateTime birthDate = LocalDateTime.of(2000, 1, 1, 0, 0, 0);
System.out.println(birthDate);

Duration duration = Duration.between(birthDate, today);//第二个参数减第一个参数
System.out.println("相差的时间间隔对象:" + duration);

System.out.println("============================================");
System.out.println(duration.toDays());//两个时间差的天数
System.out.println(duration.toHours());//两个时间差的小时数
System.out.println(duration.toMinutes());//两个时间差的分钟数
System.out.println(duration.toMillis());//两个时间差的毫秒数
System.out.println(duration.toNanos());//两个时间差的纳秒数

Period(年、月、日)

代码示例

// 当前本地 年月日
LocalDate today = LocalDate.now();
System.out.println(today);

// 生日的 年月日
LocalDate birthDate = LocalDate.of(2000, 1, 1);
System.out.println(birthDate);

Period period = Period.between(birthDate, today);//第二个参数减第一个参数

System.out.println("相差的时间间隔对象:" + period);
System.out.println(period.getYears());
System.out.println(period.getMonths());
System.out.println(period.getDays());

System.out.println(period.toTotalMonths());

ChronoUnit(适用所有单位)

// 当前时间
LocalDateTime today = LocalDateTime.now();
System.out.println(today);
// 生日时间
LocalDateTime birthDate = LocalDateTime.of(2000, 1, 1,0, 0, 0);
System.out.println(birthDate);

System.out.println("相差的年数:" + ChronoUnit.YEARS.between(birthDate, today));
System.out.println("相差的月数:" + ChronoUnit.MONTHS.between(birthDate, today));
System.out.println("相差的周数:" + ChronoUnit.WEEKS.between(birthDate, today));
System.out.println("相差的天数:" + ChronoUnit.DAYS.between(birthDate, today));
System.out.println("相差的时数:" + ChronoUnit.HOURS.between(birthDate, today));
System.out.println("相差的分数:" + ChronoUnit.MINUTES.between(birthDate, today));
System.out.println("相差的秒数:" + ChronoUnit.SECONDS.between(birthDate, today));
System.out.println("相差的毫秒数:" + ChronoUnit.MILLIS.between(birthDate, today));
System.out.println("相差的微秒数:" + ChronoUnit.MICROS.between(birthDate, today));
System.out.println("相差的纳秒数:" + ChronoUnit.NANOS.between(birthDate, today));
System.out.println("相差的半天数:" + ChronoUnit.HALF_DAYS.between(birthDate, today));
System.out.println("相差的十年数:" + ChronoUnit.DECADES.between(birthDate, today));
System.out.println("相差的世纪(百年)数:" + ChronoUnit.CENTURIES.between(birthDate, today));
System.out.println("相差的千年数:" + ChronoUnit.MILLENNIA.between(birthDate, today));
System.out.println("相差的纪元数:" + ChronoUnit.ERAS.between(birthDate, today));

包装类

Integer类

// public Integer(int value)                     //根据 int 值创建 Integer 对象(过时)
// public Integer(String s)                      //根据 string 值创建 Integer 对象(过时)
public static Integer valueOf(int i)             //返回表示指定的int 值的 Integer 实例
public static Integer valueOf(String s)          //返回保存指定Strinq值的 Inteqer 对象
static string tobinarystring(int i)              //得到二进制
static string tooctalstring(int i)               //得到八进制
static string toHexstring(int i)                 //得到十六进制
static int parselnt(string s)                    //将字符串类型的整数转成int类型的整数

代码示例

//public Integer(int value):根据 int 值创建 Integer 对象(过时)
Integer i1 = new Integer(100);
System.out.println(i1);

//public Integer(String s):根据 String 值创建 Integer 对象(过时)
Integer i2 = new Integer("100");
//Integer i2 = new Integer("abc"); //NumberFormatException
System.out.println(i2);
System.out.println("--------");

//public static Integer valueOf(int i):返回表示指定的 int 值的 Integer 实例
Integer i3 = Integer.valueOf(100);
System.out.println(i3);

//public static Integer valueOf(String s):返回保存指定String值的Integer对象 
Integer i4 = Integer.valueOf("100");
System.out.println(i4);


/*
            public static string tobinarystring(int i) 得到二进制
            public static string tooctalstring(int i) 得到八进制
            public static string toHexstring(int i) 得到十六进制
            public static int parseInt(string s) 将字符串类型的整数转成int类型的整数
 */

//1.把整数转成二进制,十六进制
String str1 = Integer.toBinaryString(100);
System.out.println(str1);//1100100

//2.把整数转成八进制
String str2 = Integer.toOctalString(100);
System.out.println(str2);//144

//3.把整数转成十六进制
String str3 = Integer.toHexString(100);
System.out.println(str3);//64

//4.将字符串类型的整数转成int类型的整数
//强类型语言:每种数据在java中都有各自的数据类型
//在计算的时候,如果不是同一种数据类型,是无法直接计算的。
int i = Integer.parseInt("123");
System.out.println(i);
System.out.println(i + 1);//124
//细节1:
//在类型转换的时候,括号中的参数只能是数字不能是其他,否则代码会报错
//细节2:
//8种包装类当中,除了Character都有对应的parseXxx的方法,进行类型转换
String str = "true";
boolean b = Boolean.parseBoolean(str);
System.out.println(b);

基本类型转换为String

转换方式
方式一:直接在数字后加一个空字符串
方式二:通过String类静态方法valueOf()

示例代码

public class IntegerDemo {
    public static void main(String[] args) {
        //int --- String
        int number = 100;
        //方式1
        String s1 = number + "";
        System.out.println(s1);

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

        //方式2
        //public static String valueOf(int i)
        String s2 = String.valueOf(number);
        System.out.println(s2);
    }
}

String转换成基本类型

        除了Character类之外,其他所有包装类都具有parseXxx静态方法可以将字符串参数转换为对应的基本类型。

public static byte parseByte(String s)          //将字符串参数转换为对应的byte基本类型。
public static short parseShort(String s)        //将字符串参数转换为对应的short基本类型。
public static int parseInt(String s)            //将字符串参数转换为对应的int基本类型。
public static long parseLong(String s)          //将字符串参数转换为对应的long基本类型。
public static float parseFloat(String s)        //将字符串参数转换为对应的float基本类型。
public static double parseDouble(String s)      //将字符串参数转换为对应的double基本类型。
public static boolean parseBoolean(String s)    //将字符串参数转换为对应的boolean基本类型。

转换方式
方式一:先将字符串数字转成Integer类型,再调用valueOf()方法
方式二:通过Integer类的静态方法parseInt()进行转换

代码示例(仅以Integer类的静态方法parseXxx为例)

public class IntegerDemo {
    public static void main(String[] args) {
        //String --- int
        String s = "100";
        //方式1:String --- Integer --- int
        Integer i = Integer.valueOf(s);
        int x = i.intValue();
        System.out.println(x);
        
        //方式2
        //public static int parseInt(String s)
        int y = Integer.parseInt(s);
        System.out.println(y);
    }
}

Integer底层原理

建议:不要使用new的方式获取Integer对象,而是采取直接赋值或者静态方法valueOf的方式获取。因为在实际开发中,-128~127之间的数据,用的比较多。如果每次都使用new的方式获取对象,则会大量浪费内存。所以,Integer底层会提前将这个范围内的每一个数据都创建好对应的对象,并存储在数组中。如果需要用到-128~127之间的数据,Integer不会创建新的对象,而是返回已经创建好的对象。

//1.利用构造方法获取Integer的对象(JDK5以前的方式)
/*Integer i1 = new Integer(1);
        Integer i2 = new Integer("1");
        System.out.println(i1);
        System.out.println(i2);*/

//2.利用静态方法获取Integer的对象(JDK5以前的方式)
Integer i3 = Integer.valueOf(123);
Integer i4 = Integer.valueOf("123");
Integer i5 = Integer.valueOf("123", 8);

System.out.println(i3);
System.out.println(i4);
System.out.println(i5);

//3.这两种方式获取对象的区别(掌握)
//底层原理:
//因为在实际开发中,-128~127之间的数据,用的比较多。
//如果每次使用都是new对象,那么太浪费内存了
//所以,提前把这个范围之内的每一个数据都创建好对象
//如果要用到了不会创建新的,而是返回已经创建好的对象。
Integer i6 = Integer.valueOf(127);
Integer i7 = Integer.valueOf(127);
System.out.println(i6 == i7);//true

Integer i8 = Integer.valueOf(128);
Integer i9 = Integer.valueOf(128);
System.out.println(i8 == i9);//false

//因为看到了new关键字,在Java中,每一次new都是创建了一个新的对象
//所以下面的两个对象都是new出来,地址值不一样。
/*Integer i10 = new Integer(127);
        Integer i11 = new Integer(127);
        System.out.println(i10 == i11);

        Integer i12 = new Integer(128);
        Integer i13 = new Integer(128);
        System.out.println(i12 == i13);*/

习题

练习一

需求
        键盘录入一些1~10日之间的整数,并添加到集合中。直到集合中所有数据和超过200为止。

代码示例

public class Test1 {
    public static void main(String[] args) {
        /*
            键盘录入一些1~10日之间的整数,并添加到集合中。直到集合中所有数据和超过200为止。
        */
        //1.创建一个集合用来添加整数
        ArrayList<Integer> list = new ArrayList<>();
        //2.键盘录入数据添加到集合中
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("请输入一个整数");
            String numStr = sc.nextLine();
            int num = Integer.parseInt(numStr);//先把异常数据先进行过滤
            if (num < 1 || num > 100){
                System.out.println("当前数字不在1~100的范围当中,请重新输入");
                continue;
            }
            //添加到集合中//细节:
            //num:基本数据类型
            //集合里面的数据是Integer
            //在添加数据的时候触发了自动装箱
            list.add(num);
            //统计集合中所有的数据和
            int sum = getSum(list);
            //对sum进行判断
            if(sum > 200){
            System.out.println("集合中所有的数据和已经满足要求");
            break;
        }
    }

}


    private static int getSum(ArrayList<Integer> list) {
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            //i :索引
            //list.get(i);
            int num = list.get(i);
            sum = sum + num;//+=
        }
        return sum;
    }
}

练习二

需求
        
自己实现parseInt方法的效果,将字符串形式的数据转成整数。要求:字符串中只能是数字不能有其他字符最少一位,最多10位日不能开头。

代码示例

public class Test2 {
    public static void main(String[] args) {
        /*
            自己实现parseInt方法的效果,将字符串形式的数据转成整数。要求:
            字符串中只能是数字不能有其他字符最少一位,最多10位日不能开头
        */

        //1.定义一个字符串
        String str = "123";
        //2.校验字符串
        //习惯:会先把异常数据进行过滤,剩下来就是正常的数据。
        if (!str.matches("[1-9]\\d{0,9}")) {
            //错误的数据
            System.out.println("数据格式有误");
        } else {
            //正确的数据
            System.out.println("数据格式正确");
            //3.定义一个变量表示最终的结果
            int number = 0;
            //4.遍历字符串得到里面的每一个字符
            for (int i = 0; i < str.length(); i++) {
                int c = str.charAt(i) - '0';//把每一位数字放到number当中
                number = number * 10 + c;
            }
            System.out.println(number);
            System.out.println(number + 1);
        }
    }
}

练习三

需求
        
定义一个方法自己实现toBinaryString方法的效果,将一个十进制整数转成字符串表示的二进制。

代码示例

package com.itheima.a04test;

public class Test3 {
    public static void main(String[] args) {
        /*

            定义一个方法自己实现toBinaryString方法的效果,将一个十进制整数转成字符串表示的二进制

         */
    }


    public static String tobinarystring(int number) {//6
        //核心逻辑:
        //不断的去除以2,得到余数,一直到商为日就结束。
        //还需要把余数倒着拼接起来

        //定义一个StringBuilder用来拼接余数
        StringBuilder sb = new StringBuilder();
        //利用循环不断的除以2获取余数
        while (true) {
            if (number == 0) {
                break;
            }
            //获取余数 %
            int remaindar = number % 2;//倒着拼接
            sb.insert(0, remaindar);
            //除以2 /
            number = number / 2;
        }
        return sb.toString();
    }
}

练习四

需求
        
请使用代码实现计算你活了多少天,用JDK7和JDK8两种方式完成。

代码示例

public class Test4 {
    public static void main(String[] args) throws ParseException {
        //请使用代码实现计算你活了多少天,用JDK7和JDK8两种方式完成
        //JDK7
        //规则:只要对时间进行计算或者判断,都需要先获取当前时间的毫秒值
        //1.计算出生年月日的毫秒值
        String birthday = "2000年1月1日";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        Date date = sdf.parse(birthday);
        long birthdayTime = date.getTime();
        //2.获取当前时间的毫秒值
        long todayTime = System.currentTimeMillis();
        //3.计算间隔多少天
        long time = todayTime - birthdayTime;
        System.out.println(time / 1000 / 60 / 60 / 24);


        //JDK8
        LocalDate ld1 = LocalDate.of(2000, 1, 1);
        LocalDate ld2 = LocalDate.now();
        long days = ChronoUnit.DAYS.between(ld1, ld2);
        System.out.println(days);
    }
}

练习五

需求
        
判断任意的一个年份是闰年还是平年要求:用JDK7和JDK8两种方式判断提示:二月有29天是闰年一年有366天是闰年。

代码示例

public class Test5 {
    public static void main(String[] args) {
        /*
            判断任意的一个年份是闰年还是平年要求:用JDK7和JDK8两种方式判断提示:
            二月有29天是闰年一年有366天是闰年
        */

        //jdk7
        //我们可以把时间设置为2000年3月1日
        Calendar c = Calendar.getInstance();
        c.set(2000, 2, 1);
        //月份的范围:0~11
        //再把日历往前减一天
        c.add(Calendar.DAY_OF_MONTH, -1);
        //看当前的时间是28号还是29号?
        int day = c.get(Calendar.DAY_OF_MONTH);
        System.out.println(day);


        //jdk8
        //月份的范围:1~12
        //设定时间为2000年的3月1日
        LocalDate ld = LocalDate.of(2001, 3, 1);
        //把时间往前减一天
        LocalDate ld2 = ld.minusDays(1);
        //获取这一天是一个月中的几号
        int day2 = ld2.getDayOfMonth();
        System.out.println(day2);

        //true:闰年
        //false:平年
        System.out.println(ld.isLeapYear());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值