字符串
字符串的直接赋值:
String 变量 = "字符串";
字符串的比较:(== 和 equals的区别)
== 比较是储存字符串的内存地址
equals()方法比较的是字符串的内容
public class Demo{ public static void main(String args[]){ String stra = "hello"; String strb = new String("hello"); String strc = strb; System.out.println(stra==strb); System.out.println(stra==strc); System.out.println(strb==strc); } } /*----------------------------- E:\Javacode>java Demo false false true E:\Javacode>*/
public class Demo{ public static void main(String args[]){ String stra = "hello"; String strb = new String("hello"); String strc = strb; System.out.println(stra.equals(strb)); System.out.println(stra.equals(strc)); System.out.println(strb.equals(strc)); } } /*--------------------------------------- E:\Javacode>java Demo true true true E:\Javacode>*/
开发之中判断字符串时,一定要将字符串写在前面:
if( input.equals("hello")){ System.out.println("hello world!"); } //以上操作如果用户的输入为null的话,则会出现空指向异常。 //正确的方法应该是用字符串去调用 equals()方法 if("hello".equals(input)){ System.out.println("hello world!"); }
直接赋值的字符串为什么可以共用一块相同的堆内存地址:
在JVM的底层存在一个对象池,当代码中使用了直接赋值的方式定义了一个String对象,会将这个字符串对象所使用的匿名对象入池保存,如果后续还有其他的String对象也采用直接赋值的方式,并且设置同样的内容的时候,就不会开辟新的堆内存空间,而是使用已经有的对象进行引用分配。
通过对象实例化的方式定义的String对象,其内容不会保存在对象池,如果要手工入池:
public String intern();
public class Demo{ public static void main(String args[]){ String stra = new String("hello").intern(); String strb = "hello"; System.out.println(stra==strb); } } /*---------------------- E:\Javacode>java Demo true E:\Javacode>*/