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

Thread: Getting a null pointer exception.

  1. #1
    Junior Member
    Join Date
    May 2012
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Getting a null pointer exception.

    Okay, I'm still learning programming, and I have this assignment where I have to create a class Message, which 4 instance variables: sender, receiver, subject and body. I have to implement a constructor that takes four parameters and initializes the attributes accordingly.

    I have to implement a method isValid() that returns true only if: the Message object on which the method is invoked has a non-empty sender and receiver, and at least one of the body or subject must be a non-empty string.

    Along with a toString() method. I understand all this, and here is my code so far. I have no idea what I am doing wrong.

    public class Message
    {
    	String sender;
    	String receiver;
    	String subject;
    	String body;
     
    	public Message(String sender, String receiver, String subject, String body)
    	{
    		this.sender = sender;
    		this.receiver = receiver;
    		this.subject = subject;
    		this.body = body;
    	}
     
    	public Message()
    	{
    		this.sender = null;
    		this.receiver = null;
    		this.subject = null;
    		this.body = null;
    	}
     
    	public static void main (String[] args)
    	{
    		Message trying = new Message();
    		trying.sender = "sendername";
    		trying.receiver = null;
    		trying.subject = "Hi";
    		trying.body = null;
     
    		System.out.println(trying);
    		System.out.println(trying.isValid());
    	}
     
    	public boolean isValid ()
    	{
    		boolean flag = false;
     
    		if (sender.length() > 0 && receiver.length() > 0)
    			flag = true;
    			if(subject.length() >0 || body.length()>0)
    				flag = true;
    				else
    					flag = false;
     
    		return flag;
    	}
     
    	public String toString()
    	{
    		return ("From: " + sender + "\n" + "To: " + receiver + "\n" + "Subject: " + subject + "\n" + "Body: " + body);
    	}
    }

    When I run this, I get a runtime exception (it compiles, but when I run) I get this:
    Exception in thread "main" java.lang.NullPointerException
    at Message.isValid(Message.java:40)
    at Message.main(Message.java:33)


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Getting a null pointer exception.

    Something is null on that line listed in the Exception stack trace...step through the code and think about what is set to null (null is just that - you cannot call methods on a null reference)

  3. The Following User Says Thank You to copeg For This Useful Post:

    Ouzi (May 15th, 2012)

  4. #3
    Junior Member
    Join Date
    May 2012
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Getting a null pointer exception.

    Yeah, I understand that a null pointer exception is that when I try to invoke a method on a non-existing object, but I created my object, and when I output it, it works ...
    Nevermind, I changed that isValid() method to the following and it works:

    public boolean isValid ()
    	{
    		if (this.sender.length() > 0 && this.receiver.length() >0)
    			flag = true;
    				if (this.subject.length() < 0 || this.body.length() <0 )
    					flag = false;
     
    		return flag;
    	}
    of course I added,
     static boolean flag = false;
    to my instance variables.

  5. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Getting a null pointer exception.

    To further elaborate on copeg's post, the .length() method throws a Null Pointer when you invoke it on a null. I'm not entirely sure what line 40 is, but this is an indication that either sender and/or receiver OR subject and/or body is null.

    Hopefully that will help you narrow down your search.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  6. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Ouzi (May 15th, 2012)

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

    Default Re: Getting a null pointer exception.

    Hello Ouzi!
    When you get an NPE you should print the variables in the line that the exception tells you to find which of them is null, and then you can find out why it is null.
    Here the problem is that you are trying to get receiver.length(), but receiver is null (i.e. you are trying to take an attribute of something that doesn't exist). Therefore a NPE is thrown.
    In your case, you can test if the receiver (or sender) is null because -I repeat in your case- a 0-length reciever is the same as no receiver (null).
    Hope it helps.

  8. The Following User Says Thank You to andreas90 For This Useful Post:

    Ouzi (May 15th, 2012)

  9. #6
    Junior Member
    Join Date
    May 2012
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Getting a null pointer exception.

    Quote Originally Posted by andreas90 View Post
    Hello Ouzi!
    When you get an NPE you should print the variables in the line that the exception tells you to find which of them is null, and then you can find out why it is null.
    Thank you so much for this, I will take that into consideration if I ever face a NPE. However when I updated the isValid() method, the exception was gone, which is weird. I used the same technique more or less. Comparing sender.length() while being empty and it ran and gave a correct output.

  10. #7
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Getting a null pointer exception.

    Nevermind, I changed that isValid() method to the following and it works:
    Based upon the initial code you posted that should still throw the exception as you set receiver to null, then call length() on that reference, so I suspect that is not all that changed

  11. #8
    Junior Member
    Join Date
    May 2012
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Getting a null pointer exception.

    That's the only thing I have changed, the code isn't working 100% as intended, still trying to figure out why ... Thing is, the method isValid() should check if the variable is empty or not, if its empty it should return false, and if its not empty it should return true.

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

    Default Re: Getting a null pointer exception.

    Quote Originally Posted by Ouzi View Post
    Thank you so much for this, I will take that into consideration if I ever face a NPE. However when I updated the isValid() method, the exception was gone, which is weird. I used the same technique more or less. Comparing sender.length() while being empty and it ran and gave a correct output.
    If the updated isValid() method is the one from post#3, I think it will still throw a NPE, unless you gave the reciever a non null value. I told you that in your case a null sender is the same with a 0-length one, because there can't be a number with no digits. But generally a 0-length String is different than a null String. Try the following;
    public class Test {
     
        public static void main(String[] args) {
            String s = "";
            String st = null;
            System.out.println(s.equals(st));
        }
    }

  13. #10
    Junior Member
    Join Date
    May 2012
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Getting a null pointer exception.

    public class Message
    {
    	String sender;
    	String receiver;
    	String subject;
    	String body;
    	static boolean flag = false;
     
    	public Message(String sender, String receiver, String subject, String body)
    	{
    		this.sender = sender;
    		this.receiver = receiver;
    		this.subject = subject;
    		this.body = body;
    	}
     
     
    	public static void main (String[] args)
    	{
    		Message one = new Message("Slim","Georg","","");
    		System.out.println(one);
    		System.out.println("\n");
    		System.out.println(one.isValid());
    	}
     
    	public boolean isValid ()
    	{
    		if (this.sender.length() > 0 & this.receiver.length() >0)
    		{
    			if (this.subject.length() > 0 || this.body.length() > 0 )
    					flag = true;
    		}
    		else
    			flag = false;
     
    		return flag;
    	}
     
    	public String toString()
    	{
    		return ("From: " + sender + "\n" + "To: " + receiver + "\n" + "Subject: " + subject + "\n" + "Body: " + body);
    	}
    }

    The output is as follows:

    --------------------Configuration: <Default>--------------------
    From: Slim
    To: Georg
    Subject:
    Body:


    false

    Process completed.

    Also: System.out.print(one.sender.length()); Outputs: 4.
    Last edited by Ouzi; May 15th, 2012 at 11:05 AM. Reason: Additional Line

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

    Default Re: Getting a null pointer exception.

    If I were you, I would first check for null and then length() > 0, to avoid a NPE.
    And also I would use the logical && instead of the bitwise & operator. They seem to work the same but they are quite different.

  15. #12
    Junior Member
    Join Date
    May 2012
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Getting a null pointer exception.

    Quote Originally Posted by andreas90 View Post
    If I were you, I would first check for null and then length() > 0, to avoid a NPE.
    And also I would use the logical && instead of the bitwise & operator. They seem to work the same but they are quite different.
    First, thank you for your continuous support And also, I need to check both conditions that's why i was using the & operator.

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

    Default Re: Getting a null pointer exception.

    Quote Originally Posted by Ouzi View Post
    And also, I need to check both conditions that's why i was using the & operator.
    Why you need to check both conditions?
    if (this.sender.length() > 0 & this.receiver.length() >0)
    If the first is false then the whole if will be false, thus there is no need to check the second one. This is what && does. It evaluates the left side of the operation, if it's true, it continues and evaluates the right side.
    And evaluations cost

  17. #14
    Junior Member
    Join Date
    May 2012
    Posts
    7
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Getting a null pointer exception.

    Ah, my understanding was that the && operator checks if the first condition is true, then it doesn't evaluate the other. But you and a friend of mine at university today, made it clear that this wasn't the case

    I need to check both conditions cause this is the assignment I have, I have to check that two fields aren't empty.

  18. #15
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Getting a null pointer exception.

    The || operator will check only the first condition if it is true. The && operator will check only the first condition if it is false.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

Similar Threads

  1. Null Pointer Exception?
    By SeanEE89 in forum What's Wrong With My Code?
    Replies: 10
    Last Post: November 16th, 2011, 06:21 PM
  2. Null Pointer exception
    By Demetrius82 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: June 2nd, 2011, 07:32 PM
  3. Null Pointer Exception Help !!
    By AlterEgo1234 in forum Member Introductions
    Replies: 1
    Last Post: March 27th, 2011, 10:07 AM
  4. Null Pointer Exception Help!!
    By puzzledstudent in forum What's Wrong With My Code?
    Replies: 5
    Last Post: November 11th, 2010, 06:46 PM
  5. Null Pointer Exception
    By MysticDeath in forum Exceptions
    Replies: 2
    Last Post: October 24th, 2009, 01:49 PM