#Difference between manually creating a new instance of String and directly initializing a variable

1 messages · Page 1 of 1 (latest)

regal kernel
#

I was was wondering if there is any difference between manually creating a new instance of a string class and initializing a variable with a string value.

public class Array {
    public static void main(String[] args) {
        String a = new String("manual instance");
        System.out.println(a);
        String b = "initialization";
        System.out.println(b);
  }
}
pliant cipher
#

There is a slight difference in term of memory allocation bit no difference in functionalites. Both will assign a instance of the String object to the variable.

When you create a instance of the class string using the new it allocate automatically the object into the memory. On the other hand, when you using the quotes to create a string object, the compiler will check if a string of the same value already exists in memory. If it does, it doesn't create the new instance and use the one that exists. Otherwise, it does the same as using the new keyword.

It is recommend to use the direct initialization as it allows you to save some memory.

snow hemlock
#

new String("str") is useless copy allocation

#

only use String constructor if you do weird things with extra parameters