Support Forums

Full Version: [TUT]GLOBAL VARIABLES FOR JAVA!!![TUT]
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Greetings!

For about 3 hours now I have been working on my Jeopardy program with the Netbeans IDE. Once I got the interface all together, I opened up JCreator and pasted the text document GameInformationUploader section of my previous JeopardyUploader test script, then edited the naming of the Category buttons to take titles from my categories array, and saved in JCreator. When I reloaded the script in Netbeans... MASS ERRORS!!! I said "Omigawd!" and checked what the problem was...

What happened is that my arrays were not global. Well, I tried a bunch of different ways to set global variables such as in LSL or C++, but it was no good. After several minutes of failing, like a stubborn man in Walmart who has been roaming the ails looking too long and finally deciding to ask an employee, I Googled it. And I found it. And here is what this entire epic story sums up to.

To set global variables, all you have to do is after you declare your class and your first opening bracket, state your global variables... BUT, when you state your variables, put "public static" in front of them. Example:

Code:
public class GlobalDataStore
{
     public static int globalInt = 0; //<---He's Global! *teehee*
}

And that's it Smile if you already knew this, than congratulations! If you didn't know this before but do now, congratulations to you too!
Try using that static field with a non-static method. ;) It wont work.
Another way is to first create a public field like so,
Code:
public int globalInt = 0; // idk
Make sure you keep public at the beginning or it doesnt work.

Then in the class you want to call it from, you create an object of the other class and call it like this,
Code:
GlobalDataStore gDS; // invokes the GlobalDataStore class

public void someMethod() {
  gDS.globalInt = 1; // calls the variable, and sets it to 1
}

This will work with any non-static methods. But the way one you posted only works with static methods. Understand?
I see, I see, Smile very interesting
It's even a better idea to work with non-static private fields and public getters/setters. This way, the getters and setters provide an easy interface/facade and can help at sanitizing input.
(03-29-2010, 12:08 PM)Qkyrie Wrote: [ -> ]It's even a better idea to work with non-static private fields and public getters/setters. This way, the getters and setters provide an easy interface/facade and can help at sanitizing input.

I agree, and these should be used. However in some simple scenarios they are unneeded.