aspose file tools*
The moose likes Beginning Java and the fly likes Variable scope Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variable scope" Watch "Variable scope" New topic
Author

Variable scope

Maureen Charlton
Ranch Hand

Joined: Oct 04, 2004
Posts: 218
In a class I have declared a variable at the top.

My understanding is that this variable is then available to all methods within the class.

However in a method at the end of the class I am finding that the variable declared at the top is not available.

Why would this happen? Is my understanding, that a variable declared at the top of a class is available to all methods within the class NOT correct?

Does this mean my understanding is incorrect?
Nick George
Ranch Hand

Joined: Apr 04, 2004
Posts: 815
Is the variable static or non-static? If you do not use the keyword 'static', the variable is only available to particular instances of the object (ones created with the new keyword). If you are attempting to access the variable from a method marked 'static' (i.e. public static void main), you must label the variable at the top 'static' as well.

static int number;
[ November 07, 2004: Message edited by: Nick George ]

I've heard it takes forever to grow a woman from the ground
Jimmy Die
Ranch Hand

Joined: Nov 20, 2003
Posts: 97
Hi,


Make sure that the decleration is outside of constructors and methods, you can initilize them inside constructors and methods but if you declair them then inside you can only use them inside.


ie.

class SomeClass {

public SomeClass() {
int j = 0; /// can only be used inside the constructor

}

}

class NewSomeClass{

int j;

public NewSomeClass{) {
j = 0; // because it was declaired outside the constructor then you can
// use it outside... Variable scope!!!

}

}


Jimmy Die
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Please post the specific code. Trying to summarize often loses important details and we have to guess what the problem is. Even if the cause of the problem isn't obvious to you, it might be obvious to someone here if we can see your actual code.

Be sure to use UBB CODE tags to preserve your formatting. There are buttons below text box where you edit a message that can help with this. If you take the small amount of time to do this, your code will be much more readable and we will be able to help you more easily.

Thanks,

Layne


Java API Documentation
The Java Tutorial
 
Don't get me started about those stupid light bulbs.
 
subject: Variable scope