string 构造方法为对象赋值,equals方法比较两个字符串是否相等

package String;
/*
 * 写了一个简单的equals 方法
 * 总结:用string的构造方法来赋值,构造方法:public string (string xxx)
 *     比较两个字符串是否相等,用方法  public boolean equals(string str)
 */
public class StringDemo {
public static void main(String[] args) {
    String www = "hello"; //直接为www 初始化
    String yyy = new String("hello");// 这里是用到string的构造方法来赋值的,构造方法:public string (string xxx)
    String uuu = yyy;
    System.out.println(www.equals(yyy));
    System.out.println(yyy.equals(uuu));
}
}

 2、demo2

/*
 * 在student类中写了一个比较学生年龄的方法,并测试
 * 学习点:写方法时要灵活运用所学的对象的知识,传递参数时要考虑能不能用对象来实现呢?
 * object类中提供了equals方法就是比较两个对象的大小,所以equals方法就可以取代compare方法
 * 以后只要是比较两个对象中的属性的大小就用equals()方法
 */

package cn.itcast;

public class StudentTest2 {
    public static void main(String[] args) {
        Student s1 = new Student();
        Student s2 = new Student();
        Student s = new Student();
        s1.setAge(10);
        s2.setAge(10);
        s1.setName("劉德華");
        s2.setName("劉德華");
        // public boolean compare(int age1,int age2)
        // {
        // age1==age2;
        // }
        // boolean flag = s.compare(s1.getAge(),s2.getAge());
        // System.out.println(flag);第一种方法
        // boolean flag = s.compare(s1,s2);
        // System.out.println(flag); 第二种方法
        // boolean flag = s1.compare(s2);
        // System.out.println(flag);
        // 这是第三种方法

        boolean flag = s1.equals(s2);
        System.out.println(flag);

    }

}

 

posted @ 2017-03-16 19:24  初学者,方圆几里  阅读(183)  评论(0编辑  收藏  举报