aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Can't figure please help! 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 "Can Watch "Can New topic
Author

Can't figure please help!

Mike Kelly
Ranch Hand

Joined: Jul 18, 2001
Posts: 78
class MyClass
{
public static void main(String []args)
{
final int i = 100;
byte b = i;
System.out.println(b);
}
}
------------------------------------------------
class MyClass
{
public static void main(String []args)
{
int i = 100;
byte b = i;
System.out.println(b);
}
}
-----------------------------------------------
The top class compiles and prints 100. The bottom class gives compiler error, stating possible loss of percision, why please?
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
You can't assign an int to a byte without a cast. It is considered a narrowing conversion and data might be lost.
In the first case, however, we use the keyword final, which makes that value a compile-time constant. Therefore, the compiler can check to see if the value is within the range of a byte for the assignment. This can't be done if the variable is not final. That's why the second one gives a compiler error while the first one doesn't.
I hope that helps,
Corey


SCJP Tipline, etc.
Mike Kelly
Ranch Hand

Joined: Jul 18, 2001
Posts: 78
Excellent Corey thank-you.
Kumar Kausikasa
Ranch Hand

Joined: Jun 04, 2002
Posts: 45
Hi ,
Just for the info Chapter 4 of RHE clearly the above stuff.
Praveen.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can't figure please help!
 
Similar Threads
primitive type convert
This is from Tip Smarts Sample Paper
how about this test?
automatic primitive conversion from higher to lower precision?????
What is the output for First Snippet and Second Snippet?