does variable assigned to another variable changes( original variable changes ) does the second variable change?

Viewed 430

I made this code to calculate x^y without using math class, I used a variable m which I put equal to x. When x changes its value in the loop, does the value of m also changes as it is equal to x or remains the same to initial x?

package loops;

import java.util.Scanner;

public class XToPowerY {

/**
 * @param args
 */
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int x = sc.nextInt();
    int y = sc.nextInt();
    int m = x;

    for (int i = 0; i <= y - 2; i++) {
        x = x * m;

    }
    System.out.println(x);
}

}

2 Answers

m stays at the initial value of x. It would change, if you would include m = x; in your for-loop. Remember however, that Java only behaves this way with primitives.

Using a debugger helps in your case / answers your question with a few clicks.

m keeps it value, since you store only the value of x not the reference.

Related