There are many mistakes in your code ,you have written here .... this one serves your purpose. yes you are right you can change global variable from anywhere in the class... because its has the class scope ____________________________
class CheckA { public int y = 0; CheckA() { y = 1 ; System.out.println("before:"+y); change('i'); System.out.println("after:"+y); } public void change(int ch){ if(ch>0){ ch *= (-1); y = ch; } }
public static void main(String args[]) { new CheckA(); } }
Some of your methods have a parameter named "count". This parameter hides the instance variable of the same name. While this is legal, it is poor style,and likely to cause exactly the kind of confusion you are encountering here. [ October 26, 2002: Message edited by: Ron Newman ]
Ron Newman - SCJP 1.2 (100%, 7 August 2002)
bharat nagpal
Ranch Hand
Joined: Oct 26, 2002
Posts: 76
posted
0
in the method test test(int count)... The variable count will be local to the method "test", and hide the instance variable . if you want to change the value of instance variable here, either dont name this local variable as "count", or use "this.count" for global variable.
bhart1, Welcome to JavaRanch! We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy. Thanks Pardner! Hope to see you 'round the Ranch!
Check out this: In this case x is a local variable which cannot be changed by „change(int ch)“ because change() only changes a copy of the passed parameter. Change is only visible inside chang(int ch) method and not outside. If x would be an instance or class variable (static) then change(int ch) would change The value of x and this change would be visible outside of method change because There is a REFERENCE to an instance or to a class!!!
C:\Java\EigeneJavaProgramme>java CheckA20a Before change: x in main() = 3 x in change = 99 After change: x in main() = 3
Hi, I think you might need to review these concepts. 1. member variable (or instance variable) These are the variables your declare without 'static'. They can only be referred after you create a new instance. In your main() code, you need to new A(), then call A.y=1; Otherwise, compiler throws error. 2. global variable (or class variable) If you want to define global variable, you need to use 'static', public class A{ public static int y; ... Now you can call y from anywhere. y cab be referred with or without any instance of A. There is only one copy of y for all instances (if any). Cindy
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.