• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using Final Keyword & Casting

 
Chatura Dilan
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Compare following code

public class Cat{

public static void main(String args[]){

int x = 20;
byte y = 10;

y = x;

System.out.println(y);
}
}


Compilation Error

java:8: possible loss of precision
found : int
required: byte
y = x;
^
1 error

Above code is OK, because I have to do casting like this

y =(byte) x;


but look at this


public class Cat{

public static void main(String args[]){

final int x = 20;
byte y = 10;

y = x;

System.out.println(y);
}
}

This example prints 20 and no compilation error

I do not understand why it implicitly converts int to byte, when I use final keyword.

Thanks in advance.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a situation of a narrowing primitive conversion.

Basically the reason that it works is that because the int value on the right of the assignment statement is a compile-time constant, and its value is compatible with a byte, the compiler will accept the assignment.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic