Say I have created classes and now in main method, I want to assign and call them.
I write: X x = new X(); and x = new X();
What is/are the difference/differences between these two?
Say I have created classes and now in main method, I want to assign and call them.
I write: X x = new X(); and x = new X();
What is/are the difference/differences between these two?
Assuming that X is a class with a no-arg constructor (for example a default constructor), the following works:
// Declare and initialize x
X x = new X();
// Assign new value to x
x = new X();
The first code line declares a variable x and assigns a reference to the new instance of X to it (a new X object). The second line assigns a new X instance to the already declared variable x (thus discarding the reference to the first object). We declare a variable by putting the type name (or the word var) before them. So since in the first line, we have X x, this is a declaration.
In Java, variables need to be declared before they are first used. So the first code line would not work without the type name X at the front. Java would complain that the variable x had not been declared.
On the other hand, we are only allowed to declare each variable once. So putting type name X before the second line would be an error too. My Eclipse says Duplicate local variable x because it “thinks” that I am trying to declare a second variable also named x, which is not allowed (for good reasons).