Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how about this test?

 
Storm Zcm
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class MyClass {

/** Creates a new instance of MyClass */
public MyClass() {
}

public static void main(String[] args) {
final int i = 100;//#1
byte b = i;
System.out.println("b:"+b);
}
}

it run correctly.
but if you replace #1 to int i = 100;
it can't compile.
what's the reason?
 
Sekhar Kadiyala
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Buddy,
Whenever you are assigning a high storage variable to a low storage variable, you need to type cast. In this case, int occupies 32 bits and byte occupies only 8 bits. Hence

When you have


it won't compile. It will compile if you say


However, when you qualify a variable with final modifier, it will work because, now i is considered as a constant. This is as good as saying



Whenever, we assign constatns/literal, Compiler takes care of the type casting which is called internal type casting as long as that literal is within the range of the type.

Hope this helps
 
Storm Zcm
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sekhar Kadiyala
Thanks for answer. I get it.
 
raghu dubey
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sekhar,


When you say "However, when you qualify a variable with final modifier, it will work because, now i is considered as a constant. This is as good as saying
"

I am aware that constant means static and final. But no just final. I could be wrong but can you please explain.

Thanks,
Raghu.
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Raghu,

Java's notion of compile-time constants is not limited to static final class variables. Other final variables (including local variables and instance variables) can be considered compile-time constants too. Their key characteristic is that they must be initialized with what the Java Language Specification calls a "compile-time constant expression":

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5313

In fact, even a static final class variable won't be considered a compile-time constant if it's not initialized with a constant expression. Here's an example to illustrate what I mean:

[ October 31, 2007: Message edited by: Kelvin Lim ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic