Reputation: 765
public class Shape
{
public static void main(String args[]){
int num = 0;
cng(num);
}
public static void cng(int x){
x = 52;
System.out.println(x);
}
}
As you can see, in the cng
Method I set the value of x to 52 and then print out the value of x.
Then, back in the main method, the cng
method is performed on the num
variable.
What I want to do, however is set the value of 52 to x without the System.out.println(x);
function in my cng
method and print out the value in my main
method. How would I go about doing that?
I tried doing
public static void cng(int x){
x = 52;
}
and then
public static void main(String args[]){
int num = 0;
cng(num);
System.out.println(num);
}
but it only prints out a 0
because num is set to 0. I thought that performing cng
on the num
variable would change it to 52, but it doesn't.
Upvotes: 0
Views: 188
Reputation: 1057
You want to pass the data by reference. This is not possible for primitive values in Java (int, double, boolean, etc).
You have the following options:
Upvotes: 1
Reputation: 46408
make your cng method return an int variable
public static int cng(int num){
num = 52;
return num;
}
In Your Main method, assign the returned variable from cng() method
int num = 0;
num =cng(num);
System.out.println(num);
Or:
you could always, make num as a member static variable,
static int num;
Upvotes: 2
Reputation: 567
The reason for this behaviour is that arguments are passed by value in Java. This implies that it is simply a copy of the variable that you passed to it. Thus the assignment that you do is only local to the method.
Upvotes: 0
Reputation: 8467
read along the comments :
public class Shape
{
public static void main(String args[]){
int num = 0;
num = cng(); //store value returned by cng() in num
System.out.println("num : " +num); // display num
}
public static int cng(){ //change return type to int
return 52;
}
}
Upvotes: 1
Reputation: 175
Try to change your code to this:
public class Shape
{
public static void main(String args[]){
int num = 0;
num = cng(num);
System.out.println(num);
}
public static int cng(int x){
x = 52;
return x;
}
}
Upvotes: 1