Common Interview Questions for String

The following code is a small part of String interview questions I collected on the Internet a few days ago. Personally, I feel very deeply, and I hope it can be helpful to everyone. If it is not good, please criticize and correct.

1  package com.zys.string;
 2  
3  public  class Demo3_StringMianShi {
 4  
5      /** 
6       * @The equals() method in this is in String, which is different from the equals() method in Object
 7       * These are common in String 8       */ 
9      public  static  void main(String[] args) {
 10          // demo1
 ();
 11          // demo2();
 12          // demo3();
 13          // demo4(); 
14          String s1 = "ab" ;
 15          String s2 = "abc" ;
 16         String s3 = s1 + "c" ;
 17          System.out.println(s3 == s2); // false s1, s2 are both in the constant pool, s3+"c" is a StringBuffer object and must be converted to a String 
object18          System.out.println(s3.equals(s2)); // true 
19      }
 20  
21      private  static  void demo4() {
 22          String s1 = "a" + "b" + "c" ;
 23          String s2 = "abc " ;
 24          System.out.println(s1 == s2); // true java has constant optimization mechanism 
25          System.out.println(s1.equals(s2));//true
26     }
27  
28      private  static  void demo3() {
 29          String s1 = new String("abc" );
 30          String s2 = "abc" ;
 31          System.out.println(s1 == s2); // false 
32          System.out. println(s1.equals(s2)); // true 
33      }
 34  
35      private  static  void demo2() {
 36          // The following code creates a total of 
37 objects          String s1 = new String("abc"); // two An object, because it is new, a space is opened up in the heap memory, with an address value of 
38         System.out.println(s1);
 39      }
 40  
41      private  static  void demo1() {
 42          /* 
43           * Both are true, because s1 and s2 point to the same object, both in the constant variable pool
 44           */ 
45          String s1 = "abc" ;
 46          String s2 = "abc" ;
 47          System.out.println(s1 == s2); // true 
48          System.out.println(s1.equals(s2)); // true 
49      }
 50  
51 }

This is the first blog I wrote to myself, I am in a good mood, and I hope I can go further and further. .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325385330&siteId=291194637