Is it correct to initialize a String as
String value = new String("test");
value of string is assigned in multiple places and if value is null, then default value which is test should be taken, which means if I declare
String value = null;
at some point I have assign a value if in code no value is assigned.
I think you won't be able to change value = null to value= "test" by default. If the string "test" is really important to you, when you are accessing value, do this:
if(value == null){
value = "test";
}
Instead of writing this condition everywhere in the code, what you can do is call a function getStringValue() instead of using value.
String getStringValue(){
if(value == null){
value = "test"
}
return value;
}
This is same as checking the condition as mentioned above but this produces cleaner code and you don't need to write that condition every time.
Variables can't have a default value that is used if you assign them later to null. That doesn't exist.
If you do
String a = "test";
// ...
a = null;
then a will have the value null. If you want to use "test" instead of null, then you have to do it explicitely:
String actualValue = a;
if (actualValue == null) {
actualValue = "test";
}
or simply
String actualValue = a == null ? "test" : a;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With