字符串
作者:互联网
字符串的直接赋值:
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,equals,System,println,字符串,strb,out 来源: https://www.cnblogs.com/dododo70/p/10374113.html