Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

global and local variable concept

 
bhavneet kaur
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


//its output is :
1
2
why the value of x doesnt changed??
 
Enkita mody
Ranch Hand
Posts: 333
Firefox Browser Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
bhavneet kaur wrote:
class C1
{

static int s;

public static void main(String a[])
{

C1 obj=new C1();
obj.m1();
System.out.println(s);
}

void m1()
{
int x=1;
m2(x);
System.out.println(x+"");
}

void m2(int x)
{
x=x*2;
s=x;

}
}

//its output is :
1
2
why the value of x doesnt changed??

Enkita mody
Ranch Hand

Joined: Aug 06, 2012
Posts: 294

I like...



x is a method local variable of m1.it doesn't belongs to m2 method.m2 has its own another x.
 
bhavneet kaur
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

it means if "s" would also be inside main function then it would also not changed
 
Enkita mody
Ranch Hand
Posts: 333
Firefox Browser Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
bhavneet kaur wrote:
it means if "s" would also be inside main function then it would also not changed


s is a static variable, you can't declare it in static method main.
 
bhavneet kaur
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

but i have executed it again with s inside main still its giving same output
 
bhavneet kaur
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

why so i have declared it inside main as int s; so it becomes static because it is now declared inside static main method
 
Enkita mody
Ranch Hand
Posts: 333
Firefox Browser Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
bhavneet kaur wrote:
why so i have declared it inside main as int s; so it becomes static because it is now declared inside static main method


No,int s is not a static variable until you write static int s.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic