views:

68

answers:

4

Hi,

I am facing a strange problem.

if ( c2==c1){
    c3 *= 2 ; 
    System.out.println( c3 ) ; 
    .....
}

I want to insert c3*2 in the println statment. But

if ( c2==c1){
    System.out.println( c3*2 ) ; 

gives me a different result.

Here is the whole code:

        public static void main(String [] args) {

           int c1 = Integer.parseInt(args[0]) ;
           int c2 = Integer.parseInt(args[1]) ;
           int c3 = Integer.parseInt(args[2]) ;

/*  1 */       if ( c1 != c3 ){
/*  2 */        if (c2==c1){
/*  3 */              
/*  4 */              System.out.println(c3 + c2 ) ; 
/*  5 */              c3 *= c2 ; 
/*  6 */        }

/*  7 */       }else{ 
/*  8 */        if ( c2==c1){
/*  9 */                    c3 *= 2 ; 
/* 10 */                    System.out.println( c3 ) ; 
/* 11 */                    c3 *= c2 ; 
/* 12 */            if ( c1 < c2 ) c2 += 7 ;
/* 13 */                   else c2 += 5 ; 
/* 14 */               }}

/* 15 */       System.out.println( c1+c2+c3) ;     
        }          
        .....
    }

Any ideas?

+7  A: 
c3 *= 2; 
System.out.println( c3 ) ; 

would print the same thing as:

System.out.println( c3 * 2 ) ; 

but the crucial difference is that in the first case the value of the c3 variable will be modified (multiplied by 2) while in the second it will stay the same.

Darin Dimitrov
+3  A: 

It's possible to get different result depending on the type of your variable - remember *= (and also ++, --, etc) casts the result to the same type as c3. For example:

byte b = 100;
System.out.println(b*2); // 200
b*=2;
System.out.println(b); // -56

Example: http://ideone.com/ojKfA

Kobi
+2  A: 

If you do c3 *= 2; it will change the value of c3 which will print a different value from the last line System.out.println( c1+c2+c3);. So you need to follow the logic of your program.

fastcodejava
+1  A: 

If you want to modify variable and print it at the same time you can do it like this:

System.out.println(c3 *= 2);
bancer