-3

What is the difference between-

Employee e = new Employee(); and Employee e;

If Employee is a class. Where would we use it in programs to satisfy our code?

Thanks.

Sawan Sinha
  • 11
  • 1
  • 4
  • 1
    Did you try basic Java tutorial? – Pradeep Simha Mar 22 '19 at 20:17
  • 1
    @ElliottFrisch not really. Local variables are not initialized to null, and you can declare them and initialize them later. – JB Nizet Mar 22 '19 at 20:18
  • 6
    `Employee e` declares a variable `e`, of type `Employee`. If it's a field, the variable is initialized to null. If it's a local variable, it's not initialized. `Employee e = new Employee()` declares a variable `e`of type Employee, and initializes it with an newly created Employee object. Every Java book or tutorial explains that. Do some basic research please. You can't learn programming on StackOverflow. – JB Nizet Mar 22 '19 at 20:20

1 Answers1

2

The first example is an initialization. You create a new object and assign it to the variable e :

Employee e = new Employee();

The second example is a declaration. You just associate a variable name with an object type:

Employee e;

As it was mentioned by @JBNizet whether the e is initialized or not depends on where you declare this variable.

If it is class member then it gets null as a default value. If it is a local variable then it doesn't get any default value(undefined).

See more Creating Objects
And Java: define terms initialization, declaration and assignment

Ruslan
  • 6,090
  • 1
  • 21
  • 36
  • The first one makes an `Employee` object AND initializes it as a new `Employee` object. The second one makes an `Employee` object, but doesn't initialize it. Thus, the second example defines it as null. – FailingCoder Mar 22 '19 at 20:28
  • 1
    @FailingCoder "_makes an `Employee` object_" is misleading—"make" seems similar to "instantiate". The second example merely declares a variable of type `Employee`, which will be initialized to `null` if it's a field, but does not "make" an `Employee` object. – Slaw Mar 22 '19 at 20:32
  • Maybe my `word choice` is incorrect. I'm pretty sure I got the right idea though? – FailingCoder Mar 22 '19 at 20:34
  • The first example is a declaration plus an initialization. – user207421 Mar 22 '19 at 20:50