【Java】三大特殊类-String类(字符串的转换、比较、查找、替换、拆分、截取以及StringBuffer类的常用方法)、Object类、包装类(装箱与拆箱、字符串与基本数据类型转换 )

三大特殊类总结:

【Java】三大特殊类-String类(字符串的转换、比较、查找、替换、拆分、截取以及StringBuffer类的常用方法)、Object类、包装类(装箱与拆箱、字符串与基本数据类型转换 )

备注:

1.使用Object接收所有类的对象    范例1:

class Person{}
class Student{}
public class Test {
    public static void main(String[] args) {
        fun(new Person());
        fun(new Student());
    }
    public static void fun(Object obj) {
        System.out.println(obj);
    }
}

2.覆写toString()方法    范例2 :

class Person{
    private String name ;
    private int age ;
    public Person(String name, int age) {
        this.age = age ;
        this.name = name ;
    }
    @Override
    public String toString() {
        return "姓名:"+this.name+",年龄:"+this.age ;
    }
}
class Student{}
public class TestString {
    public static void main(String[] args) {
        String msg = "Hello " + new Person("yuisama", 25) ;
        System.out.println(msg);
    }
}

3.对象比较   范例3:

class Person{
    private String name ;
    private int age ;
    public Person(String name, int age) {
        this.age = age ;
        this.name = name ;
    }
    @Override
    public String toString() {
        return "姓名:"+this.name+",年龄:"+this.age ;
        }
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false ;
        }
        if(this == obj) {
            return true ;
        }
        // 不是Person类对象
        if (!(obj instanceof Person)) {
            return false ;
        }
            Person person = (Person) obj ; // 向下转型,比较属性值
            return this.name.equals(person.name) && this.age==person.age ;
    }
}
class Student{}
public class TestObject {
    public static void main(String[] args) {
        Person per1 = new Person("yuisama", 20) ;
        Person per2 = new Person("yuisama", 20) ;
        System.out.println(per1.equals(per2));
        }
}

4.装箱与拆箱  范例4:

Integer num = new Integer(55) ; // 装箱
int data = num.intValue() ; // 拆箱
System.out.println(data);

5.自动装箱与拆箱处理   范例5:

// 自动装箱
Integer x = 55 ;
// 可以直接利用包装类对象操作
System.out.println(++x * 5 );

6. 范例6:

Integer num1 = new Integer(10) ;
Integer num2 = new Integer(10) ;
System.out.println(num1 == num2);//false
System.out.println(num1 == new Integer(10));//false
System.out.println(num1.equals(new Integer(10)));//true

对于 Integer var = ? 在-128 至 127 范围内的赋值,Integer 对象是在IntegerCache.cache 产生,会复用
已有对象,这个区间内的 Integer 值可以直接使用==进行判断,但是这个区间之外的所有数据,都会在堆上产
生,并不会复用已有对象,推荐使用 equals 方法进行判断。

7.字符串与基本数据类型转换  范例7:

//字符串的组成有非数字,那么转换就会出现错误
(NumberFormatException),
而boolean转换就不受此影响

//将字符串变为int型
String str = "123" ; // String类型
int num = Integer.parseInt(str) ;

//将字符串变为double
String str = "123" ; // String类型
double num = Double.parseDouble(str) ;