-1
package com.test;

public class Callbyvalref {
    int data = 50;
    int x = 10;

    void change(Callbyvalref call) {
        call.data = call.data + 500;
    }

    void nochange(int x) {
        x = x + 25;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Callbyvalref call = new Callbyvalref();
        call.change(call);
        System.out.println("Call By reference: " + call.data);
        call.nochange(500);
        System.out.println("Call By Value: " + call.x);
    }

}

Call By reference: 550 Call By Value: 10

When I change

void nochange(int y) {
    x = x + 25;
}

Call By reference: 550 Call By Value: 35

Both times Call.x printing different values.. any one can explain what is the changes happening when argument variable is changed..

ChanGan
  • 4,254
  • 11
  • 74
  • 135
  • 3
    I don't see what you don't understand. And this example is, again, misleading. Java is pass by value and NOT pass by reference... – fge Jan 22 '15 at 07:52
  • java is always pass by value. http://www.thejavageek.com/2013/08/24/pass-by-value-or-pass-by-reference/ – Prasad Kharkar Jan 22 '15 at 08:12

3 Answers3

0

This is basicly happening because Java does provide the information for an object as reference which is passed by value.

i´ll just leave you this article for further investigations.

Is Java "pass-by-reference" or "pass-by-value"?

Community
  • 1
  • 1
SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
0

When you pass a primitive to a method, only the value is copied. The argument is a new local variable that is initialized with the value passed to it, and has no relation to the "original" value. If you modify it, you're just modifying a local variable, and cannot effect the variable used in the method call.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

In above code, in the method

void nochange(int x) {
        x = x + 25;
    }

the local variable in that function is being changed. If you change the above method as below:

void nochange(int x) {
        this.x = x + 25;
    }

OR

void nochange(int y) {
        x = y + 25;
    }

You can see what is happening there.

Rahul
  • 3,479
  • 3
  • 16
  • 28
  • Fine got it.. the variable x in nochange method is local.. i thought it is referring instance variable.. Thanks for the clarification.. – ChanGan Jan 22 '15 at 08:38