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

# ++ Operators

Ranch Hand
Posts: 143
• Number of slices to send:
Optional 'thank-you' note:
public class AddOpTest {
public static void main (String arg []){
int i = 4, j=2, k= 1;
k = k++ + -i++ - ++i - j++;

System.out.println("The value of k is " + ++k);
}
}
The value of k is 2
This is really confusing for me ,can anyone explain the sequence of operations.

-Arun

Ranch Hand
Posts: 37
• Number of slices to send:
Optional 'thank-you' note:
it gives me -11, as expected

Arun Pai
Ranch Hand
Posts: 143
• Number of slices to send:
Optional 'thank-you' note:
Hi Jay,
When I compile and run I get -10.
I went through Maha anna's discussion on this.
solution by her method.
int i = 4, j=2, k= 1;
k = k++ + -i++ - ++i - j++;
k= 1(2) -4(5) - (5)6 - 2(3).
postfixes takes the value before increment. prefixes takes value after increment.
so k = 1 - 4 - 6 -2 = -11.
in the print statement k is incremented again with prefix.
System.out.println("The value of k is " + ++k);
so now k = (-11)-10. since prefix's keep value after increment final value of k =-10.
I hope I am correct , pls correct me if I am wrong.

-Arun

Ranch Hand
Posts: 94
• Number of slices to send:
Optional 'thank-you' note:
I tried to compile the program and the O/p was
-10.I guess,it's right.
Pl.explain ,as to how & why it can be 2.(Or rather,where the answer was given as 2).

Arun Pai
Ranch Hand
Posts: 143
• Number of slices to send:
Optional 'thank-you' note:
Hi Geetha,

I picked this from the study notes at levteck.com.
check this

-Arun

Ranch Hand
Posts: 5399
1
• Number of slices to send:
Optional 'thank-you' note:
Hi Arun
Notes might be wrong as when I compile and run then also answer came -10.
AW I am using JDK1.3
Bartendrs/sheriff can someone provide new url for Maha's disscussion on this topic?
this url is not working http://www.javaranch.com/ubb/Forum24/HTML/000775.html
[ April 16, 2002: Message edited by: Ravish Kumar ]

Author & Gold Digger
Posts: 7617
6
• Number of slices to send:
Optional 'thank-you' note:
In fact the address scheme has changed, here is the new address:
https://coderanch.com/t/190825/java-programmer-SCJP/certification/Array

Arun Pai
Ranch Hand
Posts: 143
• Number of slices to send:
Optional 'thank-you' note:
Valentine had posted this earlier from Maha1

Maha2
-Arun

R K Singh
Ranch Hand
Posts: 5399
1
• Number of slices to send:
Optional 'thank-you' note:
Thanks Val

 Consider Paul's rocket mass heater.