There are 2 way of doing this:
1) The first one is the simplest possible, just return the length:
int change(int length){
length = 6;
return length;
}
N.B. Java is always pass-by-value!
2) The second one is a bit more tricky:
You have to create a method in order to set and get length
value.
Something like this:
public class FooBar { //This is you class with the length var
private int _length;
public FooBar(){
_length = 0;
}
//Now we are going to create the SET and GET methods
public GetLength(){
return _length;
}
public SetLength(int length){
_length = length;
}
}
Now that your class looks similar to the above one, we can do this:
int change(int length){
SetLength(length);
return something;
}
If you are calling it from another class you should remember to create the object of the class first as the below example:
FooBar foo1 = new FooBar();
//things and things here
int change(int length){
foo1.SetLength(length);
return something;
}
As you can see, the lenght
variable is now private so we need to always use:
Every class in java should work like this, just good habits of programming in java!