• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

question on if loop

 
Ranch Hand
Posts: 303
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?


 
Sheriff
Posts: 17652
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The operator should be "==" not "=". The former tests for equality of two values, the latter is the assignment operator.
 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"if()" must evaluate to a boolean value;
simplifying: the statement/condition within '(condition)' must evaluate to boolean.
 
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"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:
 
I would challenge you to a battle of wits, but I see you are unarmed - shakespear. Unarmed tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic