tags:

views:

469

answers:

13

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)?

+15  A: 

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.

Joey
Yep and it's even a recommended pattern in the great Joshua Bloch's "Effective Java"
zim2001
+6  A: 

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

Brian Rasmussen
nor `null` values. It's strange to see code like `Thing t = new Thing(); if (t == null ) ...` - it will never happen
Alexander Kosenkov
A: 

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.

Samuel Carrijo
hmmm, why isn't that an OutOfMemoryError? Just interested.
Tim Büthe
the correct exception is really OutOfMemoryError.
cd1
@CD1 @Tim Corrected the mistake. I knew it was something like that. my bad
Samuel Carrijo
A: 

While this is an interesting question, what problem are you encountering that makes you ask it?

DDaviesBrackett
Actually, it's not that interesting. The language reference manual says that the variables are all initialized, so you couldn't tell. But, I'm curious why anyone would ask.
S.Lott
A: 

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.

PiPeep
A: 

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)

Jason S
+3  A: 

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.

Peter
+1  A: 

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.).

quosoo
Primitive wrappers (also called boxed primitives) follow the same rules as any other class: if you use a constructor to create one, you always get a new instance. However, autoboxing doesn't necessarily create a unique object each time because it uses a factory method instead of a constructor.
Alan Moore
Did I say somethin different?
quosoo
New is always new. There are no exceptions, even for primitive wrappers.
Dave Hinton
A: 

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.

Ascalonian
Any time you use `new`, you're creating a new instance. Period. With the Singleton pattern, you're calling `SingletonClass.getInstance()`, not `new SingletonClass()`.
Michael Myers
+3  A: 

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.

Adam Crume
A: 

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.

Silent Warrior
A: 

No.

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

Joachim Sauer
A: 

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.

zkarthik