一.工具类语句
1.equals 比较两个对象的引用值是否相同
Object obj1 = new Object();
Object obj2 = new Object();
System.out.println(obj1.equals(obj2));//比较obj1和obj2的值是否相同 因为是对象 所以储存的是不同的地址 所以结果false
==和equals的区别(面试题)
==可以比较基本数据类型也可以比较引用数据类型比较基本类型比较的是值 比较引用数据类型比较的是地址值
equals不能比较基本数据类型 只能比较引用数据类型 重写之前比较的是地址 重写之后比较的是内容
//==和equals的区别
Object obj1 = new Object();
Object obj2 = new Object();
System.out.println(obj1 == obj2);//比较地址 false
System.out.println(obj1.equals(obj2));//比较地址 false
Person p1 = new Person("张三", 18, 1);
Person p2 = new Person("张三", 18, 1);
System.out.println(p1 == p2);//false
System.out.println(p1.equals(p2));//false 重写object父类中的equals方法后比较的是内容所以结果变为true
2.hashCode 返回十进制整数,唯一标识一个对象
System.out.println(obj1.hashCode());
System.out.println(obj2.hashCode());
//204349222
//231685785
3.toString 返回类名@hashCode hashcode是十六进制
System.out.println(obj1.toString());
System.out.println(obj2.toString());
//java.lang.Object@c2e1f26
//java.lang.Object@dcf3e99
二.包装类:针对基本数据类型的包装类是将基本数据类型的首字母变大写,除了 int char
A.包装类常用属性 直接类名. 调用
1.MIN_VALUE最小值 MAX_VALUE最大值
System.out.println(Byte.MIN_VALUE+","+Byte.MAX_VALUE);
//-128 127
B.包装类常用方法 直接类名. 调用
1.Character.isDigit('');判断字符是否为数字
boolean a = Character.isDigit('c');
System.out.println(a);//false
System.out.println(Character.isDigit('1'));//true
2.Character.isLetter('');判断字符是否为字母
System.out.println(Character.isLetter('c'));//true
3.Character.isLowerCase('');判断字符是否为小写字母
System.out.println(Character.isLowerCase('c'));//true
C.基本数据类型转换为包装类
1.通过构造器转换
int b = 10;
Integer b1 = new Integer(b);
System.out.println(b1+1);//11
2.字符串转换为包装类 注意:字符串不能通过以下两种方法转换为Character
2.1字符串通过构造方法转换为包装类
String s = "500";
String b2 = new String(s);
System.out.println(b2+1);//5001
2.2字符串通过包装类的valueof转换为包装类 valueof只能转换为integar
String s = "500";
Integer b3 = Integer.valueOf(s);
System.out.println(b3);//500
D.包装类转换为其他类型
1.包装类通过xxxvalue()方法转换
Integer i = new Integer(100);
int i2 = i.intValue();
System.out.println(i2);//100
2.包装类型通过toString()转换为字符串
Integer i = new Integer(100);
String s2 = i.toString();
System.out.println(s2);//输出的是字符串类型的100
3.字符串通过parsexxx()方法转换为基本数据类型
Integer i = new Integer(100);
String s2 = i.toString();
int i3 = Integer.parseInt(s2);
System.out.println(i3);//输出的是整数类型的100
E自动拆装箱
装箱是指基本数据类型-->包装类型
拆箱是指包装类型-->基本数据类型
int i4 = 20;
Integer i5 = i4; //基本数据类型转换为包装类类型 自动装箱
i4 = i5; //包装类型转换为基本类型 自动拆箱
例题:从控制台得到字符串作为整数,判断该字符是否能转换为数字
public static void main(String[] args) {
System.out.println("请输入一个字符串内容");
String s = new Scanner(System.in).next();
try {
//字符串转换为数字
Integer s1 = new Integer(s);
if(s1 instanceof Integer) {
System.out.println("可以转换为数字");
}
}catch(Exception e) {
System.out.println("输入不为数字字符串不可转换");
}
}