String in JAVA and introduce common interview questions

A profound understanding of String


1) String a string constant: the String object Once you create the object can not be changed. (Source below)

Here Insert Picture Description

        String str1 = "abc";
        String str2 = "abc";
        String str3 = new String("abc");
        System.out.println(str1 == str2);
        System.out.println(str1 == str3);

operation result

true
false
  • == Comparison of basic data types when the comparison is a value, comparing the time reference type is the address value comparison. Here is a reference to the type of comparison.
  • Creating "abc" first-time constant pool to see if there is not, then you create one, any direct use. Therefore, the same address value stored str1 and str2, point is the same.
  • Because str3 out of new objects, out of the new stack, and the constant pool str1, the address values ​​can not be equal, it is false.

2)How many Objects created with: String str=new String(“abc”)?

 String str=new String("abc");

A: I create two objects in a heap in a constant pool

  • The implementation of "abc" after a creation, new at the time to create a constant pool in the heap, and the constant pool "abc" a copy of the past. Then assigns a reference to the s1.

3) supplement Case

        String s1 = "a" + "b" + "c";// 在编译时就变成 abc 常量池中创建abc
		String s2 = "abc";
		System.out.println(s1 == s2);// true java中有常量优化机制
		System.out.println(s1.equals(s2));// true

At compile time becomes constant pool abc create abc, both in the constant pool

        String s1 = "ab";
		String s2 = "abc";
		String s3 = s1 + "c";
		System.out.println(s3 == s2);// false
		System.out.println(s3.equals(s2));// true
		

Because this is equivalent to new s3 out, the corresponding address in the stack, s2 corresponding addresses in the constant pool


Spend a little more time trying to make something of yourself and a little less time trying to impress people.

2020.02.25

Published 13 original articles · won praise 11 · views 6018

Guess you like

Origin blog.csdn.net/weixin_45393094/article/details/104506187