Two Laptop Bag
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes need help Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "need help" Watch "need help" New topic
Author

need help

umang bhartia
Ranch Hand

Joined: Sep 29, 2000
Posts: 60
can any one explain me how this prog has been compiled successfully and giving no output. As according to me it should throw an error at line marked with \\*. As u cant assign a value when checking in if condition isn't it?
public class MyIf{
public static void main(String argv[]){
MyIf mi = new MyIf();
}

MyIf(){
boolean b = false;
if(b=false) \\*
{
System.out.println("The value of b is"+b);
}
}
}

mohit joshi
Ranch Hand

Joined: Sep 23, 2000
Posts: 243

The if condition should have a boolean value or variable as parameter. In case of an assignment expression the value is same as the value of the variable on the left side of = .in your case
if(b=false) first false is assigned to b and then the value of expression is evaluated to be false. So you can assign a value while checking the parameter of if condition.
One situation in which expressions in if(expression) are not evaluated is when we are checking if a local variable has been definitely assigned when it is used.
{
int y;
int x=3;
if(x>2){
y = 6;
}
else if (x<=2){
y = 7;
}
System.out.println("y is "+y);
}
will not compile, even if logically it is possible to conclude that y will be definitely assigned by the time it is printed, the compiler doesnot take the trouble of evaluating the expressions in if conditions to crosscheck this.
 
 
subject: need help
 
Threads others viewed
If condition
questions from Marcus Green tutorial
Need help with if/else issue....
Interface and methods and exceptions
Boolean Que
developer file tools