Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: NullPointerException Error in Code that Prints Array Elements

  1. #1
    Junior Member
    Join Date
    Apr 2012
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default NullPointerException Error in Code that Prints Array Elements

    I created the ArrayDriver and ArrayClass1 classes to gain some experiences working with arrays and array elements. The code in ArrayDriver is suppose to:
    1) Create an array of ArrayClass1 objects.
    2) Initialize the two attributes of each array element to 0 and print this information out.
    3) Modify each array element's attribute and print out the modified array element's attributes.

    I encountered a Nullpointerexception error while compiling the ArrayDriver class with Eclipse. I read that this error occurs when a pointer is dereferenced but has not been instantiated (java - What is a Null Pointer Exception? - Stack Overflow). I created an array and initialized every array element with the first for loop. Still, I cannot correct the problem.

    public class ArrayDriver {
    	public static void main(String[] args){
     
    		int ARRAY_LENGTH = 10;
     
    		ArrayClass1 [] alpha = new ArrayClass1[ARRAY_LENGTH];    //Declares and instantiates the ArrayClass1 array called alpha
     
    		for(int i = ARRAY_LENGTH-1; i-1>=0; i--){   //Initializes the attributes of each alpha array element (both x and y) to 0
    			alpha[i].x = 0;
    			alpha[i].y = 0;
    		}
     
     
    		for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){   //Print out what is initialized
    			System.out.println("Old Array["+i+"]x: "+alpha[i].x);
    			System.out.println("Old Array["+i+"]y: "+alpha[i].y);
    		}
            for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){   //Modifies each array element's attributes
            	alpha[i].x = i;
            	alpha[i].y = i+1;
            }
            for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){   //Prints out new attributes
            	System.out.println("New Array["+i+"]x: "+alpha[i].x);
            	System.out.println("New Array["+i+"]y: "+alpha[i].y);
            }
     
     
     
    	}
    }

    Array Class:
    public class ArrayClass1 {
     
    	public int x = 0;
    	public int y = 0;
     
    	public ArrayClass1(int x, int y){
    	 this.x = x;
    	 this.y = y;
    	}
     
    }


  2. #2
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: NullPointerException Error in Code that Prints Array Elements

    The NullPointerExpression will occur when you run the program. (Just a nitpick, but it pays to be precise...)

    Could you post the stack trace: the long message that you get at the console when an exception occurs? And indicate which line(s) of your code it is referring to?

  3. #3
    Member
    Join Date
    Jan 2012
    Location
    Hellas
    Posts
    284
    Thanks
    11
    Thanked 59 Times in 57 Posts

    Default Re: NullPointerException Error in Code that Prints Array Elements

    Quote Originally Posted by Atypically Engineered View Post
    I created the ArrayDriver and ArrayClass1 classes to gain some experiences working with arrays and array elements. The code in ArrayDriver is suppose to:
    1) Create an array of ArrayClass1 objects.
    2) Initialize the two attributes of each array element to 0 and print this information out.
    3) Modify each array element's attribute and print out the modified array element's attributes.

    I encountered a Nullpointerexception error while compiling the ArrayDriver class with Eclipse. I read that this error occurs when a pointer is dereferenced but has not been instantiated (java - What is a Null Pointer Exception? - Stack Overflow). I created an array and initialized every array element with the first for loop. Still, I cannot correct the problem.

    public class ArrayDriver {
    	public static void main(String[] args){
     
    		int ARRAY_LENGTH = 10;
     
    		ArrayClass1 [] alpha = new ArrayClass1[ARRAY_LENGTH];    //Declares and instantiates the ArrayClass1 array called alpha
     
    		for(int i = ARRAY_LENGTH-1; i-1>=0; i--){   //Initializes the attributes of each alpha array element (both x and y) to 0
    			alpha[i].x = 0;
    			alpha[i].y = 0;
    		}
     
     
    		for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){   //Print out what is initialized
    			System.out.println("Old Array["+i+"]x: "+alpha[i].x);
    			System.out.println("Old Array["+i+"]y: "+alpha[i].y);
    		}
            for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){   //Modifies each array element's attributes
            	alpha[i].x = i;
            	alpha[i].y = i+1;
            }
            for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){   //Prints out new attributes
            	System.out.println("New Array["+i+"]x: "+alpha[i].x);
            	System.out.println("New Array["+i+"]y: "+alpha[i].y);
            }
     
     
     
    	}
    }

    Array Class:
    public class ArrayClass1 {
     
    	public int x = 0;
    	public int y = 0;
     
    	public ArrayClass1(int x, int y){
    	 this.x = x;
    	 this.y = y;
    	}
     
    }
    Hello Atypically Engineered!
    Your first for loop does not initialize your alpha array, you assign values to alpha[i].x and alpha[i].y. You should give values to alpha[i].
    Here is a typical example for initializing an int array
    int[] x = new int [10];
      for (int i = 0; i<x.length; i++ )
      x[i] = i;
      }

  4. #4
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: NullPointerException Error in Code that Prints Array Elements

    Nice link, by the way.

    Near the bottom - and garnering zero votes - we read:

    "In Java every things is in the form of class.

    If you want to use any object then you have two phases

    Declare
    Initialization
    Example:

    Declaration: int a;
    initialization: a=0;

    Same for Array concept

    Declaration: Item i[]=new Item[5];
    Initialization: i[0]=new Item();

    If you not given Initialization section then the NullpointerException arise."

  5. The Following User Says Thank You to pbrockway2 For This Useful Post:

    Atypically Engineered (April 6th, 2012)

  6. #5
    Junior Member
    Join Date
    Apr 2012
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: NullPointerException Error in Code that Prints Array Elements

    Aha! Along the lines with what andreas90 said, I did not initialize the arrays. The full stack trace was:

    Exception in thread "main" java.lang.NullPointerException
    at ArrayDriver.main(ArrayDriver.java:13)

    Line 13 is the alpha[i].x = 0 line. NullPointerException occurred when java executed the code and tried to assign values to the array elements before initializing them. Would this imply that when an array of whatever object is declared, each array element is initialized to null by java? (Or is this true only for arrays of user-defined classes? Or is it true for all declared but user-uninitialized statements?

    It seems that I confused declaring and initializing the array with initializing the array elements. But if "alpha[i] = new ArrayClass1(0,0);" initializes each element, then why didn't I get an error when I ran:
    public class ArrayDriver {
    	public static void main(String[] args){
     
    		int ARRAY_LENGTH = 10;
     
    		ArrayClass1 [] alpha = new ArrayClass1[ARRAY_LENGTH];    //Declares and instantiates the ArrayClass1 array called alpha
     
    		for(int i = ARRAY_LENGTH-1; i-1>=0; i--){   //Initializes the attributes of each alpha array element (both x and y) to 0
    			alpha[i] = new ArrayClass1(0,0);
    			alpha[i] = new ArrayClass1(0,0);
    		}
     
     
    		for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){   //Print out what is initialized
    			System.out.println("Old Array["+i+"]x: "+alpha[i].x);
    			System.out.println("Old Array["+i+"]y: "+alpha[i].y);
    		}
            for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){   //Modifies each array element's attributes
            	alpha[i].x = i;
            	alpha[i].y = i+1;
            }
            for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){   //Prints out new attributes
            	System.out.println("New Array["+i+"]x: "+alpha[i].x);
            	System.out.println("New Array["+i+"]y: "+alpha[i].y);
            }
     
     
     
    	}
    }

    since I initialized alpha[i] = new ArrayClass1(0,0); multiple times?
    Last edited by Atypically Engineered; April 6th, 2012 at 07:34 PM.

  7. #6
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: NullPointerException Error in Code that Prints Array Elements

    Would this imply that when an array of whatever object is declared, each array element is initialized to null by java? (Or is this true only for arrays of user-defined classes? Or is it true for all declared but user-uninitialized statements?
    When you declare a variable of an array type ("Foo[] fooArr;") it will have the value null. (But in a method or constructor you simply can't use a variable you have declared there before it is initialised: that's a compile time error.)

    When you initialise the variable of type array ("fooArr = new Foo[10]") its elements will all be null. But arrays of primitive things *do* get values which makes sense because they certainly can't be null.

    It follows that the initialisation of the array elements is a second operation. Unless you use a shorthand like String[] strArr = new String[]{"fee", "fie", "foe", "fum"};

    User defined classes are like every other sort of class.

    Maybe all this is easier to see in code. The commented out lines are intended to be uncommented so you can watch the ensuing carnage. (Posted as an example of the sort of experiment you can perform to answer/test your own questions/hypotheses).

     
    public class WhatsMyValue {
        private int[] intArr;
        private Object[] obArr;
     
        public static void main(String[] args) {
            int[] bad;
                // won't compile: "The local variable bad may not have been initialized"
            //System.out.println(bad); 
     
            WhatsMyValue test = new WhatsMyValue();
     
                // array variables have value null
            System.out.println("intArr=" + test.intArr);
            System.out.println("obArr=" + test.obArr);
     
                // won't run: "NullPointerException", intArr is null so can't use []
            //System.out.println("intArr[0]=" + test.intArr[0]); 
     
            test.intArr = new int[10];
            test.obArr = new Object[10];
     
                // once the arrays are initialised the values are null or zero or false
            System.out.println("intArr[0]=" + test.intArr[0]);
            System.out.println("obArr[0]=" + test.obArr[0]);
     
                // won't run: "NullPointerException", obArr[0] is null so can't use methods
            //System.out.println("obArr[0].hashCode()=" + test.obArr[0].hashCode());
     
            for(int ndx = 0; ndx < test.obArr.length; ndx++) {
                test.obArr[ndx] = new Object();
            }
                // all good now: obArr *and* obArr[0] are initialised
            System.out.println("obArr[0].hashCode()=" + test.obArr[0].hashCode());
        }
    }

    I haven't read the rest of your post yet. Maybe this answers it.
    Last edited by pbrockway2; April 6th, 2012 at 08:25 PM. Reason: typo in code comment

  8. #7
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: NullPointerException Error in Code that Prints Array Elements

    It seems that I confused declaring and initializing the array with initializing the array elements.
    Yes, exactly.

    But if "alpha[i] = new ArrayClass1(0,0);" initializes each element, then why didn't I get an error when I ran...
    Where would you expect the error? The point is you *did* initialise both alpha and each of the alpha[i] elements. Everything initialised == no NullPointerException.

    Oddly, you did assign values to alpha[i] twice. We call the first assignment "initialisation", but that's just terminology. You are free to assign as many things as you like to alpha[i] - the old values are simply discarded. (which is why it is odd to make two such assignments).

  9. #8
    Junior Member
    Join Date
    Apr 2012
    Posts
    5
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: NullPointerException Error in Code that Prints Array Elements

    Don't compilers fail to compile whenever you reinitialize the same declared pointer? Say:
    Int x = 0;
    Int x = 1;

    Would give an error along the lines of "x is already defined. Is that because here "x" is being re-declared whereas

    alpha[i] = new ArrayClass1(0,0);
    alpha[i] = new ArrayClass1(1,1);

    is analogous to an assignment after int x; :
    x = 0;
    x = 1;

  10. #9
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: NullPointerException Error in Code that Prints Array Elements

    Yes, you can't declare a variable twice.

    But in the code you were asking about (#5) only one variable is declared (other than the loop variables): alpha. And it is declared just once.

    The expression alpha[i] is not declared at all (expressions never are). And you are free to assign things to it as often as you like.

Similar Threads

  1. [SOLVED] How To Increment Array Elements
    By Nuggets in forum Java Theory & Questions
    Replies: 15
    Last Post: April 1st, 2012, 12:10 PM
  2. Missing elements in array
    By frozen java in forum What's Wrong With My Code?
    Replies: 6
    Last Post: February 10th, 2012, 11:52 PM
  3. Replies: 3
    Last Post: December 7th, 2011, 02:03 AM
  4. Help with code that prints number of evens, odds, and 0's
    By trogan234 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 2nd, 2011, 06:50 PM
  5. nothing prints after runing code
    By darego in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 11th, 2011, 11:14 AM