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 = new Phone(200) //(200 is the price of the phone).
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.