• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static variables????

 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
harilal ithikkat
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot, I understood!
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic