java--by a selection problem study value out of bounds

Source: Internet
Author: User

The original topic from the Cattle Network Java Special Exercise:

Here is the code.

1  Public classTest2 {2      Public Static voidAdd (Byte b)3     {4b=b++;5     }6      Public Static voidMain (string[] args)7     {8Byte a =127;9Byte b =127;TenAdd (+ +a); OneSystem.out.print (A + ""); A Add (b); -System.out.print (b + ""); -     } the}

Output result:-128,127.

Note that byte is a sub-class of byte, the range is [ -128,127],add function is the value of the pass, the value of a is not affected, a out of bounds to 128, is not the problem of unpacking?

Change byte to byte again, and find out whether the output is:-128,127. The problem is not here.

Try outputting the binary before and after the a++.

1  Public classTest {2      Public Static voidMain (string[] args)3     {4         5Byte a =127;6 System.out.println (Integer.tobinarystring (a));7 System.out.println (a);8a++;9 System.out.println (Integer.tobinarystring (a));Ten System.out.println (a); One          A          -     } -}

Output Result:

Because there is no way to divide decimal into binary in byte. Use Integer.tobinarystring () here. This method automatically clears the 0 in front of the binary.

So the value before and after the a++ is. 01111111,10000000.

So, what about a++ on? The output result is 10000001=-127.

Same-128-1 get results for 0111111=127

What about declaring a variable or assigning a value to a variable?

1  Public classTest {2      Public Static voidMain (string[] args)3     {4         5Byte A = (byte) 128;6 System.out.println (a);7A= (byte) 129;8 System.out.println (a);9         Ten     } One}

Output, -128,-127.

Note that Java does not check for values that are out of bounds, but calls only the values stored in memory that declare the variable size.

So how does the JVM avoid changing the value of variables beyond the variable values? Curious. First put it here and learn to study the JVM machine again.

java--by a selection problem study value out of bounds

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.