error in object array

  • 14 years ago

    import java.util.*;
    import java.util.*;

    class Data{
    private String str;
    private double d;
    private char ch;

    public char getCh() {
    return this.ch;
    }

    public void setCh(char ch) {
    this.ch = ch;
    }

    public double getD() {
    return this.d;
    }

    public void setD(double d) {
    this.d = d;
    }

    public String getStr() {
    return this.str;
    }

    public void setStr(String str) {
    this.str = str;
    }


    }

    public class TestData{

    public static void main(String[] args){
    try{

    Data[] dataArray = new Data[1];

    dataArray[0].setStr("AAA");
    dataArray[0].setD(10.0);
    dataArray[0].setCh('Z');

    System.out.println(dataArray[0].getStr());
    System.out.println(dataArray[0].getD());
    System.out.println(dataArray[0].getCh());

    }catch(NullPointerException e){
    System.out.println(e);
    }
    }


    }





























































    // error java.lang.NullPointerException

  • 14 years ago

    Java is quite strange when it comes to arrays, and doesnt really make suence unless you understand pointers to pointers in c/c++.

    In Java, to Create an Array or N objects..

    // Create an Array of Objects...
    Object[] Array = new ObjectNo [N];

    // Fill The Array With Object.
    for(int I=0; I<N;I++)
    {
         Array[I] = new Object;
    }




    In Your Code, You Create An Array (pointer to pointers)
    but dont create new objects inside the array... and therefor, causing a memory access violation.


    HOWEVER,,, your array is only 1 object in size... you dont need an array.,, just create the new object.


























Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“C++ : Where friends have access to your private members.” - Gavin Russell Baker