Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String Initialization and Default Value

Tags:

java

string

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.

like image 398
Jacob Avatar asked Jun 08 '26 07:06

Jacob


2 Answers

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.

like image 105
Karthik Avatar answered Jun 10 '26 06:06

Karthik


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;
like image 42
JB Nizet Avatar answered Jun 10 '26 05:06

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!