Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question on operators

 
Gauri Tilloo
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happens when you try to compile and run the following program?

public class Prog1 {
public static void main(String[] args) {
int k = 1;
int i = ++k + k++ + + k;
System.out.println(i);
}
}

Select the one correct answer.

a)The program will not compile. The compiler will complain about the expression ++k + k++ + + k.

b)The program will compile and will print the value 3 when run.

c)The program will compile and will print the value 4 when run.

d)The program will compile and will print the value 7 when run

Ans-d
I am not able to get that how to resolve last + + k.
I tried to run this program and the output is also 7.
if we evaluate this then...i=2 + 2 + + 3
So does this mean that no matter how many + signs u put it doesnt m,atter & its not gonna affect the output?
 
Nicky Eng
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi...

i think you're right.
no matter how many + signs you have, the output still 7.

check this out:

public class Prog1 {
public static void main(String[] args) {
int k = 1;
int i = ++k + k++ + + + + + k;
System.out.println(i);
}
}

you still get 7 as output.

correct me if i'm wrong. thanks.
[ June 30, 2005: Message edited by: Nicky Eng ]
 
bhavesh bhanushali
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes nick i think you are correct

regards ,
bhavesh
 
Biju Joseph
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you say int x = 6, implicitly it means we assign (+ve) 6 to the variable x.

int x = 6;
int x = +6;
int x = + 6;
int x = + + 6; //All will produce the same result (+ve 6).

int x = -6;
int x = + + - + 6; // (+ve) (+ve) (-ve) (+ve) 6. is negative 6.

But in the below case x will be (+ve 6).
int x = - - 6; // (-ve) (-ve) 6.

The ultimate conclusion is that, we have to do an AND operation across the + - operators. If you put any other operator(*,/), compiler will throw an error back.
 
Gauri Tilloo
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank u all for the replies..this was a real strange thing i came across.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic