ek.Nik ek.Nik -4 years ago 65
Java Question

Difference between Objects of class and objects-array

Its part of codes.In the first part of code i wrote objects of class.This is fine i havent problem.My problem is on the second part of code

Paper[] pin = new Paper[N]; //N are given by keyboard .
for (int i=0; i < N, i++) //until the lenght N
{
pin[i] = new Paper();
}
pin[0].setpencil(3); // the number 3 i random chose it from my mind,i have done get and set methods
pin[0].getpencil(3);


i want to do it not for class and this is the second part of code down.If i want to create objects not using class this is right way?

int[] pin = new int[N];
for (int i=0; i < N, i++)
{
pin[i] = new int();
}
pin[0].setpencil(3);
pin[0].getpencil(3);

Answer Source

If you want to use an array of integers, just use int[N].

int[] pin = new int[N];

That's it. Java initializes primitives for you to 0 (zero) or false for boolean. You do not need a for loop to set the contents of the array, unless you want some value other than zero.

For example, to initialize all values of your array to 42:

int[] pin = new int[N]; 
for (int i=0; i < N, i++)
{
    pin[i] = 42;
}

To read and write this array, you cannot use methods. Just treat the array deference like any other variable.

pin[0] = 3;                    // pin[0].setpencil(3);
System.out.println( pin[0] );  // pin[0].getpencil(3); prints "3"

However, classes must work differently (or at least they do in Java). If you have an object array instead of primitives:

Class Paper {
   void getpencil(int n) {}
   void setpencil(int n) {}
}

and an array

Paper[] myPaper = new Paper[N];

You must access this through methods; you cannot use the form above which is only for primitives.

myPaper[0].setpencil(3);
myPaper[0].getpencil(3);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download