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

non rechable statment?

 
Rishi Wright
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi 'All
here is the code
class Test {
void notReachable() {
int i;
if(false)
i=6;
// System.out.println(i);


}
public static void main(String[] args) {
Test t=new Test();
t.notReachable();
}
}
In the above code false is a boolean constant always equals to false that means the following statement will be never reached ...then why the compiler is not giving any not reachable error?
thnx
rishi
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the Java language spec has a special rule allowing the "if (false)" construct and saying that it doesn't make any code unreachable. The purpose is to easily allow turning debugging booleans on and off.
 
Rishi Wright
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
then how come below code is giving an error???
class Test {
public static void main(String[] args) {
Test t=new Test();
System.out.println(t.notReachable());
}
String notReachable() {
int i;
if(false)
return "String";


}
}
thnx
rishi
 
venu gopal
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rishi,
The method is expecting return statement. Either you must provide else part or include semicolon after if statement, to make compiler happy..

class Test {
public static void main(String[] args) {
Test t=new Test();
System.out.println(t.notReachable());
}
String notReachable() {
int i;
if(false)
return "String";

/*else
return "Str";
*/

}
}
String notReachable() {
int i;
if(false)
/*
; */

return "String";
}
Thanks,
Venu Gopal.
[ August 13, 2003: Message edited by: venu gopal ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic