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

simple question

 
rahul mehra
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi ,

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
}}


i understand why i'm getting the error on line no 2 cause the found return value is character and the return type is byte


but shouldn't i get the complile time error at line 1 also cause it is also
returning the character value even though the return type is byte....
[ September 05, 2007: Message edited by: deeksha mehra ]
 
pras
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi deeksha..

you are right. you should get a compiler error there also
 
greg buela
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, line 1 compiles fine. The variable is char but it is a final that is assigned a literal, so it is resolved at compile time. Java knows that the return value cannot be any other than \u0001, or 1. And so it knows that it fits a byte.
Change that value to \u0101 and you will see it won't compile, because it knows the return value doesn't fit a byte.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic