• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why Null Pointer Exception?

 
Tony Shivpershad
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.io.*;
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();
try{
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")){
theList.add(str);
}
}
}

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

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

}
 
Ryan McGuire
Ranch Hand
Posts: 1069
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
TreeSet theList = new TreeSet();
try{
String line = null;
theList = null;


This section should read:

TreeSet theList = null;
try{
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
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thanks,
Tony
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic