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 variables and non static methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Static variables and non static methods " Watch "Static variables and non static methods " New topic

Static variables and non static methods

sruthi laya

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.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();

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?

Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

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
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

Joined: Oct 15, 2008
Posts: 7
thank you guys , i am clear .
I agree. Here's the link:
subject: Static variables and non static methods
It's not a secret anymore!