• 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
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

I cant believe my eyes?

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

public class ADirtyOne
{
private final int i =10;
private byte k = i;

}

I had thought the code wouldn't compile(it need a explicit cast),but when I compile ,it compile clearly without any warning.
I thought the int is wide than byte ,so when convert a int to a byte ,need a explicit cast( private byte k=(byte)i
Am I right?
 
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, james, the compiler takes initialised final primitive variables as constants, so you code is the same as:

Note that the following code does not compile:

when the final identifier is removed.
Hope it helps.
Guoqiao

[This message has been edited by Guoqiao Sun (edited July 31, 2001).]
 
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi James,
private final int i = 127;
byte k = i ;
This will compile . The reason being that 127 fit's as a byte & the fact that i is final which means it won't change throughout it's lifetime .
Now try
private final int i = 128;
byte k = i ;
This won't compile cause i doesn't fit the byte range .
Ashish
 
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bottom line... check for 2 things
1. Range of values
2. Final declaration
int i = 127;
byte b = i; //This will never compile unless explicitly casted
//or make i as final
byte b = 127; //Narrowing conversion looks for only for range
HTH
 
reply
    Bookmark Topic Watch Topic
  • New Topic