Forums Register Login

Static variables and non static methods

+Pie Number of slices to send: Send
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++);
}

}
}
+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
 

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 :
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
thank you guys , i am clear .
No one can make you feel inferior without your consent - Eleanor Roosevelt. tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 38588 times.
Similar Threads
Null pointer
Jbuilder main methods
Question about constructors and inheritance
lil explanation requied ..
Accessing Static Members
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 10:02:48.