X Tutup
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Jeanne Boyarsky
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Ron McLeod
Saloon Keepers:
  • Tim Holloway
Bartenders:

Java NullPointerException while accessing ArrayList element

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi everyone,
I am a beginner learning Java and I’m facing an issue with an ArrayList.
I am getting a NullPointerException when trying to print elements.
What I am trying to do
Store student names in an ArrayList and print them using a loop.
Problem
The program compiles successfully but throws an exception at runtime.
My Code
Copy code
Java
 
Marshal
Posts: 82158
593
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What did you assign the ArrayList reference to?

Don't declare it as ArrayList<String>, but as List<String>. That allows you to use different types of List.
 
Bartender
Posts: 11218
91
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
On line 6 you assign null to names so when you try to access names on line 8 you get an exception.
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
names is null, it does not point to any object.  
you are trying to call a method on a null reference, which causes the exception at runtime.
Initialize the list properly
List<String> names = new ArrayList<>();
Now names refers to an actual object, so add() and the loop will work correctly.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic
X Tutup