zoukankan      html  css  js  c++  java
  • Java中的String

    public class Test{
        public static void main(String[] args) {
    		String s1="hello";
    		String s3="hello";
    		String s2=null;
    		System.out.println(s1==s3);
    		s1=new String("hello");
    		s2=new String("hello");
    		System.out.println(s1==s2);
    		System.out.println(s1.equals(s2));
    	}
    
    }
    

     true
    false
    true

    String s1="hello" ;String s3="hello"; hello是字符串常量,分配在datastatement

    s1和s3分配在栈空间,datastatement存在一个hello以后不再存储相同元素

    因此s1==s3

    s1=new String("hello"); s2=new String("hello");

    s1和s2不是相同对象因此不相等

    public class M4 {
    	
    	String s1="hello";
    	String s2=new String("hello");
    	
    	public void change(String s1,String s2) {
    		s1="test";
    		s2="test";
    	}
    	public static void main(String[] args) {
    		M4 ex=new M4();
    		ex.change(ex.s1,ex.s2);
    		System.out.println(ex.s1);
    		System.out.println(ex.s2);
    		System.out.println(ex.s1==ex.s2);
    		System.out.println(ex.s1.equals(ex.s2));
    		
    	}
    	
    }
    

     hello
    hello
    false
    true
    不论是new 出的对象还是分配在datastatement,String内容都不发生改变

    Java中String类有一个compareTo方法,该方法返回一个int类型的数据。
    其比较规则是:拿出字符串的第一个字符与参数的第一个字符进行比较,如果两者不等,比较结束,返回两者的ascii差,即字符串的第一个字符减去参数的第一个字符的ascii码值.
    如果相等,则比较第二个字符,以此类推。比较到最后还是相等的,方法返回值为0。
    如果两个字符串的长度不同,并且一个字符串与另一个字符串的前面N个字符相等,那么这个方法返回返回两个字符串长度之差。
     
  • 相关阅读:
    分享一下前一段时间的开发总结
    循环,梦
    从C#程序中调用非受管DLLs
    大学生零工资就业,谁之过?
    国外宽带用户的上网速度能达到多少呢?
    天沉沉,来个好天气吧
    虚伪,不只是形容一个人
    回头思考关于xml的使用
    从毕业生当中看人与人的差距
    C# 编码规则
  • 原文地址:https://www.cnblogs.com/52circle/p/8982256.html
Copyright © 2011-2022 走看看