File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Problem with Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem with "private static"" Watch "Problem with "private static"" New topic

Problem with "private static"

Suresh Rajadurai
Ranch Hand

Joined: Feb 22, 2007
Posts: 58
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.


marc weber

Joined: Aug 31, 2004
Posts: 11343

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 ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
lei feng

Joined: Aug 23, 2007
Posts: 26
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

Joined: Dec 11, 2005
Posts: 47

There is only one way to access static member, and that is classname.static_member_name

Preparing for OCPJWCD 6.
Gavin Tranter
Ranch Hand

Joined: Jan 01, 2007
Posts: 333
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 ]
I agree. Here's the link:
subject: Problem with "private static"
It's not a secret anymore!