Confusion of reference variables vs objects in arrays

Precaution in using reference variables vs objects in array creation

Note: If you are new to reference variables, read Reference Variables Anonymous objects before reading this.

Reference variables vs Objects is very confusing while creating array objects as an array. Observe the following code.

public class Demo
  int x;
  public static void main(String args[])
    Demo d[] = new Demo[2];
    // d[0].x = 100;  this is error at this point as d[0] is a reference variable and not an object
    // Following statements convert reference variables d[0] and d[1] into objects
    d[0] = new Demo();
    d[1] = new Demo();

    d[0].x = 100;         // now this works
    d[1].x = 200;

    System.out.println("d[0].x value: " + d[0].x); 
    System.out.println("d[1].x value: " + d[1].x); 

reference variables vs objects

Demo d[] = new Demo[2];

Many people think, in the above statement, two array objects of Demo class are created. It is wrong.

The statement creates two reference variables of Demo class. That is, d[0] and d[1] are reference variables and not objects. They must be converted into objects before used. That is what is done in the following statements.

d[0] = new Demo();
d[1] = new Demo();

Now, d[0] and d[1] are full-fledged objects and can be used in the program as you like.

Pass your comments and suggestions to improve this tutorial on "Confusion of reference variables vs objects in arrays".

2 thoughts on “Confusion of reference variables vs objects in arrays”

  1. excellent sir, i hava done msc(cs) through distance education(annamalai university). and 33 years old. i dont have any experience in software field. worked as computer teacher in blor.

    now i completed diploma in java(java and advance java). if i want to try in software industry, how to improve more technical knowledge to get job. please guide me.

Leave a Comment

Your email address will not be published.