4

I'm a little confused about when a variable or a method should be static. I've developed an app with several classes, variables and methods, and very rarely use the keyword static. Yet it works satisfactorily. Could you tell me if I make mistakes and why. Here is a sample of my code:

public class GameActivity extends AppCompatActivity {

public String[] mots = {"AFTERNOON", "AIRPORT","AVENUE","BETWEEN", "BUS", "CAB", "COAST","DAY",
        "DIFFERENCE","DOLLARS","ENGLISH","FRENCH","GOOD","GOODBYE","HOUR","IMPROVE","LATER",
        "LOCAL","MARGARET","NAME","NINE","NUMBER","ONLY","PHONE","PLANE","SAME","SHARE",
        "SIDEWALK","STATES","SUNDAY","THERE","TIME","TWELVE","UNITED","UNIVERSITY","VERY",
        "WEST","WHEN","WOMAN","YOUNG"};

public String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M",
        "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};

public String mysteryWord = "vide";
//public int nombreDeLettres;

public int numeroImage = 1;
public boolean jeuFini = false;
public int lettresDevinees = 0;
public int wins = 0;
public int losses = 0;

public int numberOfMots;
int numeroAuHasard;
public Boolean maLettreAServi = false;
public ArrayList<CharSequence> lettresEssayees = new ArrayList<>();

public Button monBouton;
public TextView monTextView;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    AdView mAdView = (AdView) findViewById(R.id.adView);
    AdRequest request = new AdRequest.Builder()
            .addTestDevice("AC98C820A50B4AD8A2106EDE96FB87D4")  // adds my test phone
            .build();
    mAdView.loadAd(request);

    // une des solutions pour rendre la zone trado scrollable
    TextView myXmlContent = (TextView)findViewById(R.id.zone_trado_scrollable);
    myXmlContent.setMovementMethod(new ScrollingMovementMethod());

    // écouteurs de tous les boutons actifs
    ecouteursDeBoutons();

}


// joue une lettre
public void playLetter(final String letter) {

    Resources res = getResources();
    final int resId = res.getIdentifier(letter, "id", getPackageName());
    monTextView = (TextView) this.findViewById(R.id.zone_trado_scrollable);

    final TextView maLettre = (TextView) this.findViewById(resId);
    maLettre.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (!jeuFini) { // il faut mettre ce test _dans_ le onClick(View v)

                if (!mysteryWord.equalsIgnoreCase("vide")) {

                    if (!lettresEssayees.contains(maLettre.getText())) {
                        // on teste que la lettre n'a pas déjà été essayée

                        maLettreAServi = false;

                        // boucle de test de lettre
                        for (int i = 0; i < mysteryWord.length(); i++) {
                            if (String.valueOf(mysteryWord.charAt(i)).equals(maLettre.getText())) {

                                int j = i + 1; // car dans le layout xml les id des positions commencent à 1

                                //monTextView.append("\nyou correctly found " + maLettre.getText() + " at position " + j);

                                final int resId = getResources().getIdentifier("position" + j, "id", getPackageName());
                                final TextView lettreADeviner = (TextView) GameActivity.this.findViewById(resId);
                                lettreADeviner.setText(maLettre.getText());

                                maLettreAServi = true;

                                lettresDevinees++;
                            }
                        }

                        maLettre.setText(""); // on efface de l'alphabet la lettre essayée

                        lettresEssayees.add(maLettre.getText());
                        // on la met dans l'arraylist lettresEssayees
                        // afin de ne pas la réessayer
                        // noter que java comprend qu'il s'agit d'un caractère et non d'une string


                        // test pour effacer de l'alphabet une lettre qui a servi
                        if (!maLettreAServi) {

                            // incrémenter le pendu
                            numeroImage++;

                            if (numeroImage < 10) {
                                ImageView monImage = (ImageView) findViewById(R.id.imagePendu);
                                final int imageId = getResources().getIdentifier("pendu" + numeroImage, "drawable", getPackageName());
                                monImage.setImageResource(imageId);
                            } else {
                                ImageView monImage = (ImageView) findViewById(R.id.imagePendu);
                                final int imageId = getResources().getIdentifier("pendu10", "drawable", getPackageName());
                                monImage.setImageResource(imageId);

                                jeuFini = true;
                                monTextView.setText(Html.fromHtml("<font color=\"red\">you lost</font>"));
                                monTextView.append("\nthe word was "+mysteryWord);

                                losses++;
                                TextView nombrePertes = (TextView) findViewById(R.id.nr_losses);
                                nombrePertes.setText("" + losses); // pas réussi à utiliser toString(), alors j'utilise cette converstion
                            }
                        }

                        // test qu'on a trouvé le mot mystère
                        if (lettresDevinees == mysteryWord.length()) {
                            jeuFini = true;


                            // randomisation des félicitations
                            Random generator = new Random();
                            int randomIndex = generator.nextInt(3);

                            if(randomIndex == 0){
                            monTextView.setText(Html.fromHtml("<font color=\"blue\">bravo!</font>"));}

                            else if(randomIndex == 1){
                            monTextView.setText(Html.fromHtml("<font color=\"blue\">fantastic!</font>"));}

                            else if (randomIndex == 2) {
                            monTextView.setText(Html.fromHtml("<font color=\"blue\">you won</font>"));}


                            // rappel de ce qu'était le mot à deviner
                            monTextView.append("\nthe word was indeed " + mysteryWord);

                            String son = mysteryWord.toLowerCase()+"1";

                            final int resRaw = getResources().getIdentifier(son, "raw", getPackageName());
                            final MediaPlayer mp = MediaPlayer.create(GameActivity.this, resRaw);
                            mp.start();

                            wins++;
                            TextView nombreGains = (TextView) findViewById(R.id.nr_wins);
                            nombreGains.setText("" + wins); // pas réussi à utiliser toString(), alors j'utilise cette converstion
                        }
                    }

                } else {
                    monTextView.setText("click on Select word first");
                }
            }
        }
    });
}

...

}
Andy
  • 99
  • 1
  • 2
  • 9

6 Answers6

11

The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. if we talk about static variable then we difine it as The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.

The static variable gets memory only once in class area at the time of class loading.

and if we talks about it uses: when you want to share your variable or methods only single copy through out the class without creating different copy, you should use static.

Advantages It makes your program memory efficient (i.e it saves memory).

John smith
  • 1,781
  • 17
  • 27
  • 1
    Your explanation clarifies things. I added "static", as well as "final", wherever appropriate. Thanks – Andy Oct 17 '15 at 06:46
2

A static variable can be accessed directly with its class name, and it will have a single instance.

YourActivity.staticVariableName=something;

It is helpful for accessing a variable from anywhere i the application. But beware it has a lifetime until your whole Application ends. So it consumes that memory for a whole application lifetime. So use it by keeping that in mind.

Hari Krishnan
  • 5,992
  • 9
  • 37
  • 55
2

Generally all constants and variables that are not tied to a class object and are applicable for the entire should be declared static. So looking at your sample code you should declare mots, alphabet as static and final since there is not point of having a separate copy of these for every object of your class.

Also keyword static allows you to access these constants from other classes also by just using the class name GameActivity like GameActivity.mots if you want to use them elsewhere and final keyword assures you that no one can change those.

public final static String[] mots = {"AFTERNOON", "AIRPORT","AVENUE","BETWEEN", "BUS", "CAB", "COAST","DAY",
        "DIFFERENCE","DOLLARS","ENGLISH","FRENCH","GOOD","GOODBYE","HOUR","IMPROVE","LATER",
        "LOCAL","MARGARET","NAME","NINE","NUMBER","ONLY","PHONE","PLANE","SAME","SHARE",
        "SIDEWALK","STATES","SUNDAY","THERE","TIME","TWELVE","UNITED","UNIVERSITY","VERY",
        "WEST","WHEN","WOMAN","YOUNG"};

public final String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M",
        "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
pgiitu
  • 1,671
  • 1
  • 15
  • 23
1

when you want to share your variable or methods only single copy through out the class without creating different copy, you should use static.. and also interface variables are by default static and final. you should go for basic JAVA concepts first if you want to know more

sud
  • 505
  • 1
  • 4
  • 12
1

static variable is basically use when your want to single variable use multiple place in your app. similarly concept of static method. for more informaton follow this link http://www.javatpoint.com/static-keyword-in-java

Binesh Kumar
  • 2,763
  • 1
  • 16
  • 23
1

I just would like to add another point at pgiitu's and Piyush Gupta's answers.

According to the Java docs: If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

Therefore, as pgiitu mentioned mots and alphabet should be declared as static and final. However, by naming convention, you should rename them to MOTS and ALPHABET respectively.

AuroMetal
  • 928
  • 3
  • 14
  • 32