2

Found this second way of initializing an object in a book. Pretty confused right now.

HellixS
  • 27
  • 4
  • 2
    Possible duplicate of [Uninitialized Object vs Object Initialized to NULL](http://stackoverflow.com/questions/16699593/uninitialized-object-vs-object-initialized-to-null) – Laur Ivan Mar 08 '16 at 14:59

3 Answers3

7

This declares a variable:

Car myCar;

That variable is of type Car and is called myCar. However, it hasn't been initialized to anything yet. It's a placeholder for a Car object, but no such object has been placed there. So its value is null.

This declares and initializes an instance:

Car myCar = new Car();

You can logically think of it as the following two statements in one:

Car myCar;
myCar = new Car();

A variable is declared and created, set as a placeholder, and an instance of Car is put there.


Edit: More specifically (and I learned something here just now), the value is null if it's a class-level member. For example:

class MyClass {
    Car myCar;

    void someMethod() {
        // myCar is "null" here
    }
}

However, if it's a local variable in a method, it's slightly different:

class MyClass {
    void someMethod() {
        Car myCar;
        // myCar is "uninitialized" here.
    }
}

The difference is mostly semantic and you shouldn't have to worry about it, unless you have errors or are doing strange things. The compiler will tell you if you're trying to use an "uninitialized" variable at all, since it can't be used until it's been initialized. But a null variable can be used, it's value is simply null.

David
  • 208,112
  • 36
  • 198
  • 279
1

The first statement defines a variable and assigns it a value by constructing a new Car instance. The second simply defines a variable without allocating it a value;

lance-java
  • 25,497
  • 4
  • 59
  • 101
1

Car myCar; This doesn't initialize the object, just declare it.

In the statement Car myCar; value of myCar is null if myCar is an instance variable. It is not pointing to any object in memory. You can declare the variable and intialise it before you use it first time otherwise it will throw a NullPointerException.

In the statement Car myCar = new Car();, there is an object created in memory by name myCar of class Car.

declaration: a declaration states the type of a variable, along with its name. A variable can be declared only once. It is used by the compiler to help programmers avoid mistakes such as assigning string values to integer variables. Before reading or assigning a variable, that variable must have been declared.

See this

Community
  • 1
  • 1
Charu Khurana
  • 4,511
  • 8
  • 47
  • 81