java.lang.NullPointerException while using String format in java


In this Example we are going to understand the String Format of strings and the error

Error Message :
Exception in thread "main" java.lang.NullPointerException
       at java.base/java.util.regex.Matcher.getTextLength(Matcher.java:1770)
       at java.base/java.util.regex.Matcher.reset(Matcher.java:416)
       at java.base/java.util.regex.Matcher.<init>(Matcher.java:253)
       at java.base/java.util.regex.Pattern.matcher(Pattern.java:1133)
       at java.base/java.util.Formatter.parse(Formatter.java:2700)
       at java.base/java.util.Formatter.format(Formatter.java:2655)
       at java.base/java.util.Formatter.format(Formatter.java:2609)
       at java.base/java.lang.String.format(String.java:2988)
       at com.si.Strings.StrinFormat.main(StrinFormat.java:7)

Error Description :

package com.si.Strings;

public class StrinFormat {

       public static void main(String[] args) {
              String str3 = null;
              String str2 = String.format(str3, 4.256398);
              System.out.println(str2);
    }
}
In the above program we get an error in the red background line.
In the String format we are passing the format as a String variable like str3 .
If str3 not defined then we will get null pointer exception.


Solution:
If we declared the format as String variable at method level then need to do null check to avoid the null pointer exceptions.

package com.si.Strings;

public class StrinFormat {

       public static void main(String[] args) {
              String str3 = null;
              String str2 = null;
              if(str3!=null){
               str2 = String.format(str3, 4.256398);
              }else {
              System.out.println("String format should not be null Please define");
              }
    }}
Output:
String format should not be null Please define

Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar