DelphiFAQ Home Search:

java.lang.NullPointerException when using arrays?

 

comments27 comments. Current rating: 4 stars (7 votes). Leave comments and/ or rate it.

Question:

Why do I keep getting a "java.lang.NullPointerException" when using arrays?

Answer:

Two possible explanations:
  1. You've indexed past the array bounds
  2. You haven't initialized the array correctly

   // example of an incorrectly initialized array:

       public class Test {
          public static void main(String args[]) {
             String sa[] = new String[5];
             sa[0].charAt(0);
          }
       }

    // example of a correctly initialized array:

       public class Test {
          public static void main(String args[]) {
             String sa[] = new String[5];

             for(int i = 0; i < 5; i++) {
                sa[i] = new String();
             }
 
             sa[0].charAt(0);
          }
       }

Content-type: text/html

Comments:

You are on page 1 of 2, other pages: [1] 2
2007-06-15, 03:45:05
anonymous from Canada  
I have been trying to find a straight answer to this question for 3 hours, thank you so much.
2007-12-02, 06:54:43
anonymous from Colombia  
rating
It works for me!!!
2008-02-23, 16:41:37
anonymous from Finland  
rating
At last, simply elegant explanation.
2008-05-02, 07:46:57
anonymous  
Thank u so much.. I'm trying to find this for hours... Thanks a lot again
2008-05-26, 13:26:18
anonymous from United Kingdom  
FFS at last, thank you so much. I have been looking for this for hours!
2008-05-29, 16:06:25   (updated: 2008-05-29, 16:08:53)
anonymous from Egypt  
that is gr8 but actually it didnt work with me :(

what about this block of code..

FileInputStream fis= new FileInputStream('users.txt');
ObjectInputStream ois=new ObjectInputStream(fis);
byte [] usersfile = new byte[100];
int filesize=0;
try {
filesize= ois.read(usersfile);
} catch (IOException e) {

e.printStackTrace();
}

here i'm trying to read from an existing file
but i get a nullpointerexception too.. and i donno the reason..
is it because of the byte array??!!
2008-07-15, 00:24:53
anonymous from Ratho, United Kingdom  
Excellent. This explains several days of work. Button grids and battleships here we come!!
2008-09-14, 10:14:15
anonymous from United States  
rating
Thank you very much. I was looking to try and figure out what was wrong with my applet and found this site and fixed it in a matter of minutes.
2008-10-12, 03:23:31
anonymous from United States  
rating
thank you so much

i've been stuck on this forever
2008-11-03, 08:27:09
anonymous from Korea (R)  
rating
Very nice!! thanks a lot
2008-11-11, 22:22:25
anonymous from India  
Its really a good example..and seeing this example i can solve my problem.
2008-11-27, 17:12:00
[hidden] from United States  
rating
Great but how can I access what I'm trying to do. I have gone into my security and enable java scripting but still don't know how to access the site I want someone please help.
2009-01-24, 17:51:15   (updated: 2009-01-24, 18:03:53)
anonymous from Canada  
I'm getting the same error with a 2D Array. I have a contructor before my Main method looks like this:

public Forest(int size){
    size= n+2;
    int forest[][] = new int[size][size];
    forest[n][n]= 1;
    }


And here's my printarray method:

public static void printForest() {
   
    // Loop through the number of rows in the array.
    for (int row=0; row < forest.length; row++) {

    // Loop through the columns in the rowth row.
    for (int col=0; col < forest[row].length; col++){

        // Print out the [row][col] item from the array.
        System.out.print(forest[row][col] + ' ');
    }

    // Go to a new line after each row is printed.
    System.out.println();
    }
}

And Here's my main method:

public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in),1);
        Forest origForest = new Forest(Forest.forest);
       
        //get probability and size of the internal grid (n) from the user
        System.out.print('Enter an integer for the size of the forest:\n');
        int n = Integer.parseInt(keyboard.readLine());
        System.out.print('Enter a percentage for the probability that a tree will catch fire:\n');
        double probCatch = Double.parseDouble(keyboard.readLine());
        System.out.println(probCatch);
        System.out.println(n);
        System.out.println('Here's my forest:');
        printForest();
        System.out.println();
       
    }
   
I can't get the 2d array to print out.
Help?
Thanks



Keywords:
2009-04-01, 18:41:20
anonymous from United Kingdom  
THANK GOD! Ive spent the past 2 hours trying to sort this out for a Uni project! Thanks a lot :)
2009-06-22, 04:46:11
anonymous from India  


I'm hoping this is the right place for posting my question. This is the error I'm getting in my code...

ani@ani-desktop:~/Desktop/FINAL-UTILITIES$ java retrievalGabor single-image/0000.jpg single-image-gabor-query.txt featdb.txt gabdb.txt 1 gaGabor-output.txt qt
1
gaGabor-output.txt
im here
java.lang.NullPointerException
at retrievalGabor.main(retrievalGabor.java:90)



//The alignment of the features is assumed to be AVG, VAR, CSD, GABOR

import java.io.*;
import javax.imageio.*;
import java.awt.*;
import java.awt.image.*;

class retrievalGabor
{
    public static void main(String args[])
    {
        if(args.length!=6 && args.length!=7)
        {
            System.out.println('The parameters are {Query Image} {Query Gabor file} {Features File} {Gabor Text File} [blocks] {Relevant Features} {EPS directory}');
            System.exit(0);
        }
       
        int BLOCKS=1, FEATURES=15, SCALE=3, ORIENTATION=4;
        BufferedImage bi, bi1;
        GraphicsEnvironment ge= GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice gd=ge.getDefaultScreenDevice();
        GraphicsConfiguration gc=gd.getDefaultConfiguration();
        Graphics2D g2D=null;
        ColorModel cm=null;
        DataInputStream dis, dis1;
        BufferedReader br, br1;

        float features[][], diff[], query[], tmp=0;
        String names[], tmps=null, tokens[];
        int images=0, bitcount=0;
        char ch;

        try{
            bi=ImageIO.read(new File(args[0]));
            bi1=gc.createCompatibleImage(bi.getWidth(null), bi.getHeight(null));
            g2D=bi1.createGraphics();
            g2D.drawImage(bi, null, 0, 0);
            bi=bi1;

            dis=new DataInputStream(new FileInputStream(args[2]));//opening the features file
            br=new BufferedReader(new FileReader(args[3]));//opening the texture features file
           
            if(args.length==7)
            {
System.out.println(args[4]);
                BLOCKS=Integer.parseInt(args[4]);

System.out.println(args[5]);
                dis1=new DataInputStream(new FileInputStream(args[5]));//opening the relevant features file
System.out.println('im here');
            }
            else
                dis1=new DataInputStream(new FileInputStream(args[4]));//opening the relevant features file

           
            //query=myFinalToolkit.computeColorSampleImage(bi, BLOCKS, SCALE*ORIENTATION);
//query= new float[126];

float [] qry = {0.1544465f ,0.54298925f ,0.73340774f ,0.017640665f ,0.085013896f ,0.095653236f ,0.0f,0.4047619f ,0.36394557f ,0.21768707f ,0.09863946f ,0.088435374f ,0.08163265f ,0.06462585f ,0.05782313f ,0.27210885f ,0.26870748f ,0.10204082f ,0.0f ,0.010204081f ,0.0034013605f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.023809524f ,0.010204081f ,0.0f ,0.0f ,0.17687075f ,0.32312927f ,0.0f ,0.0f ,0.09863946f ,0.6632653f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.013605442f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.08163265f ,0.0f ,0.0f ,0.0f ,0.49659863f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.010204081f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f ,0.0f};

// float [] query =         {0.1544465f ,0.54298925f ,0.73340774f ,0.017640665f ,0.085013896f ,0.095653236f ,0.0f} ;
// ,0.4047619 ,0.36394557 ,0.21768707 ,0.09863946 ,0.088435374 ,0.08163265 ,0.06462585 ,0.05782313 ,0.27210885 ,0.26870748 ,0.10204082 ,0.0 ,0.010204081 ,0.0034013605 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.023809524 ,0.010204081 ,0.0 ,0.0 ,0.17687075 ,0.32312927 ,0.0 ,0.0 ,0.09863946 ,0.6632653 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.013605442 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.08163265 ,0.0 ,0.0 ,0.0 ,0.49659863 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.010204081 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0 ,0.0};
//
query = new float[150];
for (int i=1;i<126; i++){
query[i] = qry[i];
}

            br1=new BufferedReader(new FileReader(args[1]));//opening the Query texture file
            tokens=(br1.readLine()).split(' ');
            for(int i=3;i<2*BLOCKS*SCALE*ORIENTATION;i++)
                query[BLOCKS*6+120+i-3]=Float.parseFloat(tokens[i]);
            br1.close();

            //reading the features file
            images=dis.readInt();
            features=new float[images][BLOCKS*(6+SCALE*ORIENTATION*2)+120];
            names=new String[images];

            for(int i=0;i<images;i++)
            {
                names[i]=new String();
                while((ch=dis.readChar())!='\n')
                    names[i]+=ch;
               
                for(int j=0; j<BLOCKS*6+120;j++)
                    features[i][j]=dis.readFloat();        
                dis.readChar();

                tokens=(br.readLine()).split(' ');
                for(int j=3;j<BLOCKS*2*SCALE*ORIENTATION;j++)
                    features[i][BLOCKS*6+120+j-3]=Float.parseFloat(tokens[j]);
            }
            dis.close();
            br.close();

int [] wt = { 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1 } ;
            //reading the feature relevancy
/*             wt=new int[BLOCKS*(FEATURES-1)+1];
            for(int i=0;i<BLOCKS*(FEATURES-1)+1;i++)
            {
wt[i] = 1;
            //     wt[i]=dis1.readInt();
// System.out.println(i+ ' ' + dis1.readInt());
            //     System.out.print(wt[i]+' ');
            }
            System.out.println();
            dis1.close();
*/
            diff=new float[images];
            for(int i=0;i<images;i++)
            {    
                //average and variance in color
                for(int j=0;j<BLOCKS;j++)
                {
                    for(int k=0;k<2;k++)
                    {
                        tmp=0;
                        if(wt[j*(FEATURES-1)+k]==1)
                        {
                            for(int     l=0;l<3;l++)
                                tmp+=Math.abs(query[j*6+k*3+l]-features[i][j*6+k*3+l]);
                           
                            diff[i]+=tmp/3;
                        }
                    }
                }

                //CSD
                tmp=0;
                if(wt[BLOCKS*(FEATURES-1)]==1)
                {
                    for(int k=0;k<120;k++)
                        tmp+=Math.abs(query[BLOCKS*6+k]-features[i][BLOCKS*6+k]);
                   
                    diff[i]+=tmp/120;
                }
               
                //texture features
                for(int j=0;j<BLOCKS;j++)
                    for(int k=0;k<SCALE*ORIENTATION;k++)
                    {
                        tmp=0;
                        if(wt[j*(FEATURES-1)+2+k]==1)
                            for(int l=0;l<2;l++)
                                {
                                    tmp+=M. abs(query[BLOCKS*6+120+j*SCALE*ORIENTATION+2*k+l]-features[is[i][BLOCKS*6+120+j*SCALE*ORIENTATION+2*k+l]);
                                }
                            diff[i]+=tmp/2;
                    }
               
            }


            //sort the entries in the sorted order
            for(int i=0;i<images-1;i++)
                for(int     j=0;j<images-i-1;j++)
                {
                    if(diff[j+1]<diff[j])
                    {
                        tmp=diff[j];
                        diff[j]=diff[j+1];
                        diff[j+1]=tmp;

                        tmps=names[j];
                        names[j]=names[j+1];
                        names[j+1]=tmps;
                       
                        tmps=null;
                    }
                }
           
/*             //sort the entries in the sorted order by name
            for(int i=0;i<29;i++)
                for(int     j=0;j<29-i;j++)
                {
                    if(names[j].compareTo(names[j+1])>0)
                    {
                        tmp=diff[j];
                        diff[j]=diff[j+1];
                        diff[j+1]=tmp;

                        tmps=names[j];
                        names[j]=names[j+1];
                        names[j+1]=tmps;
                       
                        tmps=null;
                    }
                }
*/
               
            Runtime rt=Runtime.getRuntime();
            String arr[]=new String[3], dir[]=new String[2];
           
            dir[0]=new String('/bin/mkdir');
            if(args.length==6)
            //     dir[1]=new String('/tmp/'+args[5]+args[0].substring(args[0].lastIndexOf('/')+1, args[0].lastIndexOf('.')));
            dir[1] = nString( '/home/sushanth/Desktop/myUtilities/NEW-UTILITIES/outputputfiles');

            else
dir[1] = nString( '/home/sushanth/Desktop/myUtilities/NEW-UTILITIES/outputputfiles');


//             dir[1]=new String('/tmp/'+args[6]+args[0].substring(args[0].lastIndexOf('/')+1, args[0].lastIndexOf('.')));
// System.out.println(dir[1]);
            rt.exec(dir);

            arr[0]=new String('/bin/cp');        
            for(int i=0;i<5;i++)     {
                System.out.println(names[i]+' '+diff[i]);
                arr[1]=new String('../class_one/'+args[0].substring(0,args[0].lastIndexOf('/')+1)+names[i]);

                if(i<10)
                arr[2]=new String(dir[1]+'/0'+i+'.jpg');
                else
                    arr[2]=new String(dir[1]+'/'+i+'.jpg');
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[2]);

                rt.exec(arr);
            }    
           
        }
        catch(Exception e)
        {
            e.printStackTrace();
            System.exit(0);
        }
    }
}
You are on page 1 of 2, other pages: [1] 2

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: