I've create a program for the array of objects,
here is the code..!

import java.io.*;
class Student{
    int rollno;
    String name;
    public void setValues (int rollno, String name){
    this.rollno = rollno;
    this.name = name;
    public Student getValues(){
    Student s = new Student();
    return s;

class TestSTD{
public static void main(String args[])throws IOException{
    Student s1 = new Student ();
    s1.setValues(40, "Sufyan");
    Student s2 = new Student ();
    s2.setValues(30, "Ghori");
    Student s3 = new Student ();
    s3 = s2.getValues();
    System.out.print (s3.name + " " + s3.rollno + "\n\n");
    Student[] StdArr = new Student[5];
    InputStreamReader is = new InputStreamReader (System.in);
    BufferedReader br = new BufferedReader (is);
        for (int i=0; i<StdArr.length; i++){
        System.out.print ("Enter Roll Number: ");
            int rn = Integer.parseInt(br.readLine());
        System.out.print ("Enter Name: ");
            String names = br.readLine();
        System.out.println (StdArr[i].rollno + "   " + StdArr[i].name);

When i m running a program it is asking for 1 input then showing an error,

Exception in thread "main" java.lang.NullPointerException
at TestSTD.main(TestSTD.java:41)

Edited 6 Years Ago by Xufyan: n/a

There are two steps in using arrays of objects:
First define the array -> creates empty slots with null values
Second assign values to each of the slots/elements in the array.

You haven't done the second step.
You need to put a Student object into the array before you can call a method on that element of the array.

This article has been dead for over six months. Start a new discussion instead.