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():将字符串对象转换为字符数组

  • 相关阅读:
    学习如何看懂SQL Server执行计划(一)——数据查询篇
    【异常】warning: refname 'feature1.3.0' is ambiguous.导致git merge失败
    Mac上使用sunlogin向日葵软件远程控制电脑
    软件随想录-
    idea启动卡死,项目界面一直processing
    【异常】hbase启动后hdfs文件权限目录不一致,导致Phoenix无法删除表结构
    【异常】ssh无法登录验证,非root用户ssh本机无法成功
    【异常】postman能够请求成功获取到参数,前端请求的却请求不到
    CentOS7磁盘空间不足,却找不到占用空间的大文件
    【异常】553 Mail from must equal authorized user
  • 原文地址:https://www.cnblogs.com/zhpdqs/p/7738863.html
Copyright © 2011-2022 走看看