parameters by value.
is used when required to pass the value of a variable to a function and that is performing some operation on this value, function or method creates a local variable and worked on it.
int a = 5;
method (a):
void method (int c) {System.out.println
(c);}
The variable c is a local variable that receives a copy of the value of the variable, ie the parameter is passed by value.
Step by reference.
Passing by reference instead of sending the value of the variable, it sends the memory address which is stored in this way to modify the contents of the variable. However, this type of passing parameters in Java does not exist but if you would like to do in C + + look like this:
include
using namespace std;
void function (int & a) {
a = 10;
}
int main () {int
var = 5;
function (& var);
court <<>
}
The outturn would be 10 and the variable 10 is passed by reference, the function modifies its value.
Now back to the important parameters How does Java? In java there is only one way to do it and over PARAMETER worth, here 's an example of this:
public static void main (String [] args) {
int a = 20;
method (a);
System.out.println (a);
}
public static void method (int c) {
c = 10;
}
}
The value of the variable is always the same. Now an example using objects, in this case will use an array, since by definition arrays are objects:
public static void main (String [] args) {
int [] a = new int [1] / / declare an array of position;
method (a);
System.out.println (a [0]);
}
public static void method (int [] c) {
c [0] = 10;}
}
But it happened! Why the value changed my order? In fact this happens for the simple reason that Java variables pointing to objects, not the object but a reference to it, ie when we do this in Java:
int [] a = new int [1];
We are creating a reference to and that's how to handle the data type referenced is an array of int and also right there with the new operator is created object, and therefore the variable will refer to the memory location of that object.
So when the method receives a reference and adjust, we are modifying the value of the object, but beware, this does not mean that Java passes parameters by reference, it passes the value of
REFERENCE If Java pass by reference values \u200b\u200bwhen we do this:
public static void main (String [] args) {String
a = "Hello";
method (a) ;
System.out.println (a);
}
public static void method (String c) {
c = "New Object";}
}
The result should be "New Object" However this does not happen for the simple reason that Java passes parameters by value only
hope with this is a bit more clear how it happens Java parameters
0 comments:
Post a Comment