File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can't figure please help!

 
Mike Kelly
Ranch Hand
Posts: 78
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Mike Kelly
Ranch Hand
Posts: 78
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent Corey thank-you.
 
Kumar Kausikasa
Ranch Hand
Posts: 45
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic