I have created an array for object v. ie value v=new value; and then i call the method getval of value class like this: v.getval()
but this is showing an error and that is
"Exception in thread "main" java.lang.NullPointerException at obj_array.main(obj_array.java:38)"
Please UseCodeTags <-- press on link for instructions.
You declared an array of value objects at line 36 32:
value v = new value;
but you didn't initialize any of the array's contents, as in:
v[i] = new value();
So the array is filled with nulls, hence the NPE.
In Java, by convention, class names are capitalized.
Underscores are seldom used in Java names, rather "camel casing" is employed to distinguish parts of names. For example, your obj_array would be better titled, ObjArray.
Edit: Line numbers shifted with code tags (I think).
Always learning Java, currently using Eclipse on Fedora.
Linux user#: 501795
What you've done there is create an array that can contain value objects, but you haven't actually created any value objects. All the entries are initialised to null to begin with. Think of it like an eggbox that doesn't contain any eggs yet.
Which means when you try and call getval() or display() on v or v, you're calling them on null, which gives that exception.
By the way, I'd suggest getting into the habit of following the standard Java conventions. And that means starting your class names with a capital letter: so Value instead of value.
Array elements are not initialized, they are null, just the array is declared.
So after declaration you can put for loop to initialize each array element by calling default constructor of value class. After you can invoke method on each element of an array.
The quieter you are, the more you are able to hear.
just like to add something, array elements are intialized to their default values , whether it is declared as instance variable or local varialbe. also if you Dog class which is subclass of Animal then the statment
Animal a = new Dog;
this will create a reference a of the type Animal array which will refer to Animal array object. basically this will create a CONTAINER with 5 compartments in it. each of those compartments initially will be null, since that is the default value of objects. these 5 compartments will hold 5 reference of the TYPE ANIMAL, and each will point to Dog object. now a question could pop in your mind what if you add Cat(which IS-A Animal) to the array. you will get ArrayStoreException at runtime .