Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with "private static"

 
Suresh Rajadurai
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gurus,

I have a problem with the following code:

01. public class test01
02. {
03. private static int a=0;
04. public static void main(String [] args)
05. {
06. modify(a);
07. System.out.println(a);
08. }
09. public static void modify(int a)
10. {
11. a++;
12. }
13. }

I understand that a static variable will have ONLY ONE copy throughout the program. But here when I executed the program it prints 0(zero). But it has to be 1 at line # 11 following modify(a) at line # 6. Can anybody explain this please.

Thanks in advance.

Regards

Suresh.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you pass a parameter to a method, you are only passing a copy of the value, and this copy is assigned to a variable that is local to the method.

In this example, there is a static variable called 'a', but there is also a variable 'a' that is local to the method modify(int a). So within the body of modify, when you call a++, you are incrementing the value of the local variable. The static variable remains unchanged.

If you wanted to increment the static 'a', then you would use the class name and call test01.a++.

Note: When we say that a static variable will "only have one copy," that means there is only a single variable associated with the class, instead of having a distinct variable associated with each instance. However, that does not mean that the value cannot be copied.
[ August 26, 2007: Message edited by: marc weber ]
 
lei feng
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
agree up, there are two 'a' one is the static another is the int a as a parameter,so you'd better remove the int a in the program.
 
Saurabh Patil
Ranch Hand
Posts: 48
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is only one way to access static member, and that is classname.static_member_name
 
Gavin Tranter
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Saurabh Patil:
There is only one way to access static member, and that is classname.static_member_name


I am pretty sure you an access a static member from an object reference too!



are something like that.
[ August 29, 2007: Message edited by: Gavin Tranter ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic