-1
    static void number(int x){
        x=42;
    }


 public static void main(String[] args) {

    int x =17;
    number(x);
    System.out.println(x);

why is the value printed out still 17 and not 42? Thanks!

bri
  • 1
  • 1

2 Answers2

1

The line

number(x);

passes the value of x into number. Nothing that links back to x is passed at all. Inside number, the x argument you've declared is not in any way linked to the x variable in main; it just receives the value that you passed into number. Assigning to the argument (x = 42) just changes the value of the argument, not the variable in main.

This is called pass-by-value, meaning that whenever you pass a variable into a method, the value of that variable is passed, not anything about the variable itself. Exactly the same thing happens here:

x = 17;
y = x;
y = 42;
System.out.println(x); // 17
System.out.println(y); // 42

y = x just takes the value of x and puts it in y. There's no ongoing link between x and y.

So how would you change it? The usual approach is have number return a new value:

int number(int val) {
    return val * 2;
}

Then in main:

x = 17;
x = number(x);
System.out.println(x); // 43

Sometimes, people get confused by pass-by-value when it involves object references. Variables directly contain primitives like int, but they don't directly contain objects; they contain object references. So consider:

List<String> l1 = new LinkedList<String>();

Now, l1 contains a value that is a reference to the linked list object. Now suppose we do this:

List<String> l2 = l1;

What happened there? Do we have one list, or two?

The answer is, of course, one: The value we copied from l1 to l2 is the reference to the list, which exists elsewhere in memory.

Key points in summary:

  • When you pass a "variable" into a method, it's the value of the variable that gets passed (always — Java is purely pass-by-value [some other languages have something called pass-by-reference, where a reference to the variable is passed, but Java doesn't have that)
  • The same thing happens when you assign a variable to another variable
  • Object references are values that tell the JVM where the object is in memory
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Java is pass by value So when you passes x which is defined in main() to number() method ,only the value is copied to function parameter x and no address is passed unlike C pointers.So the value you get is 17 because it is not changed.

singhakash
  • 7,891
  • 6
  • 31
  • 65