Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking empty string in Java

Tags:

java

string

I don't know what is wrong with the below code.... I am getting input from a textbox and putting the input in a string. If the textbox is empty it will return a empty string. In the below code

   String[] str = new String[9]; 
   for(int i=0;i<9;i++){
       if(str[i].equals("")){
          System.out.println("set " + cmds[i] + " " + str[i]);
          WriteThread.sendCommand("set " + cmds[i] + " " + str[i] + "\n", false);
       }
    }

In the above code str[i] stores the input text of textboxes and I am trying to check if any element of the array is empty. I also tried with str[i] == "" and str[i] == null but no luck. The statement inside the if block if i am printing the string str[i], it shows nothing that means it is empty.

Am I doing anything the wrong way?

like image 538
Surjya Narayana Padhi Avatar asked Dec 24 '09 06:12

Surjya Narayana Padhi


People also ask

How do I check if a string is empty or null?

You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.

How do you compare empty strings in Java?

Use String. isEmpty(), or StringUtils. isEmpty(String str) if you need a null check.

Is empty string null in Java?

The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.


1 Answers

You could try :

if (str[i] == null || str[i].trim().equals("")){
// your code
}
like image 184
fastcodejava Avatar answered Sep 20 '22 15:09

fastcodejava