Setting a static variable in java

I am new to java, probably a very noob question:

I have a class

public class Foo{ private static String foo; private String bar; public Foo(String bar){ this.bar = bar; } } 

Now, before I create an object for the Foo class, I want to set the static variable foo. to be used in class. How to do it?

Also, please correct my understanding. the foo value will be the same for all objects, so it makes sense to declare it static? is not it?

+7
java
source share
3 answers
 public class Foo{ private static String foo = "initial value"; private String bar; public Foo(String bar){ this.bar = bar; } } 

Since the value will be the same for all objects, static is the right thing. If the value is not only static , but never changes, you should do this instead:

 public class Foo{ private static final String FOO = "initial value"; private String bar; public Foo(String bar){ this.bar = bar; } } 

Notice how capitalization has changed? This is a java convention. "Constants" - NAMED_LIKE_THIS.

+8
source share
  • foo will be used for all instances of foo
  • To initialize it:

Option A

private static String foo = "static variable";

Option B

 private static String foo; static { foo = "static variable"; } 

Option B is rarely used, mainly when there are some interdependencies between static variables or potential exceptions.

In any case, static init will execute when the class loads.

+5
source share

As indicated in other answers, you should set your initial value as follows:

 private static String foo = "initial value"; 

In addition, if you want to access this variable from anywhere, you need to reference it in a static context, for example:

 Foo.foo 

where Foo is the name of the class and Foo is the name of the variable.

This is really very useful for understanding the concept of static variables. Instead of referencing Foo as a member of some instance of the Foo class, you are referring to Foo as a member of the class itself. Thus, for all instances of Foo value of Foo will be the same since it belongs to the class , not an instance .

Inside a Foo class, you can avoid just calling Foo without qualifying it with the class name.

+2
source share

All Articles