Java Basic Problems

Java:Check Empty String and Avoid Null Pointer Exception

In my last post I have shared about the features of  Final Class,Variables and Methods.

Today I am going to share about how to check a string is Empty or not and also how to avoid Null Pointer Exception in java which occurs due to null value of  string.

Here I have used JOptionPane showInputDialog to take String Input from the user and then I checked the String entered by the user is empty or not.

If we check the string using the method given below we will be able to avoid Null Pointer Exception.

 

null pointer exception java

Here is the given example:

import javax.swing.*;

public class StringDemo

{

 StringDemo()

{

String reasonMsg;

reasonMsg=JOptionPane.showInputDialog(“Pleas Enter Your Name”,””);

System.out.println(“\n”);

System.out.println(“ReasonMsg:”+reasonMsg);

try

                                                {

                                                System.out.println(“\n”);

                             if(reasonMsg.trim().toString().length()==0)

                                      {

          JOptionPane.showMessageDialog(null,”You Entered Nothing”);

                                      }

                                                 if (reasonMsg.trim().toString().length()!=0)

                                                 {   

                                                                   JOptionPane.showMessageDialog(null,”You Name is:”+reasonMsg);

          System.out.println(“Your name is :”+reasonMsg);

                                                 }  

                                                }

          catch (Exception ex) {

Exception newEx = new Exception(“Error at:”+new java.util.Date()+””,ex);

 newEx.printStackTrace();

                                                }

}

public static void main(String args[])

{

StringDemo x=new StringDemo();

}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s