Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null pointer exception in string array with assigning null during initialization

Tags:

java

string

I am beginner in java.Now i'm facing problem during pratice.Actually i want to get String tokens from a StringTokenizer class and wanna assign these tokens to the array of string.but i'm getting null pointer exception.My code is here.

public class Token {
    public static void main(String str[])
    {
        String str1="This is my first page";
        StringTokenizer str2=new StringTokenizer(str1);
        int i=0;
        String d[]=null;
        while(str2.hasMoreTokens())
        {
            d[i]=str2.nextToken();

        }
    System.out.println(d);
    }
}
like image 776
Tushar Paliwal Avatar asked Feb 14 '26 15:02

Tushar Paliwal


2 Answers

Arrays in Java must be initialized. This:

String d[] = null;

essentially creates a reference to an array, which is null. Hence the NullPointerException.

What is more, even if it were initialized, the size is fixed and the array cannot be resized. You cannot do:

String[] d = new String[]; // won't compile: size not specified

Continuing on, you do:

d[i] = "whatever";

and i is always 0.

Use a List<String> instead:

List<String> list = new ArrayList<>();

and .add(theString) to it:

while (str2.hasMoreTokens())
    list.add(str2.nextToken());

Last but not least, this:

System.out.println(d);

will not do what you think it does. It will print the string representation of the array reference. If you want a string representation of the array plus its elements, do:

System.out.println(Arrays.toString(d));
like image 131
fge Avatar answered Feb 16 '26 04:02

fge


You should count the token and initialize the string array based on that using str2.countTokens()

And printing should be done inside the loop..

public static void main(String str[]) {
    String str1 = "This is my first page";
    StringTokenizer str2 = new StringTokenizer(str1);
    int i = 0;
    String d[] = new String[str2.countTokens()];
    while (str2.hasMoreTokens()) {
        d[i] = str2.nextToken();
        System.out.println(d[i]);
    }
}
like image 23
AurA Avatar answered Feb 16 '26 04:02

AurA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!