Challenge four Java questions

  • 2020-04-01 04:32:56
  • OfStack

Four basic Java questions, how many can you answer?

The use of ==
Let's start with an interesting piece of code


Integer a = 1000,b=1000; 
Integer c = 100,d=100;  public void mRun(final String name){ 
    new Runnable() { 
       
      public void run() { 
        System.out.println(name); 
      } 
    }; 
  } 
   
 
System.out.println(a==b); 
System.out.println(c==d); 

If you can get the right answer and understand how it works. That means you're okay. If your answer is true and true, your foundation is lacking.
First announced the answers, to run the code, we will get false  True. We know that == is comparing the references of two objects, and the abcd here are both newly created objects, which should be false. This is the interesting part of this question, whether it is an interview question or a discussion forum, this question has a high attendance rate. The principle is very simple. Let's look at the class integer.java.


public static Integer valueOf(int i) { 
   return i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128]; 
 } 
 
  
 private static final Integer[] SMALL_VALUES = new Integer[256]; 
 
 static { 
   for (int i = -128; i < 128; i++) { 
     SMALL_VALUES[i + 128] = new Integer(i); 
   } 
 } 

          When we declare an Integer c = 100; From time to time. At this point, autoboxing occurs, simply by converting the basic data type to an Integer object, which is the valueOf method being invoked. As you can see, -128-127 is cached in the Integer. The official explanation is that small Numbers are used more frequently, so the Numbers in between are cached for optimal performance. That's why the answer to this question is false and true. When the declared Integer object has a value between -128 and 127, the same object is referenced, so the result is true.
Second, the String
So let's look at the code


String s1 = "abc"; 
String s2 = "abc"; 
String s3 = new String("abc"); 
System.out.println(s1 == s2); 
System.out.println(s1 == s3); 

Again, guess what the answer is?
            According to the syntax of ==, s1, s2, and s3 are three different objects. In general, the output will be false. However, the result of running the program is true and false. The second output false is understandable, and the first output true is confusing. We know that some primitive types of variables and object reference variables are allocated in the stack memory of the function, and the heap memory holds the new objects and arrays. However, there is another area called the constant pool. Like we usually think of String s1 as "ABC "; The value of the declared string object is stored in a constant pool. When we create an object like String s1 = "ABC", the "ABC" is stored in the constant pool (also called the String pool), when we create the reference String s2  When = "ABC", the Java layer will look for the existence of "ABC" in the constant pool first. If so, s2 will point to this value and will not be recreated. If not, the pool will be created and added. That's why the answers are true and false.

Final keyword
So let's look at a piece of code


 public void mRun(final String name){ 
    new Runnable() { 
       
      public void run() { 
              try { 
               Thread.sleep(1000); 
              } catch (InterruptedException e) { 
               // TODO Auto-generated catch block 
              e.printStackTrace(); 
              }  
              System.out.println(name); 
      } 
    }.start(); 
  } 

          I'm sure you've written a lot of this code. When an inner class accesses a local variable, it needs to put a final modifier before the local variable, or the compiler will report an error. That's usually what we do. Okay, second question, why do we add the final modifier? I believe that most of my friends have not thought about this problem, but whenever it is used, directly add to it, never go deep into the principle. This is not desirable for a good programmer, we should not only know how it is but also why it is.
          Now let's analyze why we add the final keyword. First, the lifecycle of an inner class is member-level, whereas the lifecycle of a local variable is the body of a method or something like that. That is, when the mRun method executes, the new thread runs, and the new thread sleeps for a second. The main thread continues, mRun completes, and the life cycle of the name attribute ends. After 1 second, syetem.out.printh (name) executes. At this point, however, the name is dead and out of memory. In order to prevent this error, Java strictly requires internal class local variables, which must be modified with the final keyword. After the local variable is modified with final, there is a copy of the local change in memory, which is actually accessed when the inner class accesses it. It's like taking the lifetime of a local variable and making it longer. The bottom line is that the Java engineers filled in the hole in advance, otherwise I don't know how many friends will worry about internal class local variables.
Integer and int
Look at the following code


Integer a = new Integer(1000); 
int b = 1000; 
Integer c = new Integer(10); 
Integer d = new Integer(10); 
System.out.println(a == b); 
System.out.println(c == d); 

This question is a follow-up to the first one. If you can get the answer to this question very quickly, congratulations. == comparator means you have a good command of it.
The right answer: true  , false
Many of you will be puzzled by this answer, but let's talk about the second one first, and the Integer is caching -128-127, isn't it? This is supposed to be true, but if you look at it carefully, the Integer here is new, it's not a cache, so it's false. Now why is the first one true again? First of all, the value here is 1000, which is definitely not related to the Integer cache as we know it. Since it has nothing to do with the cache, a is a new object, so the input should be false. But notice that b is of type int. When int and Integer are compared with ==, Java will automatically unbox the Integer, that is, convert the Integer to an int, so the comparison is for an int, so the result is true.

Did a few rightness, the level that tests according to oneself quickly, undertake checking to fill up!


Related articles: