public class Test { public static void main(String args[]) { final int i=100; byte b=i; System.out.println(b); } } The output is 100.
Code 2: public class Test { public static void main(String args[]) { int i=100; byte b=i; System.out.println(b); } } I am wondering why it gives out put in first case ie., code 1.
sorry... didn't get your doubt! Was this code from a mock exam, a book? Please contextualize it R u trying to figure out if there is a reason the code author didn't tell the output in the second case? Thanx
Madhu I think the question you want answered is why does the 1st code compile and print 100 and the 2nd code not compile at all, right? In the 1st example the int i is a final varialbe so the compiler knopws that its value will not change. when you assign the value of i to the byte variable b the compiler 'knows' that it is ok, becasue i is final, and will allow the assignment. In the 2nd piece of code the int is not final so the assignment of its value to the byte requires a cast. Because it is a narrowing conversion and i might not always fit into a byte you have to tell the compoiler that it is ok and that it is what you want to do even if you might lose data. hope that helps
Thanks Dave,I got it. From explaination can i conclude like this 1.Any final variable which can fit into another data type say byte is okie as long as value fits in at that time as it is final and compiler knows that it wont change further.
Hi Bindesh: Your issue was different than hers. Yours was about assigning non-static value to a static variable and her's is explicit cast needed for narrowing. Barkat Mardhani
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop