Click here to Skip to main content
15,884,986 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Output for the below code is:
e
0

1. I kind know the output 'e' is the 2nd character of 'Hello', but which 'System.out.println' executed that output?

2. I don't understand how could it get the 2nd output '0'? The sequence of the output seems not right.



C#
public class MyProgram
{
    public void start()
    {
        int x = 0;
        String welcome = "Hello";
        myMethod(x, welcome);

        System.out.println(x);
    }

    private void myMethod(int x, String s)
    {
        x = x + 1;

        System.out.println(s.charAt(x));

    }
}
Posted

1 solution

The line x = x + 1; is changing the value of a local variable x of the method myMethod, which is not changing the value of x declared in the method start().
That's why the System.out.println(x) is returning 0.


So, what's happening is this:
myMethos(x, welcome) is incrementing a local variable, which is used to read the character at index 1 of the "Hello", so, the e character.

Then, after the my method, the x from start (which is still 0) is printed.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 7-Jul-14 18:02pm    
My 5, just for understanding what looked complete gibberish to me. To depth of the OP's misconceptions is incredible.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900