Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# who can explain me this please ??

Ranch Hand
Posts: 189
I was trying by mysel the following :

int i =10;
private byte k = i ;

this won't compile, but when declare i final, it compiles fine

final int i =10;
private byte k = i ;

This will compile

Could you explain me why ??

Deepak Bala
Bartender
Posts: 6663
5
A final int is a compile time constant. What that means is that you cannot change the value of that int at runtime. So the compiler now knows what the value of int is and whether it can fit into the byte. So it compiles.

However if the int were not final its value may not be in the range of a byte. So the compiler cannot know for sure if the assignment is legal. Try these different code snippets

int i = 10;
byte b = i;

final int i = 10;
byte b = i;

final int i = 256;
byte b = i;

Ralph Jaus
Ranch Hand
Posts: 342
A final int is a compile time constant
Note that John is using a different definition of a compile time constant than K&B (see chap. 5 under "Legal expressions for switch and case", page 324): There a compile time constant is final and the value is assigned in the declaration.
So it compiles
This is true only for compile time constants in the sense of K&B. For example

final int i;
i = 10;
byte b = i;

won't compile, but

final int i = 10;
byte b = i;

will.

Ranch Hand
Posts: 189
Thanks my friends, I got it.

Regards

Faber Siagian
Ranch Hand
Posts: 52
Hi John,

I think compile-time constant is a prerequisite for "case" legal argument, and nothing to do with this case.

the value of i is still in the range of byte, and yes, it won't be compiled successfully, because you need an explicit cast on it.

It should be fine.

kaushik vira
Ranch Hand
Posts: 102
public class Test {

final int i =10;
private byte k = i ;

}

This is very simple.. compiler doing optimizations on code. it`s final so it`s value not got to be change. onces you compile this code then latter when you decompile this code. you will get code like following.

public class Test
{

public Test()
{
k = 10;
}

final int i = 10;
private byte k;
}

now there is no relation between int and byte like k=i; like. now it`s totally independent and not affect each other. and 10 is in range of byte so again no need to cast it.

every compiler doing compile time optimization on code.

for future detail go Java performance tunning.

[ July 21, 2008: Message edited by: kaushik vira ]

[ July 21, 2008: Message edited by: kaushik vira ]
[ July 21, 2008: Message edited by: kaushik vira ]