【忘不了的Java基础】之String

问题:

  1. String存放在内存的哪个区域中?

  2. String创建几种方式的对比?

  3. String的比较==,和equals()方法,有什么不同?

  4. String为什么要设置成final类型?

  5. String做形参的传递是怎么的?

  6. String,与StringBuffer,StringBuilder?

 

1.String存放在内存的哪个区域中?
2.String创建几种方式的对比?
    public static void main(String[] args) {
        String s1 = "a";  //第一种
        String s3 = "a";
        String s2 = new String("a");  //第二种
​
        System.out.println("s1==s2  "+(s1==s2));  //false
        System.out.println("s1==s3  "+(s1==s3));  //true
​
        System.out.println("s1.equal(s2)  "+s1.equals(s2)); //true
        System.out.println("s1.equal(s3)  "+s1.equals(s3)); //true
    }

 3.String的比较==,和equals()方法,有什么不同?

== 比较的是对象的引用

equals()比较String的内容value

//String源码
public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            if (n == anotherString.value.length) {   //依次比较字符数组的内容
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

 

4.String为什么要设置成final类型?
public final class String
   implements java.io.Serializable, Comparable<String>, CharSequence {

 

5.String做形参的传递是怎么的?

对于一个方法而言,参数是为该方法提供信息的,而不是想让该方法改变自己的。

示例:

public static void main(String[] args) {
​
        String q = "abc";
        System.out.println(q);  //abc
        String qq = upcase(q);
        System.out.println(qq);  //ABC
        System.out.println(q);  //abc
​
    }
​
    public static String upcase(String s){
        return s.toUpperCase();
    }

解读:

当把q传给upcase()方法时,实际传递的时引用的一个拷贝。其实,每当把String对象作为方法的参数时,都会复制一份引用,而该引用所指的对象其实一直待在单一的物理位置上,从未动过

 

 

6.String,与StringBuffer,StringBuilder?

 

猜你喜欢

转载自www.cnblogs.com/tingtingzhou/p/10909198.html