Fester
Fester

Reputation: 59

What are the differences between using "new" keyword and and not using it?

What are the differences between this:

Class object1 = new Class();

and this:

Class object1;

Correct me if I'm wrong, but I'm pretty certain that the first code is used to refer to a new object while the other is not. Even if that's the case I still don't know which one I should be using for my program. Thanks in advance!

Upvotes: 0

Views: 881

Answers (4)

sagi
sagi

Reputation: 40491

First one is creating a new instance of Class object.

Second one is just declaring the a variable of Class type. It will be uninitialized until you initialize it.

Note that your first example is doing the same as the second one, plus initializing it.

Class object1 = new Class();

Is short syntax for:

Class object1;
object1 = new Class();

Upvotes: 7

Robin Bennett
Robin Bennett

Reputation: 3231

When you declare a variable Class object1 you're just defining a place to put something, that will only take objects of that type. Initially it will be null.

When you use new you're actually creating the object.

Upvotes: 0

Connell
Connell

Reputation: 14419

Class object1 = new Class(); creates a new instance of Class and assigns it to the object1 variable.

Class object1; only declares the variable, but does not assign any value to it (not even null). You cannot use the variable e.g. perform a null check or pass it into another method until you assign a value to it.

Class object1;
// other code
object1 = new Class();

Upvotes: 2

adjan
adjan

Reputation: 13684

Class object1 = new Class();

is the same as

Class object1; // declare variable
object1 = new Class(); // instantiate object and assign reference to variable

Upvotes: 2

Related Questions