user2982119
user2982119

Reputation: 13

Need help understanding Java program flow

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".

Upvotes: 1

Views: 119

Answers (3)

Arnav Kumar
Arnav Kumar

Reputation: 17

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

Upvotes: 0

Matthias
Matthias

Reputation: 3592

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).

Upvotes: 1

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79875

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.

Upvotes: 8

Related Questions