Tegwin
Tegwin

Reputation:

In Java, is new always new?

Is there any way in Java that a statement like

Thing thing = new Thing();

could not result in a new object being created (i.e. any way that thing could end up pointing to an already-existing object)?

Upvotes: 5

Views: 915

Answers (12)

zkarthik
zkarthik

Reputation: 959

The call to new can fail if this is the first time you are referring to the class and if the class has static blocks that fail to initialize. I have experienced behaviors wherein any runtime errors that occur in a static block or constructor will result in the new call throwing a ClassNotFound Exception in the context of usage within the websphere application server. The websphere class loader apparently rejects the class from loading because of the runtime exception.

Upvotes: 0

Joachim Sauer
Joachim Sauer

Reputation: 308269

No.

After executing that line of code thing will never reference an object that existed before that line.

Upvotes: 0

Samuel Carrijo
Samuel Carrijo

Reputation: 17949

No, in the case there's no space in memory for it, you should get an OutOfMemoryError.

Of course, there could be other exceptions thrown by the Thing constructor.

Upvotes: 0

Silent Warrior
Silent Warrior

Reputation: 5295

new always creates new object. In java you can't reuse object using new. Really this leads to performance issue in certain java class. For e.g. Boolean class can practically stores only two values (true or false), still a user can create multiple objects with same value using new.

Upvotes: 0

Adam Crume
Adam Crume

Reputation: 15844

Several people are saying that an object won't be created if the constructor throws an exception. I would just like to point out that this is not true. As an example, take a look at this very bad code:

public class Test {
    static int count;

    static Set<Test> set = new HashSet<Test>();

    int id = count++;


    public Test() {
        set.add(this);
        throw new RuntimeException();
    }


    public static void main(String[] args) throws Exception {
        for(int i = 0; i < 5; i++) {
            try {
                new Test();
            } catch(Exception e) {
            }
        }
        System.out.println(set);
    }


    public String toString() {
        return "Test[" + id + "]";
    }
}

The output is:

[Test[0], Test[1], Test[2], Test[4], Test[3]]

new creates a new object EVERY TIME.

Upvotes: 4

Ascalonian
Ascalonian

Reputation: 15213

In Java, the only thing I can think of is using the Singleton pattern. This would not create multiple new instances of Thing, but rather an instance of the same object every time.

Upvotes: -1

quosoo
quosoo

Reputation: 829

New is always new (maybe with some exceptions for primitive wrappers), but if reusing objects is a desired behaviour there are ways to do that through certain design patterns (singleton, factory, pool etc.).

Upvotes: 1

Peter
Peter

Reputation: 6362

Using new will always result in a new object being allocated and created. However, you might be referring to the concept of interning, where objects and stored in a pool and can be reused to save on space. For a good example, see this article on String interning in Java.

Upvotes: 3

Jason S
Jason S

Reputation: 189906

as far as I know it's not like C++ where you can overload operator new or do placement new or other allocator things. (but I'm not familiar with the JLS)

Upvotes: 0

bgw
bgw

Reputation: 2056

I'm not sure if I understand your question correctly.

The definition of new is to allocate and initialize a new object.

I guess you might be able store a static reference to a object, and then clone it to make a new object, but that object would still be new.

Since you cannot modify the value of this (otherwise you could just say something like this = oldObject in your constructor), the only way you could do this is to throw an exception, like has been mentioned before.

Upvotes: 0

Brian Rasmussen
Brian Rasmussen

Reputation: 116501

If the constructor for Thing throws an exception, the object isn't created. However, thing will never point to another existing instance of Thing.

Upvotes: 6

Joey
Joey

Reputation: 354864

The new operator allocates new heap space and calls the constructor. You will always get a new object that way (unless, as others pointed out, an Exception is thrown in the constructor).

The thing is a little different with static methods that return a reference, such as Integer.valueOf() which re-uses objects from an internal pool if possible.

Upvotes: 16

Related Questions