基本数据类型 和 包装类 的相互转换
基本数据类型 和 包装类 的相互转换
Java中, 一切皆对象
Linux中, 一切皆文件
要体会, 这种思想, 有时候, 真的是需要体会
1, java提供了8种基本数据类型 对应的 包装类, 使得 基本数据类型的变量 具有 类的特征
2, 掌握 基本数据类型, 包装类, String三者之间的相互转换
基本数据类型 | 包装类 |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char | Character |
1. 基本数据类型 --> 包装类
https://www.bilibili.com/video/BV1Kb411W75N?p=304
https://www.bilibili.com/video/BV1Kb411W75N?p=305
package com.beyondx.java;
import org.junit.Test;
public class WrapperTest {
@Test
public void test1() {
int num1 = 10;
Integer in1 = new Integer(num1);
System.out.println(in1.toString()); // 10
Integer in2 = new Integer("123");
System.out.println(in2.toString()); // 123
}
}
java.lang.Integer部分源码
public final class Integer extends Number implements Comparable<Integer> {
// 内部类
private static class IntegerCache {
}
// 2个构造器, 安排
public Integer(int value) {
}
public Integer(String s) throws NumberFormatException {
}
}
java.lang.Float部分源码
public final class Float extends Number implements Comparable<Float> {
// 3个构造器, 安排
public Float(float value) {
}
public Float(double value) {
}
public Float(String s) {
}
}
java.lang.Boolean部分源码
public final class Boolean implements java.io.Serializable, Comparable<Boolean> {
// 2个构造器, 安排
public Boolean(boolean value) {
}
public Boolean(String s) {
}
}
2. 包装类 --> 基本数据类型
https://www.bilibili.com/video/BV1Kb411W75N?p=306
包装类 转化为 基本数据类型: 调用包装类 的 xxxValue()
package com.beyondx.java;
import org.junit.test;
public class WrapperTest {
@Test
public void test2() {
Integer in1 = new Integer(12);
int i1 = in1.intValue();
System.out.println(i1 + 1);
Float f1 = new Float(12.3);
float f2 = f1.floatValue();
System.out.println(f2 + 1);
}
}
java.lang.Integer部分源码
public final class Integer extends Number implements Comparable<Integer> {
// 内部类
private static class IntegerCache {
}
// 2个构造器
public Integer(int value) {
}
public Integer(String s) throws NumberFormatException {
}
// 几个方法
public byte byteValue() {
}
public int intValue() {
}
public long longValue() {
}
public float floatValue() {
}
public double doubleValue() {
}
}
参考链接
https://blog.csdn.net/weixin_38361153/article/details/88218744