Java基础学习笔记:自动装箱和拆箱、字符串转换以及格式化数据

#.封装类
  • 所有的基本类型,都有对应的类类型 
  • 比如int对应的类是Integer 
  • 这种类就叫做封装类
public class TestNumber {
public static void main(String[] args) {
  int i = 5;
//把一个基本类型的变量,转换为Integer对象
Integer it = new Integer(i);
//把一个Integer对象,转换为一个基本类型的int
int i2 = it.intValue();
}}
#.Number类
  • 数字封装类有 
Byte,Short,Integer,Long,Float,Double 
  • 这些类都是抽象类Number的子类  
#.自动装箱
不需要调用构造方法,通过=符号自动把 基本类型 转换为 类类型 就叫装箱
public class NumberTest {
public static void main(String[] args) {
int i = 5;
//自动转换就叫装箱
Integer it = i;
}}
#.自动拆箱
不需要调用Integer的intValue方法,通过=就自动转换成int类型,就叫拆箱
public class NumberTest {
public static void main(String[] args) {
Integer it = new Integer(5);
//自动转换就叫拆箱
int i = it;
}}
#.数字转换为字符串,字符串转换为数字
数字转字符串
  • 方法1: 使用String类的静态方法valueOf 
  • 方法2: 先把基本类型装箱为对象,然后调用对象的toString
public class NumberTest {
public static void main(String[] args) {
int i = 5;
//方法1
String str = String.valueOf(i);
//方法2
Integer it = i;
String str2 = it.toString();
}}
字符串转数字
  • 调用包装类的静态方法parseXX
public class NumberTest {
public static void main(String[] args) {
String str = "999";
int i= Integer.parseInt(str);
long l = Long.parseLong(str);
short s = Short.parseShort(str);
byte b = Byte.parseByte(str);
}}
如果字符串是 3.1a4,转换为浮点数会得到什么?
如果字符串内容不是合法的数字表达,那么转换就会报错(抛出异常)
posted @ 2022-08-01 14:22  海、蓝天与梦想  阅读(26)  评论(0)    收藏  举报