1

Here is the code

import java.util.*;
 class Example
 {
  public static void main(String args[])
  {
    final int x=127; int y=100;
    byte b;
    b=x; //Legal ?
    b=y; //Illegal 
  }
 }

Can you explain why b=y is illegal? I think final means no further change, is that correct?

6
  • 1
    Can you explain which lines do you expect to be legal and illegal? Otherwise it's quite hard to guess which aspect of this code it is that you are confused about. Commented Jan 28, 2020 at 19:32
  • 2
    You don't mention even if you have tried to compile it. Have you? What do you understand from the compiler output result? Commented Jan 28, 2020 at 19:33
  • line 8 & 9 th... b=x; b=y; Commented Jan 28, 2020 at 19:34
  • compile error: incompatible types: possible lossy conversion. Commented Jan 28, 2020 at 19:36
  • 1
    So, you're trying to store an int value (bigger) into a byte (smaller) box. Nothing related with the 'final' word. You'll find it useful to read the Java Tutorial at docs.oracle.com/javase/tutorial/java/nutsandbolts/… Commented Jan 28, 2020 at 19:37

1 Answer 1

9

The final keyword does mean "no further change", so you're correct there. The issue here has to do with data "width".

An int can hold more data than a byte (i.e. it is "wider" than a byte). This means that when you do b = x, you're "narrowing" the width of the int to fit into the byte. This only works if the compiler can guarantee that the int is small enough to fit into the byte, which requires the int to be <= 127, and to also be final (so that it cannot later be changed to be > 127).

In your code, both x and y are narrow enough to fit into a byte, but only x is final, so it's the only one the compiler allows to be directly assigned to a byte variable.

  final int x=127; final int y=100; // Made y final
  byte b;
  b=x; //Legal
  b=y; //Also legal 
  final int x=200; final int y=100; // Made x too big
  byte b;
  b=x; //Illegal
  b=y; //Legal 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.