package day12_01;
/*
* 字符串特点:一旦被赋值,就不能改变
*
* 面试题?
* String s=new String("hello")和String s="hello"区别?
* 有,前者会创建2个对象,后者创建1个对象
* ==:比较的是引用类型的地址值是否相同
* equals:比较引用类型默认也是比较地址值是否相同,而String类重写了equals方法,比较的是内容是否相同
*
* 看程序写结果:
* 字符串如果是变量想家,先开空间,在拼接
* 字符串如果是常量想家,是先加,然后在常量池中找,如果有就直接返回,否则,就创建
* String str=null 和String str=""的区别?
* String str = null 不分配内存空间
* string str = “” 分配内存空间,只是空间大小是空字符串的大小而已
* */
public class StringDemo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// String string = "hello";
// string += " world";
// System.out.println("string:"+string);//hello world
String s1 = new String("hello");
String s2 = "hello";
System.out.println(s1 == s2);// false
System.out.println(s1.equals(s2));// true
System.out.println("----------------------");
//看程序写代码:
String s3="hello";
String s4="world";
String s5="helloworld" ;
System.out.println(s5==s3+s4);//false
System.out.println(s5.equals(s3+s4));//true
System.out.println(s5=="hello"+"world");//true
System.out.println(s5.equals("hello"+"world"));//true
}
}
Java中String字符串比较面试题
原文作者:xiakexiaohu
原文地址: https://blog.csdn.net/xiakexiaohu/article/details/72845050
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/xiakexiaohu/article/details/72845050
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。