File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes global and local variable concept Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "global and local variable concept" Watch "global and local variable concept" New topic
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: global and local variable concept
 
Similar Threads
Constants
solving problems
is rectangle?
Dan's questions : static variable
finding the intersection of two lines- for a junit test case