What is the purpose of the expression “new String(…)” in Java?

后端 未结 9 1060
迷失自我
迷失自我 2020-11-22 02:39

While looking at online code samples, I have sometimes come across an assignment of a String constant to a String object via the use of the new operator.

For example

9条回答
  •  长情又很酷
    2020-11-22 03:21

    The only time I have found this useful is in declaring lock variables:

    private final String lock = new String("Database lock");
    
    ....
    
    synchronized(lock)
    {
        // do something
    }
    

    In this case, debugging tools like Eclipse will show the string when listing what locks a thread currently holds or is waiting for. You have to use "new String", i.e. allocate a new String object, because otherwise a shared string literal could possibly be locked in some other unrelated code.

提交回复
热议问题