aspose file tools*
The moose likes Beginning Java and the fly likes Static variables and non static methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Static variables and non static methods " Watch "Static variables and non static methods " New topic
Author

Static variables and non static methods

sruthi laya
Greenhorn

Joined: Oct 15, 2008
Posts: 7
Hi ,

I have written a program in which i am trying to understand the static concepts .

I have a doubt , can i access a static variable in a non static method.

because when i am doing that it is executing properly ...
please check the below

import java.io.*;
import java.lang.*;

public class StaticExample{


private static int cal=1;
private static int count = 0;


static void method1(){
System.out.println(" The cal value is " + cal);
}

void method2(){
System.out.println( count);
}

public static void main (String [] args){
StaticExample ex = new StaticExample();
ex.method1();
ex.method2();
while(count<10){
System.out.println(count++);
}

}
}
rakesh sugirtharaj
Ranch Hand

Joined: Dec 16, 2007
Posts: 151
Yes! Calling a static from a non-static method is allowed but not the reverse. When a member is static it is like it is common to all instances of that class. So it should be accessible by non static methods. But a non static member, belongs to one specific instance(object) of the class and hence cannot be directly invoked without creating an instance. Does that make sense?


Cheers!
RSR
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

can i access a static variable in a non static method.

Yes you can. Imagine that this static variable will be the same for all instances of that class, so any instance can access it. What you can also try is :


[My Blog]
All roads lead to JavaRanch
Anoobkumar Padmanabhan
Ranch Hand

Joined: Aug 08, 2007
Posts: 103
Yes.
You can access the static variables from nonstatic methods. The difference between static and non-static variables is that the static variables are common to the class. ie, the same copy of the static data will be available for all the instances of that class.

in the reverse case, for accessing non-static data from a static method, we should use some object. that is also the same reason... non static data are object specific. ie, they are available within a class instance only.


Thanks<br /> <br />Anoobkumar<br />SCJP 1.5
sruthi laya
Greenhorn

Joined: Oct 15, 2008
Posts: 7
thank you guys , i am clear .
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static variables and non static methods
 
Similar Threads
Accessing Static Members
lil explanation requied ..
Jbuilder main methods
Null pointer
Question about constructors and inheritance