Google+

52. Assignment and '?' operator








Program to demonstrate basic assignment operator usage                                                                                                                                                                                                                                      

class AssignmentOperator
{
   public static void main(String args[])
   {
      int a;
      a=5;       //Here we are using assignment operator '=' to assign value '5' to variable 'a'
      System.out.println(a);
   }
 }

Output of this program:

5

Program to demonstrate assignment operator assigning a single value to more than one variable in a single statement

class AssignmentOperator2
{
   public static void main(String args[])
   {
      int a,b,c;
      a=b=c=5;    //Here we are using assignment operator '=' to assign value '5' to variables 'a','b' and 'c' in a single statement
      System.out.println(a);
      System.out.println(b);
      System.out.println(c);

   }
 }

5
5
5

Program to demonstrate '?' operator

class QuestionOperator
{
   public static void main(String args[])
   {
      int i=10;

      int k= i<0 ? -i: i;    // i<0 is true then -i after the question mark will be assigned to variable 'k' else value of i will be assigned

      System.out.println("k="+k);

   }
 }

Output of this program:

k=10

Another Program to demonstrate the '?' operator

class QuestionOperator
{
   public static void main(String args[])
   {
      int i=-10;

      int k= i<0 ? -i: i;     // i<0 is true then -i after the question mark will be assigned to variable 'k' else value of i will be assigned

      System.out.println("k="+k);

   }
 }

Output of this program:

k=10






Please comment below to feedback or ask questions.

Operators precedence topic will be explained in the next post




7 comments:

aarkays said...

Another Program to demonstrate the '?' operator => you mentioned the same Arun.

Arun Motoori said...

@aarkays - No, there is a difference. int i=10; is mentioned in one of the program and int i=-10; i.e. positive integer value is passed to int variable in the first program and negative integer value is passed to int variable in second program.

B Dinesh said...

Hi Arun, as we have passed -10 (negative Value), shouldn't the result be -10?
Please clarify

sujji said...

There is an error in last 2 programs output,both the outputs will be 10? plz clarify.

Arun Motoori said...

@Dinesh and Sujji - Correct output is displayed.

chandan mohanty said...

i did not understand, as in above two program we have assigned value as 10 and -10 . How the output will be same

Arun Motoori said...

@Chandan mohanty -

i=-10

i<0 is -10 < 0 , which is true

When it is true, from ?-i:i; , -i will be picked

-i is -(i) i.e. -(-10) , which is nothing but 10

Hence the output will be 10.