• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dan's questions : static variable

 
Kristof Camelbeke
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question 1
class GFC404 {
private static int x=1;
static void m1(int x, int y) {x++; y++;}
public static void main (String[] args) {
int y=3; m1(x, y);
System.out.println(x + "," + y);
}}
What is the result of attempting to compile and run the program?
a. Prints: 1,3
b. Prints: 2,3
c. Prints: 1,4
d. Prints: 2,4
e. Run-time error
f. Compile-time error
g. None of the above
Answer is a, I answered b because I thought that the static variable x CAN be changed in the method m1() regardless the fact that only a copy is passed to the method m1. I mean it's a STATIC variable...Can somebody explain me why not ???
 
David Hadiprijanto
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The variable x in method m1 hides the static variable x in class GFC404.
Hope the code below helps to clarify.
 
Kristof Camelbeke
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok David I understand it now... bloody hiding !
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic