Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Final with primitives

 
Sridhar Padala
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The below code works fine

class Final
{

public static byte mone()
{
final int i=127;
return i;

}
}

But why the below code is not working as final means compile time constant and can't be changed in the future and the number is in byte range also.

class Final
{

public static byte mone()
{
final float i=127; //not working for long.float and double.
return i;

}
}
Explain in detail the reason. Thanks in Advance
 
Benoît de Chateauvieux
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sridhar Padala,

It's a question for the SCJP forum, not for the SCBCD one...
But the answer is:

Implicit Cast (Narrowing) is only possible with integers literals.
It's mean you can cast implicitly to:
- byte (if the value is < 128)
- short (if the value is < 32768)
- char (if the value is < 65536)

There's no implicit cast with two variable.
But in your case, the int i is final, so it's considered as literal by the compiler.

There's no implicit cast with float and double.

Hope it helps,

Beno�t
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic