java - null pointer exception in string array with assigning null during initialization -


i beginner in java.now i'm facing problem during pratice.actually want string tokens stringtokenizer class , wanna assign these tokens array of string.but i'm getting null pointer exception.my code here.

public class token {     public static void main(string str[])     {         string str1="this first page";         stringtokenizer str2=new stringtokenizer(str1);         int i=0;         string d[]=null;         while(str2.hasmoretokens())         {             d[i]=str2.nexttoken();          }     system.out.println(d);     } } 

arrays in java must initialized. this:

string d[] = null; 

essentially creates reference array, null. hence nullpointerexception.

what more, if initialized, size fixed , array cannot resized. cannot do:

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

continuing on, do:

d[i] = "whatever"; 

and i 0.

use list<string> instead:

list<string> list = new arraylist<>(); 

and .add(thestring) it:

while (str2.hasmoretokens())     list.add(str2.nexttoken()); 

last not least, this:

system.out.println(d); 

will not think does. print string representation of array reference. if want string representation of array plus elements, do:

system.out.println(arrays.tostring(d)); 

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -