Creating an array of objects sets them all to null?

I am using the following code:
public class PlayerTest {
    public static void main(String[] args) {
        Player[] p = new Player[1];
        System.out.println(p[0].getId());
}and for the 'Player' object:
public class Player {
    int id;
    String name;
    int prediction;
    int score;
    public Player() {
        this.name = "a";
        this.score = -1;
        this.id = genRanId();
        this.prediction = -1;
...and, when i try to execute the "PlayerTest" class, i get the error:
Exception in thread "main" java.lang.NullPointerException
        at PlayerTest.main(PlayerTest.java:5)I think this is because when the array of player objects is created, they are all set to null, and the fields are not created. How do i get the program to initialise the fields in each player object of the array?
Creating the array of Player objects doesnt seem to use the constructor for the player class like creating an indivdual one does for some reason, as if i create a single element, instead of an array of them, it works fine....
Please help!

Yes you are quite right they are null by default (that is nothing is assigned to the array of pointers you have created) you will have t initialise the array the array
        Player[] p = new Player[1];
        for(int i=0;i<p.length;i++)p[i] = new Player();
    //or you can do
   Player[] p = {new Player(),new Player()};(IMHO) Its pointless having an array like this with identical objects you are betteroff instantiating the Person class using a constructor that takes some initial parameters however it is up to you.
Good luck
Wiraj

Similar Messages

  • Formatted .data file, reading in and creating an array of objects from data

    Hi there, I have written a text file with the following format;
    List of random personal data: length 100
    1 : Atg : Age 27 : Income 70000
    2 : Dho : Age 57 : Income 110000
    3 : Lid : Age 40 : Income 460000
    4 : Wgeecnce : Age 43 : Income 370000
    and so on.
    These three pieces of data, Name,Age and Income were all generated randomly to be stored in an array of objects of class Person.
    Now what I must do is , read in this very file and re-create the array of objects that they were initially written from.
    I'm totally lost on how to go about doing this, I have only been learning java for the last month so anyone that can lend me a hand, that would be superb!
    Cheers!

    Looking at you other thread, you are able to create the code needed - so what's the problem?
    Here's an (not the only) approach:
    Create an array of the necessary length to hold the 3 variables, or, if you don't know the length of the file, create a class to contain the data. Then create an ArrayList to hold an instance of the class..
    Use the Scanner class to read and parse the file contents into the appropriate variables.
    Add each variable to either the array, or to an instance of the class and add that instance to the arraylist.

  • Creating an arrays of objects from a class

    I was wondering does any one know how to create an array of objects from a class?
    I am trying to create an array of objects of a class.
    class name ---> Class objectArray[100] = new Class;
    I cant seem to make a single class but i need to figure out how to create an array of objects.
    I can make a normal class with Class object = new Class

    There are four lines of code in your for-loop that actually do something:
    for(index = 0; index < rooms.length; index++) {
    /*1*/  assignWidth.setWidth(Double.parseDouble(in.readLine()));
    /*2*/  rooms[index] = assignWidth;
    /*3*/  assignLength.setWidth(Double.parseDouble(in.readLine());
    /*4*/  rooms[index] = assignLength;
    }1.) Sets the width of an object, that has been instantiated outside the loop.
    2.) assigns that object to the current position in the array
    3.) Sets the width of a second object that has been instantiated outside the loop
    4.) assigns that other object to the current position in the array
    btw.: I bet you meant "assignLength.setLength(Double.parseDouble(in.readLine());" in line 3 ;)
    Since each position in an array can only hold one value, the first assignment (line 2) is overwritten by the second assignment (line 4)
    When I said "construct a new room-object and assign it to rooms[index]" I meant something like this:
    for(index = 0; index < rooms.length; index++) {
        Room aNewRoom = new Room();
        aNewRoom.setWidth(Double.parseDouble(in.readLine()));
        aNewRoom.setLength(Double.parseDouble(in.readLine());
        rooms[index] = aNewRoom;
    }1.) Constructs a new Object in every iteration of the for-loop. (btw: I don't know what kind of objects you're using, so this needs most likely modification!!)
    2.) set the width of the newly created object
    3.) set the length of the newly created object
    4.) assign the newly created object to the current position in the array
    -T-
    btw. this would do the same:
    for(index = 0; index < rooms.length; index++) {
        rooms[index] = new Room();
        rooms[index].setWidth(Double.parseDouble(in.readLine()));
        rooms[index].setLength(Double.parseDouble(in.readLine());
    }but be sure you understand it. Your teacher most likely wants you to explain it ;)

  • Creating an array of objects of a class known ONLY at RUNTIME

    I have a method in a class which expects an array of objects of particular type (say A) as its only argument. I 'invoke' this method using reflection. I have the instances of the class A stored in a Vector. When I do 'toArray' on this vector, what I get back is an array of Objects and not an array of objects of A. I assign this array to the zeroth element of another Object array and pass that array as a second argument to the 'invoke' method. Of course, it throws an Exception saying - argument types mismatch. Because I am sending an array of Objects to a method expecting an array of objects of A. My problem is I don't know A until runtime. So I have to handle whatever I am getting back after doing 'toArray' on a vector as a Generic Object. I know there's another version of 'toArray' in the Vector class. But it's API documentation didn't help a lot.
    Can anybody please help me solve this problem? Any sort of hints/code snippet would be of great help.
    Does the above description makes any sense? If not, please let me know. I would try to illustrate it with a code sample.
    Thanks a lot in advance.

    Sorry, for the small typo. It is -
    clazz[] arr = (clazz [])java.lang.reflect.Array.newInstance(clazz, n);
    instead
    Thanks for the reply. I could do this. But I am
    getting a handle to the method to be 'invoke'd by
    looking at the types of the parameters its
    expecting(getParameterTypes). So I can't change it to
    accept an array of Generic Objects.
    I looked at the java.lang.reflect.Array class to do
    this. This is what I am trying to do-
    String variableName is an input coming into my
    program.
    n is the size of the array I'm trying to create.
    Class clazz = Class.forName(variableName);
    clazz[] arr = (clazz
    [])java.lang.reflect.newInstance(clazz, n);
    According to Reflection API, it should work, right?
    But compiler yells at me saying 'class clazz not
    found'.
    Any suggestions/hints/help?
    Thanks, again.

  • How to create an Array of Object

    Is this correct:
    Object[] anArray = new Object[5];
    Thanks.

    Your code will create an array of 5 null references to class Object. After that line you could code:anArray[0] = new Integer(5);- or -
    Object x = anArray[1];but if you code:anArray[3].DoSomething();and have not initialized anArray[3], you will get a NullPointerException.
    Doug

  • Creating an array of objects

    Hey,
    I basically have two classes and am trying to create an array of one class in the sub class. My code keeps coming up with <identifier> expected on complie:
    Main Class
    import java.util.ArrayList;
    import java.io.*;
    * @author David Bainbridge
    * @Date 12/02/07
    public class Main {
             public ArrayList<City>ListOfCities;
    public static void main(String[] arguments) {
         Main.newcity();
         public Main() {
         ListOfCities = new ArrayList<City>(); //this creates an array which stores all instances of the cities.
         public static void newcity() {
              String Name = "Lincoln";
              String Lat = "10";
              String Long = "11";         
              ListOfCities.add(new City(Name, Lat, Long)); 
              Lincoln.displaycity();
    }City Class
      * The City class represents a City.
      * @author David Bainbridge
      * @Date 13/02/07
    public class City {
         private String Name;
         private String Latitude;
         private String Longitude;
          * Constructor for the City.
         public City(String cityName, String cityLat, String cityLong) {
              Name = cityName;
              Latitude = cityLat;
              Longitude = cityLong;          
          * Display the current City.
    public void displaycity() {
              System.out.println("Name: " + Name);
              System.out.println("Latitude: " + Latitude);
              System.out.println("Longitude: " + Longitude);
    }

    Thanks JJCoolB but neither worked!
    I have rejigged my code:
    import java.util.ArrayList;
    import java.io.*;
    * @author David Bainbridge
    * @Date 12/02/07
    public class Main {
             public static ArrayList<City>ListOfCities;
    public static void main(String[] arguments) {
         ListOfCities = new ArrayList<City>(); //this creates an array which stores all instances of the cities.
         Main.newcity();
         public static void newcity() {
              String Name = "Lincoln";
              String Lat = "10";
              String Long = "11";         
              ListOfCities.add(new City(Name, Lat, Long)); 
              Lincoln.displaycity();
    }I get two complie errors with it one says:
    public static ArrayList<City>ListOfCities; - <identifier> expected
    ListOfCities = new ArrayList<City>(); //this creates an array which stores all instances of the cities. - '(' or '[' expected.
    Thanks in advance for any help people!

  • Create an array of objects

    i have to write a program with 3 classes, Student, Coarse, and Main.
    Coarse class has 3 instance variables, with the constructor:
    public Coarse(String symbol, String name, int credit)Student class has 3 instance variables plus one method, one of these variables is an array of class Coarse, if i write a constructor of Coarse-class in Student, i would limit the number of coarses to one.
    Coarse coarse=new Coarse("CMPE112", "OOP", "3");i want the student to input all the coarses he signed in???

    noowa wrote:
    i want the student to input all the coarses he signed in???How do you want them to input their courses? If this is a dynamically-sized array, then instead of using an Array, go for an ArrayList. Then find some way to get user input (if that's what you wanted) and then instantiate new course objects into the ArrayList.
    Arrays: http://java.sun.com/docs/books/tutorial/reflect/special/index.html
    Lists: http://java.sun.com/docs/books/tutorial/collections/implementations/list.html
    ArrayList: http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html
    As for input, there are many, many options. Common ones are use the BufferedReader, InputStreamReader, and Scanner classes.
    There are some solutions here: http://forum.java.sun.com/thread.jspa?threadID=555025&messageID=2724272
    I'm not fully comprehending your question. Care to give some surrounding code or information?

  • I set the duration of a clip and iMovie sets it to something else. So I try to set all stills to same length and iMovie sets them all to a different interval. Now I have a movie much longer than intended. ?!?!

    Well, the title of the question pretty much says it all.

    If you go to Edit/Preferences, you can set the default duration for each slide. This will affect only those photos you've imported into your project AFTER changing this preference.
    You should also turn off the preference for Scale to Frame Size, so your photos do not fill the screen. (And, for efficiency's sake, make sure your source photos are no larger than 1000x750 pixels, per the FAQs at the top of this forum.)
    You can also set the duration of each slide by selecting all of the stills you want to include on in your slideshow, right-clicking and selecting the Create Slideshow option.

  • I have multiple phones, how do i set them all up on icloud?

    Is there a way to set all phones up in one iCloud, or does each phone have to be set up separately?

    There is a way to set all phones on one icloud and there are some positives and negatives about that and it has to be done on all devices one by one.
    http://www.apple.com/icloud/setup/ios.html
    Devices will sync with each other, so if you do not want family contacts merge for example you do not need one icloud account.

  • Creating array of objects of JLabel , JTextField type

    hello,
    I wanted to create an array of objects of JLabel class. I wrote and complied the following lines. it was successfully compiled but during execution it showed - 'start: applet not initialized' on the applet's window. What wrong have I done and how can I get rid of that?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    /*<html>
    <applet code="test.class" width=200 height=300>
    </applet>
    </html> **/
    public class test extends JApplet
         Container c = getContentPane();
         JLabel lb[];
         public void init()
                   for( int i = 0; i < 10; i++ )
                   lb[i] = new JLabel( "Line" + i );
                   c.add( lb[i] );
    }

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    /*<html>
    <applet code="test.class" width=200 height=300>
    </applet>
    </html> **/
    public class test extends JApplet
         Container c = getContentPane();
         JLabel lb[] = new JLabel[10];
         public void init()
                   for( int x = 0; x < 10; x++ )
                   lb [x]= new JLabel( "Line" + x );
                   c.add( lb );
    // showing applet not initiliazed
    // generating nullPointerException
    // please helpLast post, thats a promise!!! :-)Still wrong. See corrections in 'for' loop. :)

  • How to update an object property located in an array of objects

    Hello all,
    I have a script that creates custom objects and populates them and saves them into an array. This array of objects is later converted to a CSV file for reuse later on. On a subsequent need to run the script and to save time and avoid recollecting
    data I have previously amassed, I read in the contents of the csv file and put this data into an arryOfObjects.
    I need to manipulate the data in specific objects but I can't figure out how to accomplish that task.
    I can identify the correct object within the array with the following command. I have been trying to pipe that result into either set-variable or set-itemproperty without success.
    $arrayOfObjects | select-object | where HostName -like $_.'name'
    This works, I can see my desired object and the data fields contained within it.
    I now need to modify one of the property fields. (Alias).
    I have been trying the following as a line of thought, but so far without success. It doesn't fail/error out, but it doesn't update the data either.
    $arrayOfObjects | select-object | where HostName -like $_.'name' | set-itemproperty -name Alias -value "newAlias"
    I'm wondering if I need to specify something for the -path argument, but since the array is in memory and not a registry location or a file I am not sure what I should use, if this is the problem at all.
    Any suggestions would be appreciated.
    Thanks
    Smitty

    yes, I have redacted things, and obscured other things because I can not go around posting critical infrastructure information out on the internet.
    Here is the first three lines of my .csv file
    "OrigIP","AL_HostName","AL_Found","AL_Enabled","AL_Status","N_HostName","InREDACTED","N_Found","Delta","IsStale","Ping","InDNS","InAD","Location","Alias","IsServer","HostType","OS","ApplianceName","FQDN","ChatterValue"
    "10.24.11.4","ABCD","yes","yes","never","abcd.domain.com","yes","yes","*","*","Y","Y","N","TEST","*","*","eventlog","","","ABCD.DOMAIN.COM","*"
    "10.24.12.18","EFGH","yes","yes","Dec 30 2014 09:15:00","efgh.domain.com","yes","yes","-25","No","Y","Y","Y","TEST","*","yes","eventlog","xxxxxx","","EFGH.DOMAIN.COM","*"
    When I import this file I create a new custom object (objectCurrent) which I populate with the data from the csv file. I then store this object into an array of objects (objectCollection).
    All of the data is present.
    I then read in a new csv file that would contain most of the same hosts, but possibly additional new ones. upon importing the second csv file I loop through the entries.
     I have a conditional statement that checks to see if the host name from the second csv file, if it isn't then treat it like a new object and go fill in all of the details of the object using my various functions, etc.
    Import-CSV$currentALReport-Delimiter","|ForEach-Object
         if($objectCollection.N_HostName
    -notcontains$_.'name')
            # then create a new currentObject and go populate the properties of the object 
         elseif ($objectCollection.N_HostName -contains $_.'name') {
              # copy this object and update the object's AL_Status (which is the last reported message date info)
                  # send that to the function that will parse it, compare Julian dates and see if it falls within my
                  # criteria as being stale.  if so set the IsStale property to Yes, but reguardless set the AL_Status
                  # newest last reported message data
    JRV states that "The "select object" does nothing at all unless you have a column in your CSV called "object".  The where clause will do nothing because it is syntatctically wrong and illogical. "
    I beg to differ.  Using the above command :   with the script running and the current focus ($_.'name') equals "abcd.domain.com"
     $arrayOfObjects | select-object | where N_HostName -like $_.'name'
    It obtain a single object within my array of objects similar to this:
    IP: 1.2.3.4
    N_HostName: abcd.domain.com
    IsStale: No
    LastMsgDate: Dec 30 2014 09:15:00
    Delta: 1
    Ping: Yes
    InDNS: Yes
    InAD: Yes
    Alias: *
    (other fields omitted for brevity) I could get any of my existing objects if I match the hostname
    If I used only the command "  $objectCollection | Select-Object "    it returns every object in my array.
    So to narrow down the selection to a single object I add the " | where N_HostName -like $_.'name'  "
    which gives me the exact object I am searching for.
    My only question is how can I modify the contents of the object that I have specified within the array of object???

  • Plz help!! array of object (for search)

    i've got few questions of array of object
    1-how to search for a price that is greater than 300 in the array of object
    and how to list all of them?
    2- how to search for the smallest price in the array of object, and how to list?
    can anyone provde a java code for me:P?
    but plz don't too complex
    coz i'm a learner of javaT_T

    _< i still can't understand, and dunno how to change into the code that i needand you guyz help me change it?
    /*wirte the driver program which will define and create an array of
    objects instantiated from the class WaterBill
    Create Accessor and Mutator methods to get/set data from the class.
    write code within the driver method to perfrom the following:
    a) The final total of funds
    b) To search for accounts greater than $300 in the array of objects,
         and list all the customer details
    c)To search for the lowest bill in the array of objects, and list
    those customer dtails
    Class definitions and Objects  using price
    import java.text.*;
    import javax.swing.JOptionPane;
    public class Pre_pb3
         public static void main(String []args)
              int  TTc=0;
              int accNum[]=new int[20];
              String name[]=new String[20], output, stans, display; //stAccNum, stUsage, stTTc;
              double usage[]=new double[20];
              double TTa=0.0;
              double price[]=new double[20];
              char ans;
              double acctG,lowest;
              int i=0;
              waterBill MYwaterBill = new waterBill();
              ans='Y';
              while (!(ans=='N'))
                   name=inputName();
                   accNum[i]=inputAccNum();
                   usage[i]=inputUsage();
                   price[i]=calculateAmountOwing(usage[i]);
                   TTa=MYwaterBill.TTaPrice(price[i]);
                   output=MYwaterBill.outputInfo(name[i], accNum[i], usage[i], price[i]);
                   waterBill MYwaterBill2= new waterBill(name[i], accNum[i],usage[i], price[i]);     
                   stans=JOptionPane.showInputDialog("Do you wanna continue?, (Y)es, (N)o");
                   stans = stans.substring(0, 1);
                   stans=stans.toUpperCase();
                   ans=stans.charAt(0);
                   TTc++;     
              MYwaterBill.outputoutput(TTc, TTa);
              MYwaterBill.findGreat();     //b)
              MYwaterBill.searchDetail();     //c)
              System.exit(0);                                                  
         public static String inputName()
                   String name;
                   name=JOptionPane.showInputDialog("Enter Name ");
                   return name;
         public static int inputAccNum()
              int accNum;
              String stAccNum;
              stAccNum=JOptionPane.showInputDialog("Enter Account Number");
              accNum=Integer.parseInt(stAccNum);
              return accNum;
         public static double inputUsage()
              double usage;
              String stUsage;
              stUsage=JOptionPane.showInputDialog("Enter Water Usage");
              usage=Double.parseDouble(stUsage);
              if (!(usage>=0 && usage<=99999999))
                   System.out.println("water useage is invalid");
                   System.exit(0);
              return usage;
         public static double calculateAmountOwing(double usage)
              double price=0.0;
              if (usage>=0)
                   if (usage<=10000)
                        price=(10000/10)*0.01;
                   else if (usage>10000)
                        price=((10000/10)*0.01)+(((usage-10000)/10)*0.02);
              else
                        System.out.println("Error of usage");
                   return price;
    class waterBill
         private static     int TTc=0 ,accNum=0;
         private static String name, stAccNum, stUsage, stTTc;
         private static String output=" ";
         private static double usage=0.0;
         private static double TTa=0.0;
         private static double price=0.0;
         private static String lowest;
         public waterBill()
              name=" ";
              accNum=0;
              usage=0.0;
              price=0.0;
         public waterBill(String n,int an, double us, double p)
              setName(n);
              setAccNum(an);
              setUsage(us);
              setPrice(p);
         public void setName(String n)
              name=n;
         public void setAccNum(int an)
              accNum=an;
         public void setUsage(double us)
              usage=us;
         public void setPrice(double p)
              price=p;
         public String getName()
              return name;
         public int getAccNum()
              return accNum;
         public double getUsage()
              return usage;
         public double getPrice()
              return price;
         public double TTaPrice(double price)
              TTa=TTa + price;
              return TTa;
         public String outputInfo(String name, int accNum, double usage, double price )
              String output=" ";                         
              output: System.out.println( "Account Number: "+ accNum +
                                       "\nWater Usage: " + usage +
                                       "\nCost Owing: " price
                                       "\nName: "+ name+"\n");
              return output;
         public void outputoutput(int TTc, double TTa)
              display:     System.out.println("Total customer: "+ TTc +
                                  "\nTotal amount owing: " + TTa + "\n\n");
         public void findGreat()//search the a/c that is greater than 300.
              //dunno how to do, so i just leave it blank^^"
              public String searchDetail()//search the smallest a/c
              //same...dunno how to doT_T     

  • Help populating an array of objects

    New here, trying to figure this out.
    I'm trying to create an array of objects, then populate the array defining fields. I stripped this down as far as i could to simplify the problem but I get the following error when I compile (i tweaked the carrot placment, formating issues i guess):
    PointsTest.java:41: ']' expected
    cubeArray[0] = new Point();
    ^
    PointsTest.java:41: invalid method declaration; return type required
    cubeArray[0] = new Point();
    ^
    2 errors
    My code:
    class PointsTest{
        public static void main(String[] args) {
                   //So far, this works.
                //convert 3 numbers to point coordinates held in temp variables
                float xT = (Float.valueOf(args[0])).floatValue();
                float yT = (Float.valueOf(args[1])).floatValue();
                float zT = (Float.valueOf(args[2])).floatValue();
                Point point1 = new Point(xT, yT, zT);
                point1.printXYZ(); 
    class Point {
        //A BASIC point class
        //fields defined
        float x, y, z;
        //a constructor that sets initial XYZ values
        Point(float startX, float startY, float startZ) {
                x = startX;
                y = startY;
                z = startZ;
        //a no argument constructor for defualt states
        Point () {
            x = 0;
            y = 0;
            z = 0;
        //method
        void printXYZ(){
            System.out.println("coordinates: " + x + " " + y + " " + z);
    class Cube{
         Point cubeArray[] =  new Point[9];
         cubeArray[0] = new Point();
    }I've looked for answers online without much luck, I'm not worried about using a loop to populate the array at the moment (you can do it one at a time, right?). Didn't see any obvious listings in the java tutorials about arrays of objects. Any help would be appreciated.

    You need to put operations inside of a method instead of just floating them around inside the top-level of your Cube class. The errors you are getting are related to the fact that only class data members or methods are supposed to be inside the top-level of a class definition.
    Something like this should get you started:
    class Cube{
            private Point[] cubeArray;
            public Cube(){
             cubeArray =  new Point[9];
    }Regards,
    -MF

  • When creating a book how can I get all the photos from an album to show up in the order they were in the album?

    When creating a book in iphoto, how can I get all the photos from the album I want to use to show up in the order that they are in the album?  When I tried to use the option to add my own photos instead of having the program "flow" them, they showed up all mixed up.

    iPhoto puts them in the book in chronological order.  So to get your photos from an album into an iPhoto book in the same order you will need to use the Photos ➙ Batch Change ➙ Date menu option and set them all to the same date with a 1 minute time difference between each. 
    OT

  • Array of Object Refs

    I am doing exercises in a book (a couple books) to learn Java. I am a procedural pgmr and want to learn Java.
    Question 3 in Chapter 4 says:
    Create an array of object references of the class you created in Exercise 2, but don't actually create objects to assign into the array. When you run the program, notice whether the initialization messages from the constructor calls are printed.
    In exercise 2, I created an created an overloaded constructor. There are two constructors one that takes an argument and one that doesn't. I think I understand that I am being asked to look to see the values of the variables before the object is actually created but after initialization.
    My question is that I am not sure I understand what is being asked in question 3. I have to create an array of object references. I understand object references to be the varable names that hole the contents of the object. I don't understand what I am supposed to put into each (the two) elements of the array.
    Here is program written for exercise 2:
    //: c04:J402.java
    /* This has overloaded constructors. However, the argument must be given. Without it, there is an exception at runtime. */
    class Bird {
    Bird() {
    System.out.println("The object is an egg");
    Bird(String age) {
    System.out.println("The object is " + age + " months old");
    public class J402 {
    public static void main(String[] args) {
    String age = args[0];
    new Bird(age);
    } ///:~
    Thank you so much for any help.

    My question is that I am not sure I understand what is
    being asked in question 3. I have to create an array
    of object references. I understand object references
    to be the varable names that hole the contents of the
    object. I don't understand what I am supposed to put
    into each (the two) elements of the array.
    You need to make three different concepts clear to yourself: objects, object references, and reference variables.
    Objects are objects are objects. They are self contained entities that live somewhere in the memory. But, as you can't manipulate the memory directly (there are many good reasons for that), you can't manipulate objects directly.
    To get to objects you need references (or pointers). A reference is like a memory address. It normally points to the memory location of an object, but if the reference can also be a special 'null' reference that doesn't point to any object (or to every possible object, depending on how you want to look at it). The JVM takes care of talking to the underlaying object through the reference.
    An object can have many references pointing to it but a reference can point to only one object (or no / any object in the case of a null reference).
    Reference variables, then, are the ones you have in source code. Here's an example of a reference variable:Bird tweety;
    tweety = new Bird("I thought I saw a pussy cat!");(given a hypotetical class that can take a String object as an argument to the constructor)
    "tweety" is a reference variable. A reference variable is a variable that can hold a reference -- surprise! :). If not set to any particular reference, it's value may be null. If you now do something likeBird bird2 = tweety;
    tweety = new Bird();you first define a new ref. variable "bird2" and set its value to tweety's ref. Then you reset the var. tweety to point to a new Bird object. What happens to bird2? Nothing!! ... but if instead of "tweety = new Bird();" you had written "tweety.setChirp("TWEET!!!");" and then called bird2.chirp(), it would have chirped with "TWEET!!!" because the references of bird2 and tweety point to the same object.
    But, you can have references outside reference variables. In reference arrays (or "object arrays", the terminology can be confusing), for instance. Then, the codeBird[] flock = new Bird[2];0) Creates, allocates and initializes a new reference array object.
    1) Creates a new reference variable called "flock" and assigns it to a reference that points to the object that was created in 0).
    2) Creates 2 more references to Bird objects, initially set to null. No further objects are created. These references can be used like reference variables through flock[0] and flock[1].
    (not necessarily in this order)
    Now this should answer the excersise 3. The references of flock[0] and flock[1] are left as null and they don't point to any objects - They will only if you do something like "flock[0] = new Bird("chirp!");" or "flock[1] = tweety;"

Maybe you are looking for