10

I am new to java hence 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 instantiate any object for class Foo, I want to set that static variable foo. which will be used in the class.. How do i do this?

Also, please correct my understanding. value of foo will be same across all the objects, hence it does make sense to declare it as static ? right?

2
  • Just write private static String foo = "MyValue"; Will it differ depending on run-time decisions? Commented Aug 22, 2013 at 21:36
  • You want it to be set to a constant value? Or to change its value sometimes? Is a null value acceptable? Commented Aug 22, 2013 at 21:57

3 Answers 3

8
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 across all objects, static is the right thing to use. If the value is not only static but also never changing, then 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 the capitalization changed there? That's the java convention. "Constants" are NAMED_LIKE_THIS.

Sign up to request clarification or add additional context in comments.

Comments

5
  1. foo will be shared among all instances of Foo
  2. To initialize it:

Option A

private static String foo = "static variable";

Option B

private static String foo;

static {
    foo = "static variable";
}

Option B is seldom used, mostly when there are some inter-dependencies between static variables or potential exceptions.

In either case, static init will happen when the class is loaded.

Comments

2

As stated by the other answers, you should set your initial value like so:

private static String foo = "initial value";

Additionally, if you want to access this variable from anywhere, you need to reference it in a static context, like so:

Foo.foo

where Foo is the class name, and foo is the variable name.

This is actually very useful in understanding the concept of static variables. Rather than referencing foo as a member of some instance of the Foo class, you are referencing foo as a member of the class itself. So, for all instances of Foo, the value of foo will be the same because it is owned by the class and not the instance.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.