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 7 of 7

Thread: NullPointerException Error

  1. #1
    Junior Member
    Join Date
    Oct 2012
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default NullPointerException Error

    Hey Guys,

    Im new to Java programming,
    I just got this annoying error and I really dont know how to solve it,
    What I am making is a basic program, which has an array of class object,
    So that I cant store a students name and age in each one,

    Then search through the array for a specific name, or even display the whole array,

    Now,
    The program is working almost 100%,
    I can search through the array and also display it all,

    But my problem is when it has finished displaying I get this NullpointerException error,

    This is my code,

    MAIN CLASS
    import java.util.Scanner;
     
    public class TestStudent
    {
    	public static void main(String[] args)
    	{
    		Scanner sc = new Scanner(System.in);
    		Student[] s = new Student[50];
    		int i = 0;
     
     
    		while(true)
    		{
    		System.out.println("\nStudent Registration");
    		System.out.println("\n\nPlease Select From Menu: \n1)Add \n2)Display \n3)Search 4)Exit");
    		System.out.print("\nEnter Choice: ");
    		int choice = sc.nextInt();
    		switch(choice)
    		{
    			case 1:
    				if(i == 50)
    					{
    						System.out.println("Student Database Is Full!!");
    					}
    					else
    					s[i] = new Student();
    					System.out.print("Enter Student Name: ");
    					String studentName = sc.next();
    					s[i].setName(studentName);
    					System.out.print("Enter Student Age: ");
    					int studentAge = sc.nextInt();		
    					s[i].setAge(studentAge);
    					i++;
    					break;
     
    			case 2:
     
    					for (i = 0; i < s.length; i++)
    					{
    					System.out.println("Student Name: "+s[i].getName());					
    					System.out.println("Student Number: " +s[i].getAge());											
    					}
    					break;
     
    			case 3:
    					System.out.print("\n\nPlease enter a name to find "); 
    					String search = sc.next();
     
    					for (i = 0; i < s.length; i++) 
    						{
    							if (search.equals(s[i].getName())) 
    							{
    							int z = i;
    							System.out.println("The Student " + s[z].getName() + " Was Found!\n " + "Student Age: " + s[z].getAge());
    							}
    							else
    							{
    							System.out.print("Record Not Found!");
    							}
    						}
     
    					break;
     
    			case 4:
     
     
    					break;
     
    			default:
    					System.out.println("Wrong Value Entered:");
    		}
     
     
     
    		}
     
     
    	}
    }

    CLASS OBJECT
    public class Student
    {
    	private int stuAge;
    	private String stuName;
     
    	public void setName(String name )
    	{					
    		stuName = name;	
    	}
     
    	public void setAge(int age)
    	{
     
    		stuAge = age;	
     
    	}
     
    		public String getName()
    	{
    		return stuName;
    	}
     
    	public int getAge()
    	{
    		return stuAge;
    	}
     
    }
    If someone could help me I would be SOOOOOOOOOOOOOOOOO Happy,
    This is doing my head in >"<..

    I know my programming skills are not great and this could be made better,
    but Im new,

    I am welcome to any feedback,

    and thanks in advance!
    Last edited by pbrockway2; October 17th, 2012 at 04:31 PM. Reason: code tags added


  2. #2
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    939
    Thanks
    6
    Thanked 202 Times in 178 Posts

    Default Re: NullPointerException Error

    Hi TaoNinja, welcome to the forums!

    I have added "code" tags to your post. The idea is that you put [code] at the start of any code and [/code] at the end: that way the formatting is preserved by the forum software and the code is readable. It is also a good idea to use spaces rather than tabs to indent code as the latter can be rather wide when rendered by a web browser.

    To begin figuring out why you get a null pointer exception we'll have to be clear about where this exception is occurring. Post the entire stack trace you get (the thing that starts by reporting a NullPointerException and then follows with a number of lines saying which lines of code were involved.)

  3. #3
    Junior Member
    Join Date
    Oct 2012
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: NullPointerException Error

    Quote Originally Posted by pbrockway2 View Post

    To begin figuring out why you get a null pointer exception we'll have to be clear about where this exception is occurring. Post the entire stack trace you get (the thing that starts by reporting a NullPointerException and then follows with a number of lines saying which lines of code were involved.)
    Hi there,

    Thanks for that, I was not sure how to embed the code in those boxes to make the code easier to read,

    The error i get is as follows;

    Exception in thread "main" java.lang.NullPointerException at TestStudent.main(TestStudent.java:51)

    Hope this helps!

    Thanks again!

  4. #4
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    939
    Thanks
    6
    Thanked 202 Times in 178 Posts

    Default Re: NullPointerException Error

    Exception in thread "main" java.lang.NullPointerException at TestStudent.main(TestStudent.java:51)
    I'm guessing that line 51 is this one:

    if (search.equals(s[i].getName()))

    Now you will get a null pointer exception whenever you try and use a variable (or other expression) as if it had a non null value when it is really null. There are a couple of ways that this commonly happens: calling methods, and accessing arrays.

    String[] arr;
    System.out.println(arr[0]); // bad! arr is null
     
    arr = new String[42];
    System.out.println(arr[0].length()); // bad! arr has a value, but can't call length() when arr[0] is null
     
    arr[0] = "foo";
    System.out.println(arr[0].length()); // :) prints 3. arr has a value, and arr[0] has a value

    Going back to your case we see that there are three things that could be null: search, s and s[i]. You can figure out which is the culprit by using System.out.println();

    System.out.println("About to test name against search");
    System.out.println("search=" + search);
    System.out.println("s=" + s);
    System.out.println("s[i]=" + s[i]);
    if (search.equals(s[i].getName()))
    {
        int z = i;
        // etc

    Once you have figured out which thing is null go back through your code to where you thought you had assigned it a non null value and try to think about why that didn't happen.

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

    Default Re: NullPointerException Error

    In which case num is null. The best way to avoid this type of exception is to always check for null when you did not create the object yourself. So doSomething should be re-written as
    Follow this syntax for it
    public void doSomething(Integer num){
    if(num != null){
    //do something to num
    }
    }

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

    Default Re: NullPointerException Error

    Hi,

    if as you say, the exception occurs after it has displayed the results successfully, I would suggest you check the Student.getName and Student.getAge methods, since these are the methods you have called in the display and search options. If you post the source for this class, I can help you further.

    rgds.

  7. #7
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    939
    Thanks
    6
    Thanked 202 Times in 178 Posts

    Default Re: NullPointerException Error

    @chetanaegis: I don't think there is a num in the OP's code. And I wonder if the claim that it is best to always check explicitly for null might be a little extravagant. Sometimes if a variable is null, that indicates a real problem somewhere: a faulty assumption we have made. In short, a bug. Surrounding that bug in a protective if statement will just let it breed.

    Rather, the bug ought to be found, caught and fixed. And sometimes that means a method like your doSomething() will do absolutely nothing but throw a NullPointerException. And it needn't even do that explicitly, it might be enough to let the NPE happen as part of its normal operation. From doSomething()'s point of view there is little it can do (the problem occurred elsewhere) and little it ought to do (for fear of masking the problem).

    To make this more concrete, I would code your example as:

        /**
         * Does something with a non zero integer.
         * @param  num  the integer to which something is done
         * @throws NullPointerException if the supplied argument is null
         * @throws ArithmeticException if the supplied argument is zero
         */
    public void doSomething(Integer num) {
         // code here, eg
        System.out.println(1 / num);
    } 
     
        /**
         * Does something with a non zero integer.  If a null argument is used (or an argument with
         * value zero) then 1 will be used.
         * @param  num  the integer to which something is done
         */
    public void doSomethingEx(Integer num) {
        if(num == null || num == 0) {
            num = new Integer(1);
        }
         // code here, eg
        System.out.println(1 / num);
    } 
     
        /**
         * Sets some field to a non zero integer.
         * @param  num  the value to be used
         * @throws IllegalArgumentException if the supplied argument does not specify a nonzero integer
         */ 
    public void setSomething(Integer num) {
        if(num == null || num == 0) {
            throw new IllegalArgumentException(
                    "setSomething() wants a nonzero integer, not " + num);
        }
        // code here, eg
        myNum = num;
    }

    Mind the javadocs! Sometimes an explicit if statement is called for, sometimes not. (doSomethingEx() is a sort of middle ground where its debatable. Perhaps it makes the method unnecessarily complex.)

    Our programs shouldn't be minefields with null pointer exceptions as something to be "avoided". When writing a program an NPE should be welcomed - as an old friend! - because of the information it, and its associated stack trace provides. This was the burden of my posts above.

    @patrick.thomas58: On the contrary, if the results have displayed "successfully" (=="the OP saw the data he or she expected"), that would seem to give a clean bill of health to the getter methods that provided the information. (The OP did post that code.) Better, I think, to start by determining exactly what expression was null. (as in #4)

    @world: NPE's are more like mayflies or wild flowers than they are like elephants. By those standards this thread is old. The original problem, defunct. (Cue, parrot.)
    Last edited by pbrockway2; December 21st, 2012 at 03:52 PM. Reason: fixed cut-n-paste errors in the cpde

Similar Threads

  1. Error, NullPointerException
    By alex067 in forum What's Wrong With My Code?
    Replies: 15
    Last Post: October 14th, 2012, 09:05 AM
  2. NullPointerException Error in Code that Prints Array Elements
    By Atypically Engineered in forum Collections and Generics
    Replies: 8
    Last Post: April 6th, 2012, 10:21 PM
  3. NullPointerException Error
    By nicsa in forum Exceptions
    Replies: 6
    Last Post: November 19th, 2011, 04:32 PM
  4. NullPointerException error
    By pyrotecc25 in forum What's Wrong With My Code?
    Replies: 7
    Last Post: April 14th, 2011, 01:17 PM
  5. NullPointerException error
    By blazerix in forum What's Wrong With My Code?
    Replies: 7
    Last Post: January 24th, 2011, 08:59 PM