-3

How come the output of this program is:

12
300

Can anyone please explain where the 300 part comes from?

Explain calArea1() please.

public class Practice3 {
    int i;
    int j;

    public static int calArea2(Practice3 t) {
        t.i=t.i+10;
        t.j=t.i+20;
        return t.i*t.j;
    }

    public static void main(String[] args) {
        int area = calArea1(3,4);
        System.out.println(area);
        Practice3 t = new Practice3();
        area = calArea2(t);
        System.out.println(area);
    }

    public static int calArea1(int i, int j) {
        return i*j;
    }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
Mohammed Sajjad
  • 35
  • 3
  • 10

2 Answers2

2

t.i and t.j start as 0.

t.i=t.i+10; //t.i = 0 + 10 = 10
t.j=t.i+20; // t.j = 10 + 20 = 30
return t.i*t.j; // t.i * t.j = 10 * 30 = 300
Cameron
  • 434
  • 2
  • 4
2

You made a mistake on the second line here:

t.i=t.i+10;
t.j=t.i+20; // << This should be t.j+20

Since t.i has been set to 10 at the time you add 20 to it, the result is 30, which, when multiplied by 10, gives you 300.

Java offers a convenient operator += to avoid mistakes like that:

t.i += 10;
t.j += 20;

Now the output is going to be 200, matching the value that you expected.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    First time I see someone not answer the op's question as asked but somehow still solve their problem. I'm guessing that's what he was trying to understand. – Neil Jan 29 '16 at 16:21