English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

i know Java only uses pass-by-value, but could it be possible to execute a pass-by-reference in Java? Could you share with me how it works?

2007-08-07 15:42:22 · 5 answers · asked by xtianonil 2 in Computers & Internet Programming & Design

5 answers

Primitive types in Java are pass-by-value (int, float, char, etc.). Everything else is pass-by-reference, sort of.

For example, this class changes an int array which is passed by reference, and will print "99" (changed value) rather than "30" (initial value).

================
public class MyClass {
public static void main(String[] args) {
int v[] = new int[] { 30 };
modify(v);
System.out.println("" + v[0]);
}

static void modify(int[] myArray) {
myArray[0] = 99;
} }

================
Now, if you had written modify() as:
myArray = new int[] { 99 };
... then it wouldn't have changed v, since a reference to the array v points to is passed in, but not the address of the original variable v that points to the array.

If you wanted to change the array, you'd have to make a class that contains an array, and pass an instance of the class in. Then if you changed the array reference in the instance passed in, the caller would see that change as well.

2007-08-07 16:01:29 · answer #1 · answered by McFate 7 · 0 0

No, Java does pass-by-reference, whether its by-value or by-reference is strict and dependent on the fact the variable in question is a primitive type or class object.

Don't take a String as example, it is by design to be immutable and generates modified copies of itself with those UPPERCASE lowercase Trim replace methods within itself.

2007-08-07 16:42:35 · answer #2 · answered by Andy T 7 · 0 0

Perhaps what you are looking for is a reference to the problem of whether Java passes by reference or value.

This is tricky, and I had to look this up myself.

2007-08-07 16:42:08 · answer #3 · answered by Nick K 1 · 0 0

pass by value
***************************
pass by value means passing a copy of the value as an argument.

This is simple enough, however there is an important but simple principle at work here. If a variable is passed, the method receives a copy of the variable's value. The value of the original variable cannot be changed within the method. This seems reasonable because the method only has a copy of the value; it does not have access to the original variable. This process is called pass by value.

the following code shows that assigning primitive data variable i to another named j simply passes a copy of the value in i into j. That is, a data value passes and not a reference or pointer to a data location. here i has value 1 and j has value i which is again 1


int i = 1;
int j = i; // Now j holds "1"
// that is, i's value passes to j
i = 2; // j still holds "1"


Similarly, in method arguments, primitive variables pass by value. That is, a copy is made and passed to the method. Changes to the passed value do not affect the variable in the calling code.

The following shows code on top that creates an instance of AClass and invokes the aMethod with an int argument. The code on the bottom shows the AClass definition and
the aMethod.

class AClass {


int j = 1;

void aMethod (int k)
{
int i = 10 * k;
k = 5;
j = k * 10;
}
}


class BClass{
public static void main(String args[]) {

int i = 2;
AClass a1 = new AClass ();

a1.aMethod (i); \\ pass by value

int m = i; // m = i = 2 not 5
System.out.println("Value of 'i' : " + i);
System.out.println("Value of 'm' : " + m);

}
}



The value in variable i in the code on the top will be passed to variable k in the aMethod argument list shown in the AClass code in the bottom box. When that method assigns a value of 5 to k, it has no affect whatsoever on variable i the code on the top.

========================================================================


// This program uses a parameterized method.
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
// sets dimensions of box
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
}
class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// initialize each box
mybox1.setDim(10, 20, 15); // pass by value
mybox2.setDim(3, 6, 9);
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
============================================================


pass by Reference
**********************
Pass by Reference means the passing the address itself
However, if the variable passed is an object, then the effect is different. We often say things like, "this method returns an object ...", or "this method is passed an object as an argument ..." But this is not quite true, more precisely, we should say, something like "this method returns a reference to an object ..." or "this method is passed a reference to an object as an argument ..."

Generally, objects are never passed to methods or returned by methods. It is always "a reference to an object" that is passed or returned.


In general, pass by value refers to passing a constant or a variable holding a primitive data type to a method, and pass by reference refers to passing an object variable to a method. In both cases a copy of the variable is passed to the method. It is a copy of the "value" for a primitive data type variable; it is a copy of the "reference" for an object variable. So, a method receiving an object variable as an argument receives a copy of the reference to the original object.


If the method uses that reference to make changes to the object, then the original object is changed. This is reasonable because both the original reference and the copy of the reference "refer to" to same thing — the original object. There is one exception: strings. Since String objects are immutable in Java, a method that is passed a reference to a String object cannot change the original object.



To understand pass by reference lets see the sample program below:

public class TestPassByReference {
public static void main(String[] args) {
// declare and initialize variables and objects
int i = 25;
String s = "Java is fun!";
StringBuffer sb = new StringBuffer("Hello, world");

// print variable i and objects s and sb
System.out.println(i); // print it (1)
System.out.println(s); // print it (2)
System.out.println(sb); // print it (3)

// attempt to change i, s, and sb using methods
iMethod(i);
sMethod(s);
sbMethod(sb);

// print variable i and objects s and sb (again)
System.out.println(i); // print it (7)
System.out.println(s); // print it (8)
System.out.println(sb); // print it (9)

}

public static void iMethod(int iTest) {
iTest = 9; // change it
System.out.println(iTest); // print it (4)
return;
}

public static void sMethod(String sTest) {
sTest = sTest.substring(8, 11); // change it
System.out.println(sTest); // print it (5)
return;
}

public static void sbMethod(StringBuffer sbTest) {
sbTest = sbTest.insert(7, "Java "); // change it
System.out.println(sbTest); // print it (6)
return;
}
}

Output of the program :

25
Java is fun!
Hello, world
9
fun
Hello, Java world
25
Java is fun!
Hello, Java world


TestPassByReference begins by declaring and initializing three variables: an int variable named i, a String object variable named s, and a StringBuffer object variable named sb. The values are then printed. Then, each variable is passed as an argument to a method. Within each method, the copy of the variable exists as a local variable. The value of the variable — or the value of the object referred to by the variable, in the case of the String and StringBuffer object variables — is changed and printed within each method. The print statements are numbered to show the order of printing. Back in the main() method, the three values are printed again. Have a look at the output and see if it is consistent with our previous discussion.

The pass-by-reference concept is illustrated by the object variables sb and sbTest. In the main() method, a StringBuffer object is instantiated and initialized with "Hello, world" and a reference to it is assigned to the StringBuffer object variable sb.

2007-08-07 19:31:27 · answer #4 · answered by angel04 3 · 1 0

Check this..

http://radio.javaranch.com/val/2004/05/21/1085125887000.html

2007-08-07 16:33:15 · answer #5 · answered by marleymang 2 · 0 0

fedest.com, questions and answers