• 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:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Frits Walraven
Bartenders:
  • Carey Brown
  • salvin francis
  • Claude Moore

primitive type convert  RSS feed

 
Greenhorn
Posts: 13
  • 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);
}
}
After run the above code, it compile and print 100. Why it does not need an explicitly cast? i is larger than byte, right? Please help! Thanks
 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it works only if the int is declared as final. if the int is not a constant the compiler gives a loss of precision error.
 
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that is really bizarre, i had not heard of this (i am of course still learning).
i guess, it is allowed, because if the int is final (not allowed to be changed), and fits in the range of a byte, then it can be done?
 
Ranch Hand
Posts: 2545
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Once it is declared as final, it won't change. So the compiler know for sure i=100 is ok with byte.
 
I will suppress my every urge. But not this shameless plug:
Create Edit Print & Convert PDF Using Free API with Java
https://coderanch.com/wiki/703735/Create-Convert-PDF-Free-Spire
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!