70 String (a) - literal and a new and important interview questions

Literal is so directly amount 123 'a' "fff" and the like.

Creating variable initialization values ​​recommended literal because literal can be achieved using the multiplexing. Including the use of new existence is bound to open up new space.

Literal example

Str1 = String "123"; 
String str2 = "123"; 
String Str3 = "12 is"; 
Str3 = Str3 + ". 3"; 
System.out.println (str1 == str2); // address comparison, this time It is to true 
System.out.println (str1 == str3); // false, because str3 point is not the first to be created in memory of "123"

  

new content comparison string

Use inevitably open up new space in memory.

Str1 = String "123"; 
String str2 = new String ( "123"); 
System.out.println (str1 == str2); // false, because new opened up a new space, not reuse the first "123"

  

An important interview questions

String str1 = "123abc";
String str2 = "123"+"abc";
String str3 = "123";
String str4 = str3+"abc";
System.out.println(str1==str2);//true
System.out.println(str1==str4);//false

  

The first result is true, because the java at compile time, found that "123" and "abc" It is this line are eternal, so this direct line (Line 2) at compile time seen as a String str2 = "123abc";, so it str1 points to the same address.

The second result is false, because str4 splicing a variable, it first opens a space, the value of the variable stitching put up, follow-up of content on the stitching, so str4 not point to the first "123abc" object.

Guess you like

Origin www.cnblogs.com/Scorpicat/p/12083764.html