• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static variables and non static methods

 
sruthi laya
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 151
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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é
Sheriff
Pie
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 :
 
Anoobkumar Padmanabhan
Ranch Hand
Posts: 103
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
sruthi laya
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you guys , i am clear .
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic