File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Why Null Pointer Exception? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why Null Pointer Exception?" Watch "Why Null Pointer Exception?" New topic

Why Null Pointer Exception?

Tony Shivpershad

Joined: Sep 27, 2005
Posts: 18
Howdy y'all,

Trying to learn java is very frustrating!
In the code below I am getting a NullPointerException when I call the size method on the returned TreeSet (second last line). Please shed some light for me. Thanks in advance.

import java.util.*;
import java.text.*;

public class Directories2{
// Read the list of directories to populate the jList dialog
String str = new String();
BufferedReader br = null;
public TreeSet getDirName(){
TreeSet theList = new TreeSet();
String line = null;
theList = null;
File inputFile = new File("G:\\E-biz\\Technology Team\\Postal Codes\\Data\\input\\pcfiledirs.txt");
br = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile)));
while ((line = br.readLine())!=null)
//str = br.readLine();

// System.out.println(line);
if (str.startsWith("20")){

catch (IOException e) {
System.err.println("Caught IOException: "
+ e.getMessage());
return theList;

public static void main(String[] args) {
Directories2 a = new Directories2();
System.out.println ("size " + a.getDirName().size());
System.out.println ("Done");

Ryan McGuire
Ranch Hand

Joined: Feb 18, 2005
Posts: 1044
Quick answer without actually trying to fix it yet:

All you ever add to theList is str, and that's only if it starts with "20". The only value you ever assign to str is "new String()" (which doesn't start with "20"). Try adding line to theList instead.
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
TreeSet theList = new TreeSet();
String line = null;
theList = null;

This section should read:

TreeSet theList = null;
String line = null;
theList = new TreeSet();

theList.add(...) will fail with a NullPointerException if you set theList to null.
[ October 26, 2005: Message edited by: Ulf Dittmer ]
Tony Shivpershad

Joined: Sep 27, 2005
Posts: 18
Ryan and Ulf,

Thank you both for your replies. I have implemented both suggestions and the program now compiles and runs.

I apologise for not mentioning earlier that I am using jdk 1.3.

I agree. Here's the link:
subject: Why Null Pointer Exception?
It's not a secret anymore!