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 Static int Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Static int" Watch "Static int" New topic

Static int

Alpana Singh
Ranch Hand

Joined: Sep 27, 2005
Posts: 36
I was running this prg:
public class strtest{
private static int a;
public static void main(String args[]){

int k=modify (a);

public static int modify(int a){
return a;

It prints 0.Shouldn't be the output 1.My thinking is that "a" is a static int.So it retains tha changed value.

Please help
Seb Mathe
Ranch Hand

Joined: Sep 28, 2005
Posts: 225
What do you think about changing method modify with :

public static int modify(int i){
return i;

Remember : in Java methods, arguments are passed by value...

Regards,<br />Seb<br /> <br />SCJP 1.4
Pradeep Kadambar
Ranch Hand

Joined: Oct 18, 2004
Posts: 148
Hi alpana,

The very basic thing you missed out probably. In the methods scope the value of 'a' will be that of the arguement 'a' passed to it, which will overshadow the class variable 'a'. If you change the parameter name for the method you will see the value of a as you have thought off.

public class StrTest {
private static int a;

public static void main(String args[]) {

int k = modify(a);

public static int modify(int b) {
return a;

Timothy Toe
Ranch Hand

Joined: Oct 19, 2002
Posts: 156
My thinking is that "a" is a static int.So it retains tha changed value.

Why should/would a static variable retain its value ?
Do not confuse "static" with "final". Final will retain a variable's value, but not static.
Static means there is only 1 copy for all instances of the class. If there are 100 instances of your class, there will be only 1 instance of variable a. Of course, just like all other non-final variables, static variables are free to have their values changed.

Other things to note :
when a is passed into method "modify", a copy of a is passed (pass by value). The class wide static int a is not changed. That's why it remained as "0".

Seb Mathe's "in Java methods, arguments are passed by value..." is wrong. Primitives (eg int, double, char) are passed by value. Objects and arrays are passed by reference.

[ September 30, 2005: Message edited by: Timothy Toh ]
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
So, to summarize, there are two variables named "a". Which one was modified?


Java API Documentation
The Java Tutorial
S Thanigaivel
Ranch Hand

Joined: Oct 06, 2005
Posts: 60
There are two varialbles with name 'a'
1. static int a
2. int a - local variable

you r incrementing the value of local variable 'a'

and printing the value of static variable 'a' which was not initialized by you and so it takes the default value 0
I agree. Here's the link:
subject: Static int
It's not a secret anymore!