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个字符相等,那么这个方法返回返回两个字符串长度之差。
     
  • 相关阅读:
    UIImage的使用
    UIImageVIew的使用
    关于View和VIewController的关系和理解
    ZT Android 4.2蓝牙介绍
    2013深秋红土地旅行计划之井冈山
    系统性能优化
    Reorder List
    Word Break II
    iOS.CocoaPods.0
    Python 知识要点:案例:士兵突击
  • 原文地址:https://www.cnblogs.com/52circle/p/8982256.html
Copyright © 2011-2022 走看看