package Sample;

public class Sam {
    public static void main(String[] args) {
        R obj[] = new R[100];
public class R {
int current;

when executing this code i am getting null pointer exception.
while debugging at "obj[0].current=0 " it shows as malformed expression error.
please correct me........

7 Years
Discussion Span
Last Post by PersonalIT

This is a fairly common mistake with arrays in Java.

The line
R obj[] = new R[100];
creates an array to hold objects of type R. However, no actual objects of type R are created yet. You need some code such as

for(int i=0; i<100; i++)
   obj[i] = new R();

to actually create the objects. This is sometimes confusing, as arrays are normally taught with primitive data types. Arrays created with primitive data types do initialize each element. So,

ints[] = new int[20]; 
ints[0] = 7;

works. But since you are using advanced data types, you need to initialize each element.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.