This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static Instance Variables Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Static Instance Variables" Watch "Static Instance Variables" New topic
Author

Static Instance Variables

RAGU KANNAN
Ranch Hand

Joined: Dec 16, 2005
Posts: 103
Hello,

I read the book for the following statement
�The static instance variables are accessed by static method�
But the below example non- static method accessing statis instance variable (�S�), is it possible to do like this.

13. Given the following,

1. class Test {
2. static int s;
3.
4. public static void main(String [] args) {
5. Test p = new Test();
6. p.start();
7. System.out.println(s);
8. }
9.
10. void start() {
11. int x = 7;
12. twice(x);
13. System.out.print(x + " ");
14. }
15.
16. void twice(int x) {
17. x = x*2;
18. s = x;
19. }
20. }
Padma Lalwani
Ranch Hand

Joined: Nov 02, 2004
Posts: 49
Yes, static variable is accessible by all object instances of the class, think of it as a shared memory between objects of the same class, so static and non-static methods both can access it
Asha Pathik
Ranch Hand

Joined: Feb 08, 2006
Posts: 143
Hi,

void twice(int x) {
x = x*2;
s = x;
}

whenever we access instance variables from inside of a class's method it is accessed using the "this" operator. In case of non-static instance variable this signifies the current object where as in case of static variables this signifies the class for the static variable. Thus, it is possible to access static variable even from non-static context.

Asha


SCJP 1.5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static Instance Variables
 
Similar Threads
passing on values from method to method
Static variable in non static method
confusion with static variable....
possible error in the book
possible error in the book by kathy