Space Ghost
Space Ghost

Reputation: 765

How do I set a value to a variable in a method and print it out in the main method?

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

Answers (5)

Geerten
Geerten

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:

  • Make it a member of the class
  • Create a wrapper object (object references are also passed by value, but you can change the members of that object in a function, just not the object reference itself)
  • Return the value in the function (as mentioned by other answers)

Upvotes: 1

PermGenError
PermGenError

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

Karaaie
Karaaie

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

Mukul Goel
Mukul Goel

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

djakapm
djakapm

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

Related Questions