Search code examples
javatrace

Tracing through code


I have a question about the result i get when i trace through the code. In the output one of answers is 75, now i understand how all the other answers come to be. I know that int f = quip(b,10);' calls on the method below called quip. In that method you see int x = foo(a,w); and this is where i get lost. Can anyone please explain this to me? -Thanks

public class tracing
{
 public static void main(String[] args)
 {
 int a = 4, b = 5, c = 23;

 int e = foo(c, a);
 int f = quip(b, 10);

 System.out.println(e + ", " + f);
 System.out.println(a + ", " + b);
}
 public static int foo(int x, int y)
 {
 y = x + y;

 System.out.println(x + ", " + y);

 return (x + y);
 }
 public static int quip(int w, int a)
 {
 int x = foo(a, w);

 System.out.println("quip: " + w + a);

 return x * 3;
 }
} 

Output:

23, 27
10, 15
quip: 510
50, 75
4, 5

Solution

  • int f = quip(b, 10); // b = 5
    
    public static int quip(int w, int a) // w = 5, a = 10
    {
        int x = foo(a, w);
    
    public static int foo(int x, int y) // x = 10, y = 5
    {
        y = x + y; // 10 + 5 = 15, after this line y = 15, x = 10
    
        System.out.println(x + ", " + y); // prints 10, 15
    
        return (x + y); // return 25
    }
    

    Back to foo():

        int x = foo(a, w); // after this line x = 25, w = 5
    
        System.out.println("quip: " + w + a); // prints quip: 510
    
        return x * 3; // returns 25 * 3 = 75
    }
    

    Back to main():

    int f = quip(b, 10); // after this line f = 75, e = 50
    
    System.out.println(e + ", " + f); // prints 50, 75