1

Code:

public static char f( char c ){

 System.out.print( c++ );
       return c--;
    }

    public static void main(String[] args)
    {
       if( f('j') == 'k' || f('f') == 'f'){
          System.out.println( f('d') );
       }
    }

Can someone please explain to me why this prints "jde"?? Intuitively, I thought it would print "kged".

2
  • As a learning experience, try changing f so that it says System.out.print(++c); and then return --c; to see what happens! Commented Nov 12, 2013 at 8:01
  • Thanks! I wasn't aware of the difference. Commented Nov 12, 2013 at 10:55

3 Answers 3

8

The value of the expression c++ is the value of c BEFORE it gets incremented. And the value of the expression c-- is the value BEFORE it gets decremented.

So in the first call to f in your example, c starts off as 'j'. Then the line System.out.println(c++); prints 'j' and increments c, so that it's now k. On the next line, it returns the new value of c, which is 'k'.

Since the first half of the if condition is true, the second half is not evaluated. We jump straight into the body of the if. But this works the same way as before - it prints 'd' and returns 'e'. The 'e' is then printed.

Sign up to request clarification or add additional context in comments.

Comments

1

c++ is incremented after the System.out.print, so it prints 'j' first.

The second part of the if statement is not evaluated since f('j') returns 'k' as the decrement is applied after the return.

Then d is printed because f('d')' is called which first prints 'd' and then the result of the function 'e'.

If you want to understand why a problem is doing something, especially if it is rather unexpected, it is a good idea to get familiar with a debugger. With that you can step through every instruction, and see the state of your program at every execution step.

As an exercise, write a program which is using those functions, but prints qed (quod erat demonstrandum).

Comments

0

In the if condition is f('j')=='k' which is true and that is why other condition is not being checked. Here f('j') methods prints j and returns 'k' and after returning c is again 'j'. Now in System.out.println(f('d')); f('d') prints d and returns e which is printing in main method. So the output is jde

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.