装箱拆箱
封装类
所有的基本类型,都有对应的类类型,比如int对应的类是Integer,这种类就叫做封装类。
Number类
数字封装类有Byte,Short,Integer,Long,Float,Double,这些类都是抽象类Number的子类。
封装类转基本类型
public class TestNumber {
public static void main(String[] args) {
int i = 5;
//基本类型转换成封装类型
Integer it = new Integer(i);
//封装类型转换成基本类型
int i2 = it.intValue();
}
}
int的最大最小值
int的最大值可以通过其对应的封装类Integer.MAX_VALUE获取
最小值为Integer.MAX_VALUE
自动装箱
不需要调用构造方法,通过=符号自动把 基本类型 转换为 类类型 就叫装箱
public class TestNumber {
public static void main(String[] args) {
int i = 5;
//基本类型转换成封装类型
Integer it = new Integer(i);
//自动转换就叫装箱
Integer it2 = i;
}
}
自动拆箱
不需要调用Integer的intValue方法,通过=就自动转换成int类型,就叫拆箱
public class TestNumber {
public static void main(String[] args) {
int i = 5;
Integer it = new Integer(i);
//封装类型转换成基本类型
int i2 = it.intValue();
//自动转换就叫拆箱
int i3 = it;
}
}
字符串转换
数字转字符串
方法1: 使用String类的静态方法valueOf
方法2: 先把基本类型装箱为对象,然后调用对象的toString
public class TestNumber {
public static void main(String[] args) {
int i = 5;
//方法1
String str = String.valueOf(i);
//方法2
Integer it = i;
String str2 = it.toString();
}
}
字符串转数字
调用Integer的静态方法parseInt
public class TestNumber {
public static void main(String[] args) {
String str = "999";
int i= Integer.parseInt(str);
System.out.println(i);
}
}
数学方法
四舍五入:Math.round()
随机数:Math.random()
开方:Math.sqrt()
次方:Math.pow() 例如:(2的4次方)|| Math.pow(2,4)
π:Math.PI
自然常数:Math.E
格式化输出
%s 表示字符串
%d 表示数字
%n 表示换行
printf和format能够达到一模一样的效果,都是格式化输出。
换行符
换行符就是另起一行 — ‘\n’ 换行(newline)
回车符就是回到一行的开头 — ‘\r’ 回车(return)
为了使得同一个java程序的换行符在所有的操作系统中都有一样的表现,使用%n,就可以做到平台无关的换行
字符
保存一个字符的时候用char
char对应的封装类是character
下列代码为character常见的方法
public class TestChar {
public static void main(String[] args) {
System.out.println(Character.isLetter('a'));//判断是否为字母
System.out.println(Character.isDigit('a')); //判断是否为数字
System.out.println(Character.isWhitespace(' ')); //是否是空白
System.out.println(Character.isUpperCase('a')); //是否是大写
System.out.println(Character.isLowerCase('a')); //是否是小写
System.out.println(Character.toUpperCase('a')); //转换为大写
System.out.println(Character.toLowerCase('A')); //转换为小写
String a = 'a'; //不能够直接把一个字符转换成字符串
String a2 = Character.toString('a'); //转换为字符串
}
}
常见的转义
\t制表符:可以达到对齐的效果
\n换行符:可以换行
注意:
length()是字符串String的一个方法;
size()方法,是List集合的一个方法;
操纵字符串
比较字符串
== 用于判断是否是同一个字符串对象
System.out.println( str1 == str2);
System.out.println(str1.equals(str2));//完全一样返回true
System.out.println(str1.equals(str3));//大小写不一样,返回false
System.out.println(str1.equalsIgnoreCase(str3));//忽略大小写的比较,返回true
注意:使用equals进行字符串内容的比较,必须大小写一致
equalsIgnoreCase,忽略大小写判断内容是否一致。
startsWith //以…开始
endsWith //以…结束
StringBuffer
StringBuffer是可变长的字符串
length: “the”的长度 3
capacity: 分配的总空间 19
public class TestString {
public static void main(String[] args) {
String str1 = "the";
StringBuffer sb = new StringBuffer(str1);
System.out.println(sb.length()); //内容长度
System.out.println(sb.capacity());//总空间
}
}
append追加
delete 删除
insert 插入
reverse 反转