This Java code:
public class XYZ {
public static void main(){
int toyNumber = 5;
XYZ temp = new XYZ();
temp.play(toyNumber);
System.out.println("Toy number in main " + toyNumber);
}
void play(int toyNumber){
System.out.println("Toy number in play " + toyNumber);
toyNumber++;
System.out.println("Toy number in play after increement " + toyNumber);
}
}
will output this:
Toy number in play 5 Toy number in play after increement 6 Toy number in main 5
In C++ I can pass the toyNumber
variable as pass by reference to avoid shadowing i.e. creating a copy of the same variable as below:
void main(){
int toyNumber = 5;
play(toyNumber);
cout << "Toy number in main " << toyNumber << endl;
}
void play(int &toyNumber){
cout << "Toy number in play " << toyNumber << endl;
toyNumber++;
cout << "Toy number in play after increement " << toyNumber << endl;
}
and the C++ output will be this:
Toy number in play 5 Toy number in play after increement 6 Toy number in main 6
My question is - What's the equivalent code in Java to get the same output as the C++ code, given that Java is pass by value rather than pass by reference?
toyNumber
variable declared in themain
method is not in scope in theplay
method. Shadowing in C++ and Java only happens when there is nesting of scopes. See en.wikipedia.org/wiki/Variable_shadowing.