【Java】17.常用API(二)

本文详细介绍了Java中的包装类如Integer类的用法,包括基本类型与String的转换,以及Date类、Calendar类和日期工具的使用,涉及自动拆箱和装箱的概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、包装类

1.1基本类型包装类

- 基本类型包装类的作用

​ 将基本数据类型封装成对象的好处在于可以在对象中定义更多的功能方法操作该数据

​ 常用的操作之一:用于基本数据类型与字符串之间的转换

- 基本类型对应的包装类

基本数据类型

包装类

byte

Byte

short

Short

int

Integer

long

Long

float

Float

double

Double

char

Character

boolean

Boolean

1.2 Integer类(应用)

- Integer类概述

​ 包装一个对象中的原始类型 int 的值

- 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)

返回一个保存指定值的 Integer 对象 String

- 示例代码

public class IntegerDemo {
    public static void main(String[] args) {
        //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):返回一个保存指定值的Integer对象 String
        Integer i4 = Integer.valueOf("100");
        System.out.println(i4);
    }
}

1.3 int和String类型的相互转换

- int转换为String

- 转换方式

- 方式一:直接在数字后加一个空字符串

- 方式二:通过String类静态方法valueOf()

- 示例代码


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值