Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Instantiating an object without an assignment

SRAY01May 17 2014 — edited May 29 2014

Hi,

I am learning Java. I would like to know what is the significance of instantiating an object without an assignment.

I have created a class TestClass1 with a single constructor that prints a test message.

In TestClass2, if I write "new TestClass1()" rather than "TestClass1 x = new TestClass1()" it still works, and prints the test message.

I would like to know if I do not assign an object at the time of instantiation, it cannot be referenced or reused later, then what is the significance of this type of construct and when it can be useful, and where is the object being held.

public class TestClass1 {

   TestClass1() {

     System.out.println("This is a test message");

   }

}

public class TestClass2 {

  public static void main (String... args) {

    TestClass1 x = new TestClass1();  //This prints "This is a test message"

    new TestClass1();                 //This also prints "This is a test message"

    String y = new String("abc");  //this makes sense

    //The following does not throw an exception - what purpose could this conceivably serve

    new String("def");               

  }

}

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 26 2014
Added on May 17 2014
7 comments
3,075 views