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

后端 未结 9 1067
迷失自我
迷失自我 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.

    0 讨论(0)
  • 2020-11-22 03:21

    There are two ways in which Strings can be created in Java. Following are the examples for both the ways: 1) Declare a variable of type String(a class in Java) and assign it to a value which should be put between double quotes. This will create a string in the string pool area of memory. eg: String str = "JAVA";

    2)Use the constructor of String class and pass a string(within double quotes) as an argument. eg: String s = new String("JAVA"); This will create a new string JAVA in the main memory and also in the string pool if this string is not already present in string pool.

    0 讨论(0)
  • 2020-11-22 03:27

    I guess it will depend on the code samples you're seeing.

    Most of the times using the class constructor "new String()" in code sample are only to show a very well know java class instead of creating a new one.

    You should avoid using it most of the times. Not only because string literals are interned but mainly because string are inmutable. It doesn't make sense have two copies that represent the same object.

    While the article mensioned by Ruggs is "interesting" it should not be used unless very specific circumstances, because it could create more damage than good. You'll be coding to an implementation rather than an specification and the same code could not run the same for instance in JRockit, IBM VM, or other.

    0 讨论(0)
提交回复
热议问题