• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Can't figure please help!  RSS feed

 
Ranch Hand
Posts: 78
  • 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?
 
Ranch Hand
Posts: 3271
  • 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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent Corey thank-you.
 
Ranch Hand
Posts: 45
  • 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.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!