This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes When to use Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "When to use "new" when creating a new instance of an object or variable?" Watch "When to use "new" when creating a new instance of an object or variable?" New topic
Author

When to use "new" when creating a new instance of an object or variable?

J Steele
Greenhorn

Joined: Feb 28, 2013
Posts: 13
I have noticed that sometimes "new" is omitted when creating a new variable. Specifically, I have seen this when creating a new int or String. What are the rules regulating when you have to use "new" or just declare a variable? For example:
T Mishra
Ranch Hand

Joined: Apr 04, 2006
Posts: 108

This should get you started with Java. Instantiating primitives and objects


Thanks,
Tushar (SCJP 1.5)
J Steele
Greenhorn

Joined: Feb 28, 2013
Posts: 13
Thank you for the resources - exactly what I was looking for!
Stevens Miller
Ranch Hand

Joined: Jul 26, 2012
Posts: 523
    
    3

"new" is not relevant to the creation of a variable. It is used to create an instance of a class, also called an "object." It returns a reference to the newly created object, which may be stored in a variable of a type matching that of the object's class. In Line 1, you have created a variable that is of type int, which is a primitive, not a class. Anything that returns an integer may be stored in that variable. In Line 2, you have created a variable of type String. A reference to any String object may be stored in that variable. In Line 3, you have created a variable of type MyClass. A reference to any MyClass object may be stored in that variable. As it happens, in Line 3, you are also creating a new object of type MyClass. Well, you're not doing that, because you haven't completed the syntax necessary to invoke a constructor. Most likely, it would look like this:

There is no way, without knowing the class's constructor signature(s) to be sure, however, if the parenteses should be empty, or enclose an argument list. However, once a new object has been created, its reference (returned by new) can be stored in any variable of type MyClass.

Lines 3 could be rewritten thus:


Again, that's because variables are created independently of any objects, and new is used to create new objects.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When to use "new" when creating a new instance of an object or variable?