源码:
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 }
新建对象
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 }
1 //相当于stringValue = "hello java"; 2 String stringValue= "hello" + " java"; 3 String stringValueNew= "hello java"; 4 //true 5 System.out.println(stringValue == stringValueNew);
异常代码:
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);
注:
字符串比较一定要使用equals方法
String其他方法是用请参见: (https://www.cnblogs.com/liuyangfirst/p/12316114.html "String方法使用详情")
JDK源码阅读-------自学笔记(十一)(java.lang.String包装类)
原文:https://www.cnblogs.com/liuyangfirst/p/12829282.html