aspose file tools*
The moose likes Beginning Java and the fly likes Static variables???? 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????" Watch "Static variables????" New topic
Author

Static variables????

Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
class Static
{
static int x=18;
int y=21;
}


class StaticTest
{
public static void main(String[] args)
{
Static s=new Static();
System.out.println("X " +s.x);//If i type only x, i get a compiler error.
System.out.println("X " +s.y);
}
}

Why cant I access the static variable x without an instance of the class StaticTest? Then what is the difference between the variables x,y?
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3775

You should use Static.x in order to use class variable (actually that's the preffered way). But s.x also works but that's also the class variable you are accessing.

Why cant I access the static variable x without an instance of the class StaticTest?


You don't need an instance if you do as above.


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
harilal ithikkat
Ranch Hand

Joined: Oct 06, 2008
Posts: 221
hi dude,
here
x is the static variable and as you said you can access the static variable without making an object.
So how you have to access is
<class-name>.<variblename>

for eg;
Static.x
you can also acces by using object.
...............
DIFFERENCE BETWEEN x and y

when you change the value of y it will rflect only in that instance,but if you change the value of a static variabble,here x it will reflect on every object of Static class
ie





So my point is STATIC VARIABLE WILL BE SHARED BY ALL OBJECT.WHERE AS INSTANCE VARIABLES WILL NOT BE SHARED BETWEEN OBJECTS

HOPE YOUR DOUBT IS CLEAR

[ October 09, 2008: Message edited by: harilal ithikkat ]
[edit]Add code tags. CR[/edit]
[ October 09, 2008: Message edited by: Campbell Ritchie ]

SCJP 1.5
"A candle looses nothing by lighting another candle"
itechmentors.com
Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
Thanks a lot, I understood!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36514
    
  16
Please, make sure to use indentation and the code button; I have added tags to one post so you can see how much easier it is to read.
And, harilal ithikkat, please don't use ALL CAPITAL letters unless it's code which has to be upper-case.
 
 
subject: Static variables????
 
Similar Threads
Static vriables and Methods
Static Variables
Static Modifier
static block
this!!