Win a copy of AWS Security this week in the Cloud/Virtualization forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • salvin francis
  • fred rosenberger

assigning boolean to integer.

 
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We get 4 after compiling this program.
I can not understand what is happening on line 1 and the following one. Can some one explain plz.
public class test {
public static void main(String args[]) {
boolean x = true;
int a;
if(x) a = x ? 1: 2;// Line 1
else a = x ? 3: 4;
System.out.println(a);
}
}

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got an output of 1. Since x is true, this executes:
a = x ? 1: 2;
Since x is already true, the first value will have to be assigned to a. Thus, a = 1.
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Originally posted by ZEESHAN AZIZ:
We get 4 after compiling this program.
I can not understand what is happening on line 1 and the following one. Can some one explain plz.
public class test {
public static void main(String args[]) {
boolean x = true;
int a;
if(x) a = x ? 1: 2;// Line 1
else a = x ? 3: 4;
System.out.println(a);
}
}


It equals:
If(x)
{
if (x)
a=1;
else
a=2;
}
else
{
if (x)
a=3;
else
a=4;
}
 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi friends
plz someone explain that why is a=x not assigning the value of x to a.see the code below
boolean x = true;
int a;
if(x) a = x ? 1: 2;// Line 1
else a = x ? 3: 4;
System.out.println(a);
}
}
originaly posted by zeeeshan aziz.
the answer is 4.

 
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi zeeshan..
that is because first the ternary is operator is applied and the following expr is evaluated:
x?1:2
and since x is true it returns 1 which gets assigned to a, hence a=1.. my output also comes out to be 1.
hope this helps..

------------------
Hima
 
You showed up just in time for the waffles! And this tiny ad:
Devious Experiments for a Truly Passive Greenhouse!
https://www.kickstarter.com/projects/paulwheaton/greenhouse-1
    Bookmark Topic Watch Topic
  • New Topic