This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes question on if loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "question on if loop" Watch "question on if loop" New topic
Author

question on if loop

JayaSiji Gopal
Ranch Hand

Joined: Sep 27, 2004
Posts: 303
class test {

static boolean check;

public static void main(String args[]) {

int i;

if(check == true)

i=1;

else

i=2;



if(i=2) i=i+2;

else i = i + 4;

System.out.println(i);

}

}




3
4
5
6
The program does not compile because of the statement if(i=2)

i answered 4,but the correct ans is the last option.

i have come across eg, where there is a variable assignment in the if loop. one of the major questions which r a little tricky.
in this eg, also, the variable is assigned 2 which now returns true and hence i answered 4.

anybody plz explain?




SCJP 1.4, SCWCD 1.4<br /> <br />Thanks in advance!<br />Jayashree.
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4474
    
    6

The operator should be "==" not "=". The former tests for equality of two values, the latter is the assignment operator.


Junilu - [How to Ask Questions] [How to Answer Questions]
navneet shrivastava
Ranch Hand

Joined: Jul 09, 2004
Posts: 39
"if()" must evaluate to a boolean value;
simplifying: the statement/condition within '(condition)' must evaluate to boolean.


+nav
Joe Borderi
Ranch Hand

Joined: Oct 23, 2004
Posts: 151
"i have come across eg, where there is a variable assignment in the if loop."

A variable assignment will work in a loop or if condition if the variable assingments evaluate to a boolean:
 
GeeCON Prague 2014
 
subject: question on if loop