aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes how about this test? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "how about this test?" Watch "how about this test?" New topic
Author

how about this test?

Storm Zcm
Greenhorn

Joined: Jul 08, 2007
Posts: 10
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

Joined: Feb 17, 2004
Posts: 170
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


PMP CSQA SCJP SCWCD SCBCD INS 21 INS 23
Storm Zcm
Greenhorn

Joined: Jul 08, 2007
Posts: 10
Sekhar Kadiyala
Thanks for answer. I get it.
raghu dubey
Ranch Hand

Joined: Jul 05, 2007
Posts: 72
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.


Thanks,<br />Raghu.<br /> <br />SCJP 5, SCWCD 1.4, NCFM
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
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 ]

SCJP 5.0
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: how about this test?