jQuery in Action, 2nd edition*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes This is from Tip Smarts Sample Paper Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "This is from Tip Smarts Sample Paper" Watch "This is from Tip Smarts Sample Paper" New topic
Author

This is from Tip Smarts Sample Paper

Vijayalakshmi Chipada
Greenhorn

Joined: Dec 04, 2000
Posts: 17
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


Ch. Vijayalakshmi
Ishaan Mohan
Ranch Hand

Joined: Jan 20, 2001
Posts: 115
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

Joined: Mar 04, 2001
Posts: 1
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

Joined: Aug 30, 2000
Posts: 3141
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


Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: This is from Tip Smarts Sample Paper
 
Similar Threads
primitive type convert
Final Keyword
how about this test?
What is the output for First Snippet and Second Snippet?
Can't figure please help!