473,320 Members | 1,958 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Can someone tell why my program is showing null pointer exception at line 33

Hii,I was trying to solve a problem but i don't get why my program is showing null pointer exception on the commented line.Can someone explain the reason.
Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2. class cod1{
  3.         public static void main(String args[]) throws java.lang.Exception
  4.         {
  5.                 int t,i,n,j,k,p,q,r;
  6.                 int[] a =new int[100000];
  7.                 Scanner s = new Scanner(System.in);
  8.                 t=s.nextInt();
  9.                 for(i=0;i<t;i++)
  10.                 {
  11.                         p=0;
  12.                         n= s.nextInt();
  13.                         ArrayList<Object>[] al = (ArrayList<Object>[])new ArrayList[n+1];
  14.                         for(j=0;j<n;j++)
  15.                         {
  16.                                 a[j]=s.nextInt();
  17.                         }
  18.                         int c;
  19.                         for(j=0;j<n;j++)
  20.                         {
  21.                                 c=0;
  22.                                 for(k=0;k<p;k++)
  23.                                 {
  24.                                          if(al[k].size()-1>a[j])
  25.                                         {
  26.                                                 al[k].add(a[j]);
  27.                                                 c++;
  28.                                                 break;
  29.                                         }
  30.                                 }
  31.                                 if(c==0)
  32.                                 {
  33.                                         al[p++].add(a[j]);//null pointer exception 
  34.                                 }
  35.                         }
  36.                         for(j=0;j<p;j++)
  37.                         {
  38.                                 System.out.println(al[j].size()-1);
  39.                         }
  40.                 }
  41.         }
  42. }
  43.  
  44.  
  45.  
Sep 21 '15 #1
7 1461
chaarmann
785 Expert 512MB
Because a[j] is null,
and al[k].add(null) then throws this exception:
it is not allowed to add a null to this ArrayList<Object>(). You specified in the generics that it accepts only Object.
Always check for null before trying to add.
Or use ArrayList() without generics, then you can store a null there.
Sep 21 '15 #2
but i gave the input to a[j]
Sep 21 '15 #3
chaarmann
785 Expert 512MB
First of all, you should always first check with s.hasNextInt() before calling s.nextInt().

So you are right, the value of a[j] cannot be null because it's a primitive type, an "int" (sorry, I overlooked that).
Then the reason might be that your array list "al", your "ArrayList<Object>()" can only store Objects and no primitive types.

You can wrap a primitive type "int i" into an object "Integer" before storing it into "al" via "Object object = new Integer(i)". Maybe that helps.

Or much better: declare your "al" as ArrayList<Integer>(), then autoboxing will take over this job.
Sep 22 '15 #4
Same error occurs after replacing object with integer
Sep 22 '15 #5
chaarmann
785 Expert 512MB
And what happens if you also wrap it as proposed? That means, do both?
That means replace the line with the nullPointerException through:
Expand|Select|Wrap|Line Numbers
  1. al[p++].add(new Integer(a[j]));
Also change line 13 from ArrayList<Object>() to ArrayList<Integer>(), that means:
Expand|Select|Wrap|Line Numbers
  1. ArrayList<Integer>[] al = (ArrayList<Integer>[])new ArrayList[n+1];

By the way, shouldn't the arrayList size be "n" instead of "n+1"? I mean, if you are entering "1", then you create an array of size 2, with a[0] and a[1] as its elements ???
Sep 22 '15 #6
I got a doubt after you say,can you tell why the same error appears in the below code.

Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2. class w1{
  3.         public static void main(String args[]) throws java.lang.Exception
  4.         {
  5.                 int n=0;
  6.                 ArrayList<Integer>[] al = (ArrayList<Integer>[])new ArrayList[n+1];
  7.                 al[0].add(5);
  8.         //      al[1].add(6);
  9.                 System.out.println(al[0].get(1));
  10.         //      System.out.println(al[1].get(0));
  11.         }
  12. }
  13.  
Sep 22 '15 #7
chaarmann
785 Expert 512MB
Sorry for the misinformation. I really should have run your code to see where the nullPointerException occurs.
The nullPointerException occurs, because al[p] is null (and not the value given to the add-method what I assumed wrongly)
You can see that if you add following line right before the error at line 33:
Expand|Select|Wrap|Line Numbers
  1. System.out.println("al length=" + al.length + " p=" + p + ((p < al.length) ? " al[p]=" + al[p] : " invalid index"));
The output is:
Expand|Select|Wrap|Line Numbers
  1. al length=3 p=0 al[p]=null
That means, you have defined an array of arrayLists.
But you have not initialized its content, that means you have not put anything inside your array of arrayLists. There is everywhere "null" inside. You should put empty arrayLists inside to initialize its content (after line 13):
Expand|Select|Wrap|Line Numbers
  1.         for(int index = 0;index < al.length;index++)
  2.         {
  3.                 al[index]=new ArrayList<Object>();
  4.         }
  5.  
Try it and see that your null pointer exception is away. (but it can have IndexOutOfBounds-Exception if "p" is equal or bigger than the given array size n+1)


In my understanding that's a design error. You only wanted a single arrayList.
if that assumption is correct, then you should use in line 13:
Expand|Select|Wrap|Line Numbers
  1. ArrayList<Object> al = new ArrayList<Object>();
And then in line 33:
Expand|Select|Wrap|Line Numbers
  1. al.add(new Integer(a[j]));
Sep 23 '15 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: jennifer johnson | last post by:
Hello All, I appreciate anyone's assistance. I wanted to validate user customizable field values so I changed my JSP page so that the form action would post existing form - action=<%=...
1
by: Mark | last post by:
Hi, I'm writing user controls with custom events. I have a parent custom event that exposes some abstract methods and some custom events. I have also created some new user controls that...
5
by: Tony Cheng | last post by:
for (int i=0; i<_request.Form.Count; i++ ) { string key = _request.Form.GetKey(i); if ( !key.Equals("formCode") && !key.Equals("formLanguage") && !key.Equals("__VIEWSTATE") &&...
1
by: zahidkhan | last post by:
Hi All, Plz help me if you can..... I have a program something like this int main(int argc,char* argv) { try { int* p = NULL;
1
by: MRamaLakshmi | last post by:
hi, I am developing an application using Java Applet which will be uploading files. Its throwing Null Pointer exception while detecting the proxy when we are trying to load the applet using Java6....
5
by: iamdennisthomas | last post by:
Hi Guys i was developing a action servlet which is actulally getting the data from a form and putting it in the db but while executing i am getting a null pointer exception /* * Generated by...
6
by: swathi amireddy | last post by:
Currently im trying to migrate a project from .net 1.1 to 2.0.While running the application its giving an exception for the below code while doing the update operation: protected void...
1
by: Riteshti | last post by:
Im trying this java code to export data from database using sql query, But getting a null pointer exception. getting no clue to remove it . Im getting this exception at line no 26. try { ...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.