Errors in Java that are easy to make with long and integer

Source: Internet
Author: User

Today, a number of high-risk vulnerabilities were discovered after scanning the project using FindBugs, a very common one being comparison of the = = used directly when comparing two long or integer. In fact, this is wrong.

Because long and Ineger are both wrapper types, they are objects. Instead of the normal type long and int, they must all be compared with equals, either by using the Longvalue () or Intvalue () method to get the values of their base type and using the = = comparison.

However, in a special case, long and integer will -128~127 these objects cache. You can see the long type of source has a Longcache class, the code is as follows:

private static class Longcache {private Longcache () {} static final Long cache[] = new long[-(-128) + 127 + 1]        ;      static {for (int i = 0; i < cache.length; i++) cache[i] = new Long (i-128); }  }

Let's take a look at this example:

public class test05 {         public static void main (String[] args)  {           Long a = 5L;           Long b = 5L;             system.out.println ("a == b ? "  +  (a == b ));            long c = 129l;           Long d = 129L;           system.out.println ("c == d ? "  +  (c ==  d));       }  } 

The result of the printing is:

A = = b? True c = = d? False

Reason

First look at Long a = 5L; It's how to wrap a primitive type long into an object long.

You can write a test class and then decompile it to see how Java resolves a long a = 5L command.

The test classes are as follows:

public class Test06 {Long L = 3L; }

You can then use Javap-verbose Test06 to see the results of the anti-compilation, and here is the part of the output:

{  java.lang.long l;    public com.spring.test.test06 ();     Code:     Stack=3, Locals=1, Args_size=1      0:   aload_0     1:   invokespecial     #10;  //method java/lang/object. " <init> ":() V     4:   aload_0     5:    ldc2_w   #12; //long 3l     8:    invokestatic     #14;  //method java/lang/long.valueof: (J) Ljava/lang/Long;      11:  putfield         #20;  // field l:ljava/lang/long;     14:  return     linenumbertable:     line 3: 0     line 5: 4     line 3: 14       localvariabletable:     start  length  slot  name    Signature     0      15       0    this       lcom/spring/test/ test06;    }

From code 8 can be seen called a long of a class method long.valueof (long), so it can be concluded that long a = 5L is actually equal to long a = long.valueof (5);

Then look at how the Long.valueof () method is defined:

public static long valueOf (long L) {final int offset = 128;      if (l >= -128 && L <= 127) {//would cache return longcache.cache[(int) L + offset];  } return new Long (L); }

At a glance, you will first determine the value of the base type if the cached object is returned directly from the Longcache inside the -128~127, otherwise a new long object is returned.


Now it is not difficult to understand the results of Test05 program execution, because A and B equals 5, within the -127~128, so are directly from the Longcache inside a long object returned, so they use = = comparison, is equal (for the object type, = = Comparing the references of two objects to the addresses in the heap, and C and D equals 129, not between -127~128, so they are the two new long objects that are created separately, and using the = = To compare naturally is not equal.

Long overrides the Equals method:

public boolean equals (Object obj) {if (obj instanceof Long) {return value = = ((Long) obj). Longvalue ();   } return false; }

The Equals method is first obtained by using the. Longvalue () method to get the base type of long object long after the value is compared.

So for the comparison between integer and long, it's best to use equals to make sure we get the results we want.

As long as the integer, this is not an example.


Errors in Java that are easy to make with long and integer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.