Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

if and while

 
Sridhar Padala
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

The below is code working fine

public class Outer {

public static void main(String [] args) {
float x;
if (false) {
x = 3.0f;
System.out.println(x);
} } }

But when I use the same code with while, its giving compile time error

public class Outer {

public static void main(String [] args) {
float x;
while(false) {
x = 3.0f;
System.out.println(x);
} } }

For boolean value=true both are working fine. Please advice
 
Eric Pascarello
author
Rancher
Posts: 15385
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to JiG(B)

Eric
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In general, code that can't possibly execute causes a compile-time error in Java. That's what you're seeing in your "while" example.

However, "if (false)" is a special case. Java allows this, even though the code inside the "if" cannot ever run. See this part of the Java Language Specification and search for "unreachable" for why.
[ August 16, 2007: Message edited by: Peter Chase ]
 
camilo lopes
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
any variable that you to declare inside of a method is local, then before uses-there must inicializar with a value. The code does not compel, why it is not insurance that instruction if or while executes, and you after this instruction it used a local variable that does not have value. It is not guaranteed that x = 3.0f.
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Peter Chase:
In general, code that can't possibly execute causes a compile-time error in Java. That's what you're seeing in your "while" example.

However, "if (false)" is a special case. Java allows this, even though the code inside the "if" cannot ever run.


Thats a good point. Thanks Peter.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by camilo lopes:
any variable that you to declare inside of a method is local, then...


I think that the content of the "if" and of the "while" was not important to this discussion.

The question was why does "if (false)" compile and "while (false)" doesn't. The part of the JLS to which I referred in my previous answer explains that.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic