Data type conversion and Complie time constants

Hi,
I encountered this problem when I was solving Dan Chisholm Certified Java Programmer Mock Exam.

class JSC201 {
static byte m1() {
final char c1 = '\u0001';
return c1; // 1
}
static byte m2(final char c2) {return c2;} // 2
public static void main(String[] args) {
char c3 = '\u0003';
System.out.print(""+m1()+m2(c3)); // 3
}}

The question was which lines generate compile-time error. The ans was only line 2 generates error can somebody explain why only line 2 and not both line 1 and 2.

Thanks in advance
Annu

Annu,

In method m1 final char c1 = '\u0001'; is a compile-time constant i.e. we know the definite value of c1. This value in turn fits in a byte type hence the compiler performs a implicit narrowing cast to make it compatible with the return type of the method m1.

On the other hand, in method m2, although the argument is char, at compile-time we do not know the definite value of c2. It could fit in a byte or not. This is why the compiler expects an explicit cast when returning c2. c2 is not a compile-time constant.

You might want to try final char c1 = 130 in method m1.

Refer to JLS 5.2 Assignment Conversion for further reading, in particular look at the second discussion in the article.

HTH
Ashish Hareet