-12

Solution being the name of the class, what is the difference between the following?

  1. Solution solution;

  2. Solution solution = new Solution();

Nikos Tzianas
  • 633
  • 1
  • 8
  • 21
  • 4
    What do you think is the answer? This is not a "please do my homework for me" site – Roddy of the Frozen Peas Jan 18 '19 at 06:11
  • 2
    Read about classes and constructors. You'll get your answer – mrid Jan 18 '19 at 06:12
  • first one is just declaration and the second one is declaration plus initialization(means creating object and assigning it to a variable). As @RoddyoftheFrozenPeas said this is not a homework site , first please try something out then post here . – Mr Nobody Jan 18 '19 at 06:26

2 Answers2

4

There are three steps in object declaration and assignment in Java

  1. Solution solution

    You're telling Java to allocate space for a new reference variable.

    This variable will be forever of type Solution and it's only purpose is to hold the reference to an object of type Solution.

    But we haven't created that object yet, have we?

  2. solution = new Solution();

    The creation of the object. Java allocates space for the new object and creates it. That includes space for any variables that come along with the object (it's instance variables)

  3. solution = new Solution();

    We're assigning the reference variable to the newly created object (note the equals sign).

    In other words that reference variable will be connected with that object from now on and we can use that reference to call methods on it.

    Note that the last two steps are one line of code, but there's actually two different steps happening here.

what is the difference between the following?

Solution solution created an empty reference, a variable waiting for an object to be assigned to it.

Solution solution = new Solution() did all three steps in one line of code.

It created the reference, created the object and connected them together.

You can read more about the memory allocation in Java and programming in general here:

Where are instance variables of an Object stored in the JVM?

What and where are the stack and heap?

Nikos Tzianas
  • 633
  • 1
  • 8
  • 21
2
Solution solution;

only defines that solution variable is a Solution but it is otherwise uninitialized

Solution solution = new Solution();

also initializes it as an instance of Solution

Tacratis
  • 1,035
  • 1
  • 6
  • 16