File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

This is from Tip Smarts Sample Paper

 
Vijayalakshmi Chipada
Greenhorn
Posts: 17
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ishaan Mohan
Ranch Hand
Posts: 115
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sammy Bhasin
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jane Griscti
Ranch Hand
Posts: 3141
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic