This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Creating Objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Creating Objects" Watch "Creating Objects" New topic

Creating Objects

Deon Smith

Joined: Mar 08, 2002
Posts: 7
Can someone please explain the advantage or disadvantage of the comment code list for 1 and 2. Thank you

class myClass {
myClass() {
System.out.println("My Class was called");

public static void main (String[] args) {
new myClass(); //1
myClass my = new myClass(); //2

[ September 23, 2002: Message edited by: Deon Smith ]
Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
Posts: 1879

1. creates an anonymous object. Once the constructor finishes, you can no longer use/access the object or any of it's parts and it becomes immediately available for garbage collection.
2. creates an object and assigns it's reference to a variable. After creation, you can access the object's members, use it's methods, and set it to null when you are done with it.
In your example, since your class has no members or methods, the only difference would be when the object is eligible for garbage collection.
[ September 23, 2002: Message edited by: Jamie Robertson ]
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: Creating Objects
It's not a secret anymore!