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




String reasonMsg;

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








          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);




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: Logo

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s