简体   繁体   中英

Java String Initialization and Default Value

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 want a string not to be null, you can simply check the value before assigning it.

String value = valueCommingFromSomewhere;
if (value == null) {
    value = "myDefaultValue";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM