0

I have a doubt regarding type conversion between numeric values. Below is a snapshot from the book java complete reference. It says integer literals are successfully converted to byte or short provided the range of the value defined fits into the range of byte/short. However, when I try to run the following program it throws an error. Kindly clarify. Thanks. book

import java.util.Scanner;
class Test{
 public static void main(String args[])
 {   int a=10;
     byte b=16;
     b=a;
     System.out.println(b);
 }}
/tmp/IQOgFrykLL/Test.java:12: error: incompatible types: possible lossy conversion from int to byte
b=a;
^1 error

  • try casting the int to a byte – Scary Wombat Feb 17 '23 at 08:28
  • Simple explanation: The statement `b = a;` is not assigning a LITERAL to `b`. So the section of the book that talks about assigning LITERALS does not apply to that statement. The book is correct. – Stephen C Feb 17 '23 at 13:05
  • I recommend that you read this self-answered question that I wrote on this topic: https://stackoverflow.com/questions/51632152 – Stephen C Feb 17 '23 at 13:08

1 Answers1

1

It says integer literals are successfully converted to byte or short

b=a doesn't involve an integer literal.

An integer literal is something like 10 or 16: an actual number that appears in the source code.

b=10 would work, because 10 is an int literal.

Actually, it's a bit more general than only working with int literals: you can make this assignment with any compile-time constant value.

For example, if you were to make a final, it would work, because then a would be a compile-time constant value, and essentially could then be replaced by the int literal 10 wherever it is used.

Note that the definition of "compile time constant" is quite strict: it has to be a literal, or a final variable initialized with a compile-time constant value.

  • Declaring a non-final variable and never changing its value doesn't make it compile-time constant: you have to tell the compiler that its value can't change via final.
  • Declaring a variable as final doesn't make it a compile-time constant either: the value you assign it has to be a compile-time constant too.
Andy Turner
  • 137,514
  • 11
  • 162
  • 243