• Post Reply Bookmark Topic Watch Topic
  • New Topic

Storing out of range values  RSS feed

 
varsha koli
Greenhorn
Posts: 7
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am storing out of range values in int and byte type





Program will give error for only byte type as OverflowDemo.java:8: error: possible loss of precision
byte b=127+1;
^
required: byte
found: int

So why not for Integer?

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16058
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Values such as 127 and 1 in your code are integer literals; they implicitly have the type int:
An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).


The fact that you can initialize a byte variable with an integer literal without the need to cast it to byte, like this:

is possible because this is a special exception in the Java language specification.

It's explained, although in an indirect way, in paragraph 5.2:
In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:
  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.


  • The value 127 + 10 = 137 is an integer value that does not fit into a byte, therefore you cannot directly assign it to a byte without an explicit cast.
     
    Wilhelm Vogt
    Greenhorn
    Posts: 10
    Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    varsha koli wrote:
    So why not for Integer?



    As for the Integer part, you might look up the JLS on Integer Operations.

    The operation 2147483647 + 10 results in a negative int, even before it is assigned to 'value'.

    Regards
    Wilhelm
     
    Don't get me started about those stupid light bulbs.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!