aspose file tools*
The moose likes Beginning Java and the fly likes Using Final Keyword & Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Using Final Keyword & Casting" Watch "Using Final Keyword & Casting" New topic
Author

Using Final Keyword & Casting

Chatura Dilan
Greenhorn

Joined: Apr 22, 2006
Posts: 16
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

Joined: Feb 07, 2005
Posts: 2367
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using Final Keyword & Casting