swollton
swollton

Reputation: 45

Nested "System.out.print" output

Why does this program:

import java.io.*;

public class testpage
{
    public static void main(String [] args)
    {
        pri();
    }

    public static int p2 (int x)
    {
        System.out.print("p");
        return x * x + 1;
    }

    public static void pri ( )
    {
        int y = 3;
        System.out.print( p2(y) + "-" + p2(y));
    }
}

Output this:

pp10-10

Specifically, why would the output on each side of the - be different when the method calls are the same?

Upvotes: 2

Views: 394

Answers (2)

Karibasappa G C
Karibasappa G C

Reputation: 2732

Its evaluated like below

p2(y) +"-" + p2(y)

p2(y) is called first and that prints p and returned 10.

then "-" will be evaluated but it will be as it is.

then again 2nd p2(y) will be evaluated which gives call again to method which prints p and returned 10.

Note : while evaluating operands return value is no where printed.

after evaluating operands

now whole expression becomes from p2(y) +"-" + p2(y) to

p2(y) -> p
- -> do nothing as its not call to any method
p2(y) ->p

so output comes as p first operand evaluation, p second operand evaluation and then p2(y) -> returned value substituted while cancatenating.

so output comes as

pp10-10

where pp is printed for operand evaluation and rest is during cancatenation.

any doubts ?

Upvotes: 1

rgettman
rgettman

Reputation: 178263

Java will evaluate the operands of a binary operator such as + before performing the operation. This means that p2(y) will be called twice before the concatenations happen. The 2 method calls each print p before the concatenations, then System.out.print prints 10-10.

The JLS, Section 15.17.2, covers this:

The Java programming language guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed.

Upvotes: 10

Related Questions