JDK源码阅读-------自学笔记(十一)(java.lang.String包装类)

核心要点

  • String 类对象代表不可变的Unicode字符序列,因此我们可以将String对象称为“不可变对象”
  • String的核心就是char[]字符串,外部写的string对象,都会放入char[]字符串中
  • char[] 数组被final限制是一个常量,所以只能赋值一次,这便是把char成为不可变量原因之一
  • 看到的字符串变化,都是方法内新建的对象,新建的对象进行的重新赋值

源码:

1 public final class String
2     implements java.io.Serializable, Comparable<String>, CharSequence {
3     /** The value is used for character storage. */
4     private final char value[];
5         
6         ....
7     }
View Code

新建对象

 1 public String substring(int beginIndex, int endIndex) {
 2         if (beginIndex < 0) {
 3             throw new StringIndexOutOfBoundsException(beginIndex);
 4         }
 5         if (endIndex > value.length) {
 6             throw new StringIndexOutOfBoundsException(endIndex);
 7         }
 8         int subLen = endIndex - beginIndex;
 9         if (subLen < 0) {
10             throw new StringIndexOutOfBoundsException(subLen);
11         }
12         return ((beginIndex == 0) && (endIndex == value.length)) ? this
13             
14             // 新建对象
15                 : new String(value, beginIndex, subLen);
16     }
View Code

比较的使用方式

  • '=='进行String对象之间的比较 '=='是两个对象之间进行比较,这里比较需要使用equals进行比较 编译器优化:
    1  //相当于stringValue = "hello java";
    2         String stringValue= "hello" + " java";
    3         String stringValueNew= "hello java";
    4         //true
    5         System.out.println(stringValue == stringValueNew);
    View Code

异常代码:

1  String stringValueNew = "hello java";
2 
3         String helloString = "hello";
4         String javaString = "java";
5 
6         //编译的时候不知道变量中存储的是什么,所以没办法在编译的时候优化
7         String finalString = helloString + javaString;
8         //false
9         System.out.println(finalString == stringValueNew);
View Code

注: 

    字符串比较一定要使用equals方法

String其他方法是用请参见: (https://www.cnblogs.com/liuyangfirst/p/12316114.html "String方法使用详情")

原文地址:https://www.cnblogs.com/liuyangfirst/p/12829282.html