I have developed the below program but it is throwing null pointer exception.
Below is the model class..
public class Circle {
private int Id;
public Circle(int id, String name) {
super();
Id = id;
this.name = name;
}
private String name;
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Below is the dao class..
public class jdbcdaoimpl {
public Circle getCircle(int circleId)
{
Circle circle = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","saral","saral");
PreparedStatement stmt=con.prepareStatement("select * from CIRCLE where id = ?");
stmt.setInt(1,circleId);
ResultSet rset=stmt.executeQuery();
while(rset.next())
{
circle= new Circle(circleId, rset.getString("name") );
}
rset.close();
stmt.close();
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return circle;
}
}
and finally the main class..
public class jdbcDemo {
public static void main(String[] args) {
Circle c = new jdbcdaoimpl().getCircle(1);
System.out.println(c.getName());
}
}
please advise as on execution of main class it is throwing the null pointer exception.
You are swallowing all exceptions in the DAO method. It returns
null. It will also returnnullif the query simply returns an empty result.You also fail to
closeyour resources in afinally. You must propagate your exceptions, not catch them without handling.