r/javahelp • • May 12 '19

Solved Why does x equal 40 after the code executes?

int x = 10;

for (int y = 5; y < 20; y +=5)

x += y;

0 Upvotes

5 comments sorted by

1

u/MrTemotion May 12 '19

oh right... i get it now lol

1

u/codingtorinado May 12 '19

Now mark it as solved with the solved flair i think

3

u/shagieIsMe Extreme Brewer May 12 '19

Lets make this actual code... and put some print statements in.

package net.shagie.misc;

public class Twenty {
    public static void main(String[] args) {
        int x = 10;
        System.out.println("x = " + x);
        for (int y = 5; y < 20; y +=5) {
            x += y;
            System.out.println();
            System.out.println("y = " + y);
            System.out.println("x = " + x);
        }
    }
}

and the output:

x = 10

y = 5
x = 15

y = 10
x = 25

y = 15
x = 40

And, well... there's your answer. Just take the code and compile it.

You can also easily do this with an IDE (without needing to print things out) by putting a breakpoint in and stepping through the code. https://i.imgur.com/E6RdzWz.png

Learning how to debug is essential. From How To Be A Programmer

Debugging is the cornerstone of being a programmer. The first meaning of the verb "debug" is to remove errors, but the meaning that really matters is to see into the execution of a program by examining it. A programmer that cannot debug effectively is blind.

2

u/[deleted] May 12 '19

Look at what values you are adding to X.