Why not just initialize as:
private String myString = "My string";
The easiest way possible.
Answer from Malcolm on Stack OverflowHow do you initialize a String in java? - Stack Overflow
Is declaring a string literal the same as declaring a string object?
java - Why to declare a String (as final) and then use it? - Software Engineering Stack Exchange
Struggling with OOP.
Videos
Why 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.
Create a new String object and assign it your name. Print it out.
Since the question specifically asks for a String object, declaring a string literal would be incorrect?
At runtime, it does not make a difference.
The point is readability - as a member variable, it likely is declared at the beginning of the class' source code, and making it static means it doesn't have to be allocated for each new instance of the class.
Making it final signifies to the reader that the value will not change (to the compiler too, but that's less important here).
This way, there are no "magic values" buried in the implementation, and if a change is desired to the "constant", it only needs to be changed in one place.
This basically mimics what a C programmer would do with a #define.
final fields have many benefits!
Declaring fields as final has valuable documentation benefits for developers who want to use or extend your class - not only does it help explain how the class works, but it enlists the compiler's help in enforcing your design decisions. Unlike with final methods, declaring a final field helps the optimizer make better optimization decisions, because if the compiler knows the field's value will not change, it can safely cache the value in a register. final fields also provide an extra level of safety by having the compiler enforce that a field is read-only.
Don't try to use final as a performance management tool. There are much better, less constraining ways to enhance your program's performance. Use final where it reflects the fundamental semantics of your program: to indicate that classes are intended to be immutable or that fields are intended to be read-only.
Before declare final fields, you should ask yourself: does this field really need to be mutable?