How do you initialize a string in java?

I decided to use setters instead of inserting arguments into the default constructor, because it helps me better organize the code

The problem is that the only variable in the project that I am doing is String, and I'm not sure whether it should be initialized in the declaration (as a global variable?), In the setter instance method, or initialized in the class constructor.

I am wondering if there might be something problematic in this setting, whether the instance will not be initialized until its setter is used:

class MyClass{

  private String myString; 

  public MyClass(){

  }
  public void setStuff(String s){ 

    this.myString=s;
  }
}
+5
source share
5 answers

, ? , , ? ,

private static String myString = "str";

,

public static final String MY_STRING = "str";

MyClass.MY_STRING

, ,

+1

:

private String myString = "My string";

.

+7

, , .

? , :

private final String myString = "foo";

? , - :

public MyClass(string myString)
{
    this.myString = myString;
}

- , , , . , , .

+3

, , . BTW, " " , , var , , getter/setter.

String :

private String foo = "some string";
+1

, MyClass. , , .

, MyClass foo, myString, setStuff?

0

All Articles