| Author |
global and local variable concept
|
bhavneet kaur
Ranch Hand
Joined: Apr 08, 2012
Posts: 32
|
|
//its output is :
1
2
why the value of x doesnt changed??
|
 |
Enkita mody
Ranch Hand
Joined: Aug 06, 2012
Posts: 333
|
|
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.
|
OCA7
|
 |
bhavneet kaur
Ranch Hand
Joined: Apr 08, 2012
Posts: 32
|
|
it means if "s" would also be inside main function then it would also not changed
|
 |
Enkita mody
Ranch Hand
Joined: Aug 06, 2012
Posts: 333
|
|
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
Joined: Apr 08, 2012
Posts: 32
|
|
but i have executed it again with s inside main still its giving same output
|
 |
bhavneet kaur
Ranch Hand
Joined: Apr 08, 2012
Posts: 32
|
|
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
Joined: Aug 06, 2012
Posts: 333
|
|
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.
|
 |
 |
|
|
subject: global and local variable concept
|
|
|