Forums Register Login

This is from Tip Smarts Sample Paper

+Pie Number of slices to send: Send
Anyone can you please let me explain about this:
class MyClass
{
public static void main(String []args)
{
final int i = 100;
byte b = i;
System.out.println(b);
}
}
If I compile & run this I am getting 100 as output
----
class MyClass
{
public static void main(String []args)
{
int i = 100;
byte b = i;
System.out.println(b);
}
}
If I compile this, I am getting compiler error.
Please explain the difference

------------------
Ch. Vijayalakshmi
+Pie Number of slices to send: Send
In first case variable is declared as final and compiler knows that a final variable may not be modified once it has been assigned a value. Final variables play the same role as constants in C++ and #define'd constants in C.
As the value assigned to byte var. is with in its range and var is declared as final, compiler have no objection.
+Pie Number of slices to send: Send
HI,
in the first case we have initiliased b toa value 100.
so we get the desired output.
in the second case the error is that we are trying to implicitly type cast an integer to a byte..this type of implcitly type casting is not allowed in java.
hope the answer is satisfactory..
sammy
+Pie Number of slices to send: Send
Hi Vijayalakshmi,
In the first example, you declared 'i' as 'final' variable with a value of '100'.
Whenever you declare a final variable in Java, the compiler optimizes the bytecode to use the declared value in place of the variable reference (at least, that's the net result). So the compiler changes the code to do something like

'100' is within the correct range for a 'byte' so Assignment Conversion ( see JLS §5.2 ) rules apply and no error is generated.
In your second example, 'i' is not 'final', implying that it's value can change at any point during execution. The compiler does not optimize the bytecode. It sees 'i' as any integer value; you cannot assign any integer to a byte; only those within -128 to 128 so a compile error occurs.
Hope that helps.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
Is that a spider in your hair? Here, threaten it with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 656 times.
Similar Threads
how about this test?
Final Keyword
primitive type convert
What is the output for First Snippet and Second Snippet?
Can't figure please help!
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 05:08:49.