string 是一个常量

string不管有没有new,都是它的对象

String a  = new String();

String b = {‘A’,’B’};

String c = {97,98};


常量池

字符串常量池:程序当中直接写上的双引号字符串,就在字符串的常量池中。

 

==:

对于基本类型,是进行数值的比较

对于引用类型,是进行地址值的比较

public class StringDemo {

    public static void main(String[] args) {

        String str1 = "abc";

        String str2 = "abc";

        char[] charArray = {'a','b','c'};

        String str3 = new String(charArray);

 

        //判断

        System.out.println(str1 == str2);//true

        System.out.println(str1 == str3);//false

 

    }

}

关于String常量池,equals方法的一些领悟

 

注意,equals比较时应该将字符串常量放在前面,否则将变量放在前面时可能出现空指针的异常

String h = "hello";

String i = null;

 

//测试

System.out.println(h.equals("hello"));//true

System.out.println("hello".equals(h));//true

System.out.println(i.equals("hello"));//报错 Exception in thread "main” java.lang.NullPointerException

System.out.println("hello".equals(i));

相关文章:

  • 2021-07-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-12
  • 2022-12-23
  • 2022-12-23
  • 2021-07-22
猜你喜欢
  • 2022-02-08
  • 2021-07-29
  • 2021-10-12
  • 2021-07-12
  • 2021-11-19
  • 2021-08-09
相关资源
相似解决方案