2

I am trying to assign value to a class variable via a method. However, after the execution comes out of the scope of the method, the variable is still initialized to the default value. How do we accomplish this in Java?

I want to initialize x to 5 by calling the method hello(). I don't want to initialize by using a constructor, or using this. Is it possible?

public class Test {
    int x;
    public void hello(){
        hello(5,x);
    }
    private void hello(int i, int x2) {
        x2 = i;
    }
    public static void main(String args[]){
        Test test = new Test();
        test.hello();
        System.out.println(test.x);
    }
}
1

3 Answers 3

9

When you do

hello(5,x);

and then

private void hello(int i, int x2) {
    x2 = i;
}

it seems like you might be trying to pass the field itself as parameter to the hello method, and when doing x2 = i you meant x2 to refer to the field. This is not possible, since Java only supports pass-by-value. I.e. whenever you give a variable as argument to a method, the value it contains will be passed, not the variable itself.

(Thanks @Tom for pointing out this interpretation of the question in the comments.)

Sign up to request clarification or add additional context in comments.

12 Comments

I don't want to use 'this' either. Is there still a way?
@VisheshSrivastava Change the name of the variable instead. Your problem comes from the fact that your variable name shadows the attribute 's name. And btw, shadowing it is a bad practice.
Yes: remove the useless arguments of the method hello, which are completely ignored. Or at least, don't name arguments the same way as instance fields.
@VisheshSrivastava Yes. Change the name of your input variable to something else, like int in_x or my favorite: int x_
@VisheshSrivastava consider calling the method in your test. You're only calling the constructor.
|
1

The class property x is only visible by using this.x in hello() because you have declared another variable called x in the method's arguments.

Either remove that argument:

private void hello(int i) {
    x = 5;
}

Rename the argument:

private void hello(int i, int y) {
    x = 5;
}

Or use this.x to set the class property:

private void hello(int i, int x) {
    this.x = 5;
}

Comments

0

You can create two methods.

public void setX(int a)//sets the value of x
{
    x=a;
}
public int getX()//return the value of x
{
return x;
}

call setX to set the value of x and getx to return the value x.

Essentially these are called getter and setter and we use them to access private members from outside the class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.