0

I am calling the createInvestment method and Inside it is the calculateMaturityDate Method. I keep getting a Nullpointerexception when it gets to the calculateMaturityDate of the service class .

Service Class


@Service
public class InvestmentService {
    
    private static int nextAccountNumber = 2005070006;
    
    @Autowired  
    private InvestmentRepository investmentRepository;
    


      public Investment CreateInvestment(Investment investment)
       {
        investment.setAccountNumber(nextAccountNumber());
        investment.setStatus(InvestmentStatus.pending);
        investment.setStartDate(LocalDate.now());
        investment.setMaturityDate(calculateMaturityDate());
        investment.setCurrentInterest(calculateCurrentInterest());
        investment.setMaturityInterest(calculateInterestAtMaturity());
        return investmentRepository.save(investment);
       }
    
     public LocalDate calculateMaturityDate() {
      Investment investment = new Investment();
      {
           if(investment.getTenure().equalsIgnoreCase("365"))
            { investment.setMaturityDate(investment.getStartDate().plusDays(365));
            } else if (investment.getTenure().equalsIgnoreCase("120")) 
            { investment.setMaturityDate(investment.getStartDate().plusDays(120));}
           else if (investment.getTenure().equalsIgnoreCase("90")) 
            {investment.setMaturityDate(investment.getStartDate().plusDays(90));}
           else if (investment.getTenure().equalsIgnoreCase("30")) 
            {investment.setMaturityDate(investment.getStartDate().plusDays(30));}
         }
       return investment.getMaturityDate();}

This is the Model Class whose Instance is being created in the CreateInvestment Method

public class Investment 

   {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "AccountNumber", updatable = false, nullable = false)
    private int accountNumber;
    private String category;
    private BigDecimal principal;
    //private BigDecimal netInvestmentAmount;
    private BigDecimal currentInterest;
    private BigDecimal maturityInterest;
    private String tenure;
    private String marketer;
    private String investmentPackage;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate startDate;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate maturityDate;
    private int rate;
    private final double wht = 10/100;
    private String whtStatus;
    private final double  preLiquidationCharges = 25/100;
    @Enumerated(EnumType.STRING)
    private InvestmentStatus status;
    
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    @ManyToOne(targetEntity = Customer.class, 
    cascade = CascadeType.ALL, fetch = FetchType.LAZY )
    @JoinColumn(name="customer_id") 
    private Customer customer ;

This is the stack trace

2021-10-14 06:18:30.764 ERROR 11592 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null
    at com.bethsaida.org.service.InvestmentService.calculateMaturityDate(InvestmentService.java:52) ~[classes/:na]
    at com.bethsaida.org.service.InvestmentService.CreateInvestment(InvestmentService.java:43) ~[classes/:na]
    at com.bethsaida.org.controllers.InvestmentController.CreateInvestment(InvestmentController.java:64) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) ~[spring-web-5.3.9.jar:5.3.9]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) ~[spring-web-5.3.9.jar:5.3.9]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1064) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:681) ~[tomcat-embed-core-9.0.50.jar:4.0.FR]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.9.jar:5.3.9]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.50.jar:4.0.FR]

wizdemonizer
  • 105
  • 2
  • 10
  • Which variable is null? – Thorbjørn Ravn Andersen Oct 14 '21 at 13:39
  • There is no `CreateMaturityDate()` - which of the methods are you refering to? How about posting the stacktrace (you should always do that when asking about exceptions). – Thomas Oct 14 '21 at 13:40
  • First of all where is the stacktrace? second of all you shouldnt event be asking us about NPE since there is nothing easier than for u to identify it with a debugger – J Asgarov Oct 14 '21 at 13:40
  • 1
    Btw, why does `calculateMaturityDate()` create an `Investment` which is then thrown away? That looks like an awkward design. You have a couple of if-blocks that check the value of `investment.getTenure()` - do you expect that to return different values for a plain investment that has been created with `new Investment()`? – Thomas Oct 14 '21 at 13:41
  • I have edited and added the stack trace . @Thomas the calculateMaturityDate() method is a method being called inside the createInvestment method. – wizdemonizer Oct 14 '21 at 13:46
  • So which line is line 52 in `InvestmentService.java` ? My _guess_ would be that `investment.getTenure()` returns `null`. See my previous comment on that. – Thomas Oct 14 '21 at 13:48
  • When you create `Investment`, both `tenure` and `startDate` are `null` and you try to check if null tenure is equal to something and then add to `null` start date. – Nowhere Man Oct 14 '21 at 13:51

1 Answers1

0

In this code, the line Investment investment = new Investment(); will create a new Investment object with tenure value as null since you are not initializing the variable.

In the if condition if (investment.getTenure().equalsIgnoreCase("365")) is equivalent to if (null.equalsIgnoreCase("365")). This is causing the nullPointerException.

Also you may not need this additional wrapping paranthesis.

Joyal Joy
  • 11
  • 3