Difference between creating a “new object” and “Class objectname”

Say for example I have a class called Phone.

What is the difference between:

Phone p;


Phone p = new Phone(200) //(200 is the price of the phone).


new Phone(200)

I've googled and even tried it on Eclipse but can't figure it out.


Phone p; only declares a reference handler p which doesn't point anywhere (it is a not initialized and cannot be used until you assign something to it [thanks @Anthony]).

Phone p = new Phone(200); declares a reference handler p which points to a newly created Phone object (initialized with Phone(200)).

new Phone(200) creates a new Phone object, but since no reference to it is stored anywhere, it becomes immediately eligible for garbage collection (unless its constructor stores a reference somewhere, that is).

(Note that in Java, all "variables" whose type is a reference-type are really reference handlers. Only variables of value-type contain values directly. Since Phone is a reference-type (it's a class), Phone p is always a "reference to a Phone".)

The first snippet only declares a variable p with a given type Phone. You have not created any object, only a variable.

The third instantiates a new Phone object (which is not assigned to a variable).

The second combines the two, the declaration and instantiation, into a single line of code.

Phone p; // declaration of variable 
p = new Phone(200); // instantiation of object, assigned to variable 

Phone p = new Phone(200); // declaration and instantiation in a single line

For p to be used, you need to instantiate it (or otherwise initialize it). The declaration itself is not useful. In a local (a variable declared inside the scope of a method), it is illegal to use it without first initializing it. If it's a class-level member, then it will simply be a null pointer when you try to access any of its member functions.

Need Your Help

Routing Error with Post/Put requests (Passenger Headers)

ruby-on-rails passenger

I've run into a weird problem and after a bunch of research can't get any closer. I've got several forms that upload files via Carrierwave. When I upload the information, part of the route gets cut...

adding value attribute on all src tags in jquery

jquery html tags src

can i adding some value attribute on all src tags in current html page with jquery ?