zoukankan      html  css  js  c++  java
  • 课后作业二

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

    给字串变量赋值意味着:两个变量(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():将字符串对象转换为字符数组

  • 相关阅读:
    zsh(yum装包的时候,有时候会不行)
    an error occurred during the file system check错误的解决
    Linux使用tcpdump命令抓包保存pcap文件wireshark分析
    安装win7或win8系统时UEFI和Legacy模式的设置
    查看LINUX当前负载
    svn update 每更新一项就输出一行信息,使用首字符来报告执行的动作 这些字符的含义是:
    svn分支管理进行迭代开发
    Linux命令行下创建纳入版本控制下的新目录
    svn update -r m path 代码还原到某个版本(这样之前的log日志也就没了,也就是清空log日志)
    二进制日志BINARY LOG清理
  • 原文地址:https://www.cnblogs.com/zhpdqs/p/7738863.html
Copyright © 2011-2022 走看看