![]() ![]() Constant expressions that fit in the type of the variable ( byte in our case) will be automatically converted by the compiler.Ī 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. There are some special language rules for so called assignment contexts. (If it wasn’t byte b = Byte.MAX_VALUE + 0 would not have compiled!)īyte b = a + 1 // can't convert from int to byte Why is a byte not allowed to overflow like an int? Byte.MAX_VALUE happens to be a constant variable. Qualified names of the form TypeName.Identifier that refer to constant variables (§4.12.4) JLS §15.28Ī constant variable is a variable that is final and initialized with a compile-time constant expression.Literals of primitive type and literals of type String (§3.10.5).The JLS refers to this as a compile-time constant expression:Ī compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following: The compile error only occurs when there's a byte overflow, which reveals that the computation is performed at compile time. println( type( a + b)) // "int"īut as we saw earlier, there's something else at play here… Something about that overflow… In our snippet Byte.MAX_VALUE will therefore be promoted to an int and the result of the addition will be of type int.Įxample: A byte plus a byte is an int: String type( byte b) The + operator is indeed only defined for int, long, float, double and String operands. MAX_VALUE + 1 // not allowed to overflowīefore you shout " Byte.MAX_VALUE + 1 is an int expression! This is a simple type error!" note that this does compile: byte b = Byte. ![]() MAX_VALUE + 1 // allowed to overflow byte b = possible lossy conversion from int to byteByte. Why are int expressions allowed to overflow, but not byte expressions? int i = Integer. Java: Integers may overflow, but bytes may not?
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |