Home > Java > javaTutorial > Analysis of selected Java basic knowledge

Analysis of selected Java basic knowledge

黄舟
Release: 2017-09-11 10:43:30
Original
1039 people have browsed it

Selected Java basic knowledge to explain, see how many answers you can get right?

Lack of technical depth is the norm for most programmers.

Integer comparison

Look at the interesting code below. Have you noticed any abnormalities if you are sensitive to numbers?


public static void main(String[] args) {
    Integer a = 128,b=128; 
    Integer c = 127,d=127;
    System.out.println(a==b); 
    System.out.println(c==d);
}
Copy after login

If your answer is false, false, maybe you have a certain foundation and know that Integer is an encapsulated class. Of course, if your answer is true, then it is within a certain range of knowledge, but the basic knowledge is not good enough.

Okay, let's run the main method. The correct answer should be false or true. This question appeared in many interview questions in the past few years. Of course you will also say, I can do projects and it will be ok. I just need to check it. Why do I need to know? I have nothing to say.

In fact, when we assign an int value to an Integer object, the static method valueOf of the Integer class will be called. Let us take a look at how the source code is implemented.

The IntegerCache method has clear comments, cache scope, how to modify it, etc.


 /**
   * Cache to support the object identity semantics of autoboxing for values between
   * -128 and 127 (inclusive) as required by JLS.
   *
   * The cache is initialized on first usage. The size of the cache
   * may be controlled by the -XX:AutoBoxCacheMax=<size> option.
   * During VM initialization, java.lang.Integer.IntegerCache.high property
   * may be set and saved in the private system properties in the
   * sun.misc.VM class.
   */

  private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];

    static {
      // high value may be configured by property
      int h = 127;
      String integerCacheHighPropValue =
        sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
      if (integerCacheHighPropValue != null) {
        int i = parseInt(integerCacheHighPropValue);
        i = Math.max(i, 127);
        // Maximum array size is Integer.MAX_VALUE
        h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
      }
      high = h;

      cache = new Integer[(high - low) + 1];
      int j = low;
      for(int k = 0; k < cache.length; k++)
        cache[k] = new Integer(j++);
    }

    private IntegerCache() {}
  }
Copy after login


 public static Integer valueOf(int i) {
    assert IntegerCache.high >= 127;
    if (i >= IntegerCache.low && i <= IntegerCache.high)
      return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
Copy after login

Magical or not, the code description is very clear. If the value of the integer literal is between -128 and 127 In between, there will not be a new Integer object, but a direct reference to the Integer object in the constant pool, so the above operation result is a==b=false, and c==d=true.

String comparison

The next question should be relatively simple.


public static void main(String[] args) {
    String s1 = "abc"; 
    String s2 = "abc"; 
    String s3 = new String("abc"); 
    System.out.println(s1 == s2); 
    System.out.println(s1 == s3);
  }
Copy after login

Does it look familiar to you guys? Some people may be able to tell at a glance whether the answer is true or false. Of course, don’t be discouraged if you don’t get the correct answer. Let’s analyze why Mao has such an answer.

According to the syntax of ==, first of all, s1, s2, and s3 are three different objects. Generally speaking, the output will be false. However, the running result of the program is indeed true or false. The second output of false is understandable, but the first output of true is puzzling.

We know that some basic types of variables and object reference variables are allocated in the stack memory of the function, while the new objects and arrays are stored in the heap memory. However, in addition to this, there is an area called the constant pool.

Like we usually think of String s1 = "abc"; the value of the string object declared in this way is stored in the constant pool. When we create an object like String s1 = "abc", "abc" is stored in the constant pool (also called the string pool).

When we create a reference to String s2 = "abc", the bottom layer of Java will first search whether "abc" exists in the constant pool. If it exists, let s2 point to this value and will not recreate it. If the constant If the pool does not exist, create and add it to the pool. That's why the answers are true and false.

Comparison between Integer and int


public static void main(String[] args) {
    Integer a = new Integer(128); 
    int b = 128; 
    Integer c = new Integer(6); 
    Integer d = new Integer(6); 
    System.out.println(a == b); 
    System.out.println(c == d); 
  }
Copy after login

I believe many friends are confused, true or false? Let’s announce the answer directly, true or false.

c == d=false, I don’t think there is much to say. Some friends may want to ask, isn’t -128-127 cached? But the Integer we have here is new and not cached, so the result is false.

a == b=true, please note that b here is of type int. When int and Integer are compared ==, the Integer type will be automatically unboxed, that is, the Integer will be converted into the int type. So what is compared here is the value of type int, so the result is true.

The above is the detailed content of Analysis of selected Java basic knowledge. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template