Home > Java > javaTutorial > body text

Detailed explanation of the range of Integer values ​​in Java

黄舟
Release: 2017-09-09 10:34:24
Original
3151 people have browsed it

This article mainly introduces the example code of the range of Integer values ​​in JAVA. Friends who need it can refer to it

No more nonsense, I will directly post the code for you. The specific code is as follows:


package com.test;
public class Test {
  public static void main(String []args) {
   Integer a = 100;//此处若使用new,则==值必为false
   Integer b = 100;
   System.out.println(a==b);//true
   Integer c = 150;
   Integer d = 150;
   System.out.println(c==d);//false
  }
}
Copy after login

What is the reason for this?

1. When java is compiled, Integer a = 100; is translated into -> Integer a = Integer.valueOf(100);

 2. When comparing, it is still a comparison of objects

 3. In the jdk source code


public static Integer valueOf(int i) { 
  final int offset = 128; 
  if (i >= -128 && i <= 127) { // must cache 
  return IntegerCache.cache[i + offset]; //符合值范围时候,进入也创建好的静态IntergerCache,i+offset的值表示去取cache数组中那个下标的值
  } 
  return new Integer(i); //当不符合-128 127值范围时候。记住用的:new,开辟新的内存空间,不属于IntergerCache管理区
}
Copy after login

And


private static class IntegerCache { 
  private IntegerCache(){} 
  static final Integer cache[] = new Integer[-(-128) + 127 + 1]; //开辟-128到127的内存区。有0的位置哦
  static { 
    for(int i = 0; i < cache.length; i++) 
      cache[i] = new Integer(i - 128); //为内存区的数组每个对象赋值
    } 
  }
Copy after login

Here is java initialized -128- in order to improve efficiency An integer object between -127, so the assignment is the same object within this range.

Add another sentence


Integer a = 100;
  a++;
  //这边a++是新创建了一个对象,不是以前的对象。
  public static void main(String []args) {
    Integer a = 100;
    Integer b = a;//此时b指针指向值为100的堆地址 即a的堆地址,a==b成立
    a++;//此时a指向的值发生变化为101,a指针指向101的堆地址。而b任然指向100
    System.out.println(a==b);//false
  }
Copy after login

Summary

The above is the detailed content of Detailed explanation of the range of Integer values ​​in Java. 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