Why not just initialize as:
private String myString = "My string";
The easiest way possible.
Answer from Malcolm on Stack OverflowWhy not just initialize as:
private String myString = "My string";
The easiest way possible.
Well, it really depends on what that variable is and what it's going to do.
Is it a constant? If so, you can initialize it like this:
private final String myString = "foo";
Is it meant to be an instance variable? If so, you should go for something like this:
public MyClass(string myString)
{
this.myString = myString;
}
If it's some kind of optional property, the way you have now might be fine as well. In the end, it really all depends on what you're going to be doing with that variable.
Does it make sense to initialize a string as null instead of as an empty string?
Setting an empty string?
How to initialize (assign) multiple strings to one variable?
How come we don't use the new keyword to instantiate a String in Java?
Videos
I was using IntelliJ and it said that a string needed to be initialized in order for the program to work. It suggests I initialize it this way
String example = null;
instead of
String example = "";
Do you agree with this? I've found conflicting information as to whether or not this is a good idea.