0

Simple code:

class MyClass<T>
{

private T t;

    public void add(T t)
    {
       this.t = t;
    }

    public T get()
    {
     return t;   
    }  
}

And then:

public static void main(String[] args) {

    MyClass<String> StringClass = new MyClass<>();

    StringClass.add("This is string");

 // **Or actually it can be:  StringClass.add(new String("This is string"));**

I saw that people use StringClass.add(new String("This is string")) instead of simple version StringClass.add("This is string"). What's the difference?

Same story with Integers.

X-Pippes
  • 1,170
  • 7
  • 25
Ernusc
  • 516
  • 1
  • 5
  • 15

1 Answers1

1

The difference between
String foo = "bar"

and

String foo = new String("bar")

is that the first one does not create a new String object but rather, it looks for that value in the existing String values that you have created. This is called interning the value. This saves memory.

The one with the new keyword assigns new memory for the String object you created.

public class StringInternExample {
    public static void main(String[] args) {
        String foo1 = "bar";
        String foo2 = "bar";

        String foo3 = new String("Hello, Kitty");
        String foo4 = new String("Hello, Kitty");

        if(foo1 == foo2){ // compare addresses. Same address = no new memory assigned
            System.out.println("No new memory has been assigned for foo2");
        }

        if(!(foo3 == foo4)){ // compare addresses. Different addresses = new memory
            System.out.println("New Memory has been assigned for foo4");
        }

    }
}
An SO User
  • 24,612
  • 35
  • 133
  • 221