课后作业二

为什么会有上述的输出结果?从中你又能总结出什么?

给字串变量赋值意味着:两个变量(s1,s2)现在引用同一个字符串对象“a”! String对象的内容是只读的,使用“+”修改s1变量的值,实际上是得到了一个新的字符串对象,其内容为“ab”,它与原先s1所引用的对象”a”无关,所以,s1==s2返回false; 代码中的“ab”字符串是一个常量,它所引用的字符串与s1所引用的“ab”对象无关。 String.equals()方法可以比较两个字符串的内容。

2.请查看String.equals()方法的实现代码,注意学习其实现方法。

public class StringEquals {

    
/**
     * @param args the command line arguments
     */
    
	public static void main(String[] args) {
        
		String s1=new String("Hello");
        
		String s2=new String("Hello");

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

        
		String s3="Hello";
        
		String s4="Hello";

          
		System.out.println(s3==s4);
        
		System.out.println(s3.equals(s4));
        
    
	}


}

  

String类对equals()方法进行了覆盖,只要引用指向的对象的内容是一样的就认为他们相等。而Object类默认的equals()方法就是比较两个引用指向的对象本身,如果指向同一个对象,那就认为他们是相等的,否则不相等,除非像String类那样对其进行覆盖重写。

3.

String类的方法可以连续调用: String str="abc"; String result=str.trim().toUpperCase().concat("defg"); 请阅读JDK中String类上述方法的源码,模仿其编程方式,编写一个MyCounter类,它的方法也支持上述的“级联”调用特性,其调用示例为: MyCounter counter1=new MyCounter(1); MyCounter counter2=counter1.increase(100).decrease(2).increase(3); ….

package kehouzuoye;

public class MyCounter {
	int num;
	MyCounter(int a){
		num=a;
	}
	MyCounter increase(int b) {
		this.num+=b;
		return this;
	}
	MyCounter decrease(int c) {
		this.num-=c;
		return this;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		MyCounter counter1=new MyCounter(1);
		MyCounter counter2=counter1.increase(100).decrease(2).increase(3);
		System.out.println(counter2.num);
		
	}

Length():获取字串长度

charAt():获取指定位置的字符

getChars():获取从指定位置起的子串复制到字符数组中(它有四个参数,在示例中有介绍)

replace():子串替换

toUpperCase()、 toLowerCase():大小写转换

trim():去除头尾空格:

toCharArray():将字符串对象转换为字符数组

原文地址:https://www.cnblogs.com/zhpdqs/p/7738863.html