Results 1 to 2 of 2
  1. #1
    Juuno is offline Member
    Join Date
    Feb 2009
    Posts
    18
    Rep Power
    0

    Default NullPointerException

    When I try to run this program, I got NullPointerException error at Line 11. Can anyone tell me how to fix it? Thanks.


    Java Code:
    public class Test {
    
    	int a;
    	int b;
    	
    	public static void main (String args[]){
    		int i = 0;
    		
    		Test [] obj= new Test[8];
    		obj[i].a = 1;
    		obj[i].b = 1;
    		
    		for (i=0; i<4; i++){
    			obj[i+1].a = obj[i].a + 5;
    			obj[i+1].b = obj[i].b + 10;
    		}
    		
    		for (i=0; i<4; i++){
    			System.out.println(obj[i].a);
    			System.out.println(obj[i].b);
    		}
    	}
    }

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,655
    Blog Entries
    7
    Rep Power
    21

    Default

    When you create an array of type Test[] you create an array of references that each can refer to a Test object, but they don't do it (yet) (they all are null); You have to make them refer to Test objects. e.g.

    Java Code:
    Test[] t= new Test[2]; // two references
    for (int i= 0; i < t.length; i++)
       t[i]= new Test(); // make it refer to a Test object
    kind regards,

    Jos

Similar Threads

  1. NullPointerException help?
    By fab5freddy in forum New To Java
    Replies: 2
    Last Post: 02-04-2010, 08:26 PM
  2. NullPointerException: I can't get rid of it.
    By mcashe in forum AWT / Swing
    Replies: 2
    Last Post: 08-17-2009, 09:16 PM
  3. NullPointerException
    By mjz in forum JDBC
    Replies: 1
    Last Post: 08-06-2009, 11:46 AM
  4. NullPointerException
    By mensa in forum Java 2D
    Replies: 5
    Last Post: 05-03-2008, 11:19 PM
  5. NullPointerException
    By ravian in forum New To Java
    Replies: 2
    Last Post: 12-07-2007, 04:20 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •