1

(Background: My new senior developer wants to know my java skills, he gives me a program that cause an error. He wants me to explain why the error occurs and how to solve the error.

I run the program and I find the error is java.lang.NullPointerException, it also shows the stacktrace. From my knowledge (manbe I am wrong), usually the first message indicates the error occurs in which class, in my case, it shows

java.lang.NullPointerException at action.userMaint.AdminUserMaintAction.save(AdminUserMaintAction.java:301)

I ask the new senior developer for the source code because I want to view the code in the AdminUserMaintAction class

Before I post my question, I read this post What is a NullPointerException, and how do I fix it? about the error

I notice there are some other posts about this error, so roughly I know the null pointer exception because the object or something is null.

However, I still cannot figure out the how to solve the exception so I decide to post my question here)

Content

In AdminUserMaintAction class, I find the save() method. Here is the code.

public String save(){       
    String curloginId = (String) session.get("_loginid"); 
    funcid =1;

    AdmFunc admFunc = new AdmFunc();     
    admFunc.setCreatedBy(curloginId);
    admFunc.setCreatedDate(createdDate);
    admFunc.setFuncid(funcid);
    admFunc.setLoginid(curloginId);
    admFunc.setModifiedBy(curloginId);
    admFunc.setModifiedDate(modifiedDate);

    try {
        adminUserMaintService.insert(admFunc);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }                       
    return view2();     
}

From the stacktrace, the error occurs in this line

adminUserMaintService.insert(admFunc);

I find there a class called AdminUserMaintService class and the insert method is in there. Here is the code

public void insert(AdmFunc admFunc) throws SQLException{

    Connection conn = jdbcTemplate.getDataSource().getConnection();

     String sql = "INSERT INTO ADM_FUNC (LOGINID, FUNC_ID, CREATED_DATE, CREATED_BY, MODIFIED_DATE, MODIFIED_BY)  VALUES (NULL,NULL,NULL,NULL,NULL,NULL)";

    PreparedStatement pstmt = conn.prepareStatement(sql);

    pstmt.setString(1, admFunc.getLoginid());
    pstmt.setInt(2, admFunc.getFuncid());
    pstmt.setTimestamp(3, admFunc.getCreatedDate());
    pstmt.setString(4, admFunc.getCreatedBy());
    pstmt.setTimestamp(5, admFunc.getModifiedDate());
    pstmt.setString(6, admFunc.getModifiedBy());

    pstmt.execute();
}

I read the code and it seems fine and I don't know why it occurs error because there is no code indicates to return null value.

Also, there is one thing I don't understand in the AdminUserMaintService class, the insert method has hard code value such as "loginid", 3,"created by" and "modified by" and still get the null pointer exception?

I think the problem is in AdminUserMaintAction class as the stacktrace indicates the error in there

In AdminUserMaintAction class, I use System.out.println to print value in the code. Here is what I put in the code

public String save(){       
    String curloginId = (String) session.get("_loginid"); 

    funcid =1;

    AdmFunc admFunc = new AdmFunc();     
    admFunc.setCreatedBy(curloginId);
    admFunc.setCreatedDate(createdDate);
    admFunc.setFuncid(funcid);
    admFunc.setLoginid(curloginId);
    admFunc.setModifiedBy(curloginId);
    admFunc.setModifiedDate(modifiedDate);

    //I try to print values to see what values inside the code 
    System.out.println("admfunc.setFuncid is " + admFunc.getFuncid()); //it shows 1
    System.out.println("admfunc.setCreatedBy is " + admFunc.getCreatedBy() ); //it shows tester
    System.out.println("admfunc.setCreatedDate is " + new Timestamp(new Date().getTime()) ); //it shows today's date and time
    System.out.println("admfunc.setMofifiedBy is " + admFunc.getModifiedBy() ); //it shows tester
    System.out.println("admfunc.setModifiedDate is " +new Timestamp(new Date().getTime()) ); //it shows today's date and time
    System.out.println("admFunc value is" + admFunc);   //it shows jpa.AdmFunc@624c08e2
    System.out.println("start save ...");   
    System.out.println("");

    //adminUserMaintService.insert(admFunc); // I try this code and it occurs the same error
//  this.adminUserMaintService.insert(admFunc); // I try this code and it occurs the same error too

    try {
        adminUserMaintService.insert(admFunc);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("end save ...");
    return view2();

}

Also, I put hard code value in the insert method in AdminUserMaintService class.

public void insert(AdmFunc admFunc) throws SQLException{

    Connection conn = jdbcTemplate.getDataSource().getConnection();

     String sql = "INSERT INTO ADM_FUNC (LOGINID, FUNC_ID, CREATED_DATE, CREATED_BY, MODIFIED_DATE, MODIFIED_BY)  VALUES (NULL,NULL,NULL,NULL,NULL,NULL)";

    PreparedStatement pstmt = conn.prepareStatement(sql);

    pstmt.setString(1,"loginid"); 
    pstmt.setInt(2, 3);
    pstmt.setTimestamp(3,new Timestamp(new Date().getTime())); 
    pstmt.setString(4, "created by"); 
    pstmt.setTimestamp(5,new Timestamp(new Date().getTime()));  
    pstmt.setString(6, "modified by"); 

    pstmt.execute();

    try {
            conn.setAutoCommit(false);          

            pstmt.setString(1,"loginid"); 
            pstmt.setInt(2, 3);
            pstmt.setTimestamp(3,new Timestamp(new Date().getTime())); 
            pstmt.setString(4, "created by"); 
            pstmt.setTimestamp(5,new Timestamp(new Date().getTime()));  
            pstmt.setString(6, "modified by"); 

            pstmt.execute();
            conn.commit();

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            conn.rollback();
        } finally {
            pstmt.close();
            conn.setAutoCommit(true);
        }


}

However when I run the program, it still gives me the null pointer exception.

I used System.out.println to print something, I notice the value is not null. I don't understand why I get the exception, I hard coded the value in both AdminUserMaintAction and AdminUserMaintService class.

So I have some questions would like to ask here,

  1. Hard coded value is null? (from my knowledge, I don't think hard coded value equals to null, because use System.out.println can print the value. However in my case, it seems different, it still shows null pointer exception, indicate the location in action.userMaint.AdminUserMaintAction.save())

  2. Since I notice the stacktrace that indicate the exception occurs in action.userMaint.AdminUserMaintAction.save(), so I go to that class, that method to try to print value and I can see the value, so does that mean I can confirm the object is not null?

  3. If the object is not null, is there any way I can find out to solve the null pointer exception?

Thanks for your time.

Edit Thanks everyone's comments and answers, I notice adminUserMaintService is null and I put some some code it to make it not null. So when I run the code, although it still shows the null pointer exception, it shows the exception is in

Connection conn = jdbcTemplate.getDataSource().getConnection();

That means adminUserMaintService is not null at this moment.

So now I will study why the null pointer changes the location.

Thanks.

John
  • 13
  • 5
  • //adminUserMaintService.insert(admFunc); // I try this code and it occurs the same error // this.adminUserMaintService.insert(admFunc); // I try this code and it occurs the same error too ... well, duh, these lines are identical. it gives you "thé NPE"? on which line exactly? have you debugged it to check the values? – Stultuske Sep 27 '17 at 07:21
  • My first assumption would be that `adminUserMaintService` itself is null.. – daniu Sep 27 '17 at 07:22
  • I would guess that `adminUserMaintService` itself is null – Scary Wombat Sep 27 '17 at 07:23
  • Read https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it again. A NullPointerException doesn't happen because a methd returns null. It happens when you're trying to call a method (or access a field) on a null reference. So adminUserMaintService is null here. What insert() does is completely irrelevant. – JB Nizet Sep 27 '17 at 07:26
  • 1
    I hope you tell your senior developer that your Java skills are very poor, and that you submitted the code to SO for explanations. He's going to find it out on his own, so there's no use in lying. – Kayaman Sep 27 '17 at 08:19
  • @daniu, you're right. I notice `adminUserMaintService` is null and I will work on it. Thanks. – John Sep 27 '17 at 08:53
  • @ScaryWombat, you're right. I notice `adminUserMaintService` is null and I will work on it. Thanks. – John Sep 27 '17 at 08:54
  • 1
    @Kayaman, my senior developer suggests this site to me to learn and improve my java skills. And he agrees me to ask on this site so I don't think there is a lie between me and him. I know post the code in this site is not a good idea, I am new to this site and please forgive my ignorance. I will improve in the future. Thanks. – John Sep 27 '17 at 09:09

3 Answers3

1

If as you say line 301 in class AdminUserMainTAction is in fact

adminUserMaintService.insert(admFunc);

it means that adminUserMaintService is null. So adding code into AdminUserMainTService doesn't help much since the error occurs "before". Try to find out when the instance member adminUserMaintService is instantiated and how. It either never is instantiated or some factory method is used that itself returns null instead of an instance.

Lothar
  • 5,323
  • 1
  • 11
  • 27
  • You're right. I notice `adminUserMaintService` is null and I will work on it. Thanks. – John Sep 27 '17 at 08:54
0

Lets look into your exception stack trace fragment:

java.lang.NullPointerException at action.userMaint.AdminUserMaintAction.save(AdminUserMaintAction.java:301)

It means that:

  1. The exception occurred inside the action.userMaint.AdminUserMaintAction's method save()
  2. The exception was thrown at the 301st line in the class action.userMaint.AdminUserMaintAction

The java.lang.NullPointerException occurs then you invoke some class field on a variable with null pointer. So, in theory, you'd better to open the class action.userMaint.AdminUserMaintAction in an IDE or another text processor which numbers lines. It will help you to locate the exact code. It is hard to suggest more without additional info. But I suppose you hard coded the wrong code.

0

It is possible that there are mutilple exceptions wrapped in the stack trace. so you check the last 'caused by' stmt to point out the origin of npe.

L.H
  • 81
  • 6
  • I am sorry, would you please tell me what is `stmt` and `npe`? I look at the stack trace, only `service.aidw.AdminUserMaintService.insert` I can find in the source code, the rest I cannot find the source code. Thanks – John Sep 27 '17 at 09:14
  • I wanted to confirm if this is the only exception in the stacktrace. If you see only this detail, you may try debugging/printing the value of adminUserMaintService. If it prints null, then this service is causing the null pointer exception. – L.H Sep 27 '17 at 09:19
  • Thanks your reply. I guess this maybe the only exception in stacktrace because the error message just show `java.lang.NullPointerException ` and no other exceptions. – John Sep 27 '17 at 09:28
  • Another reason is after I put some code in adminUserMaintService, I still get the `java.lang.NullPointerException` in `Connection conn = jdbcTemplate.getDataSource().getConnection();` so I think that is only exception I have. Thanks – John Sep 27 '17 at 09:30