Checking if a string is empty or null in Java [duplicate] - java

This question already has answers here:
Check whether a String is not Null and not Empty
(35 answers)
Closed 8 years ago.
I'm parsing HTML data. The String may be null or empty, when the word to parse does not match.
So, I wrote it like this:
if(string.equals(null) || string.equals("")){
Log.d("iftrue", "seem to be true");
}else{
Log.d("iffalse", "seem to be false");
}
When I delete String.equals(""), it does not work correctly.
I thought String.equals("") wasn't correct.
How can I best check for an empty String?

Correct way to check for null or empty or string containing only spaces is like this:
if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }

You can leverage Apache Commons StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.
Example:
System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true
Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str).
Example:
System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true

You can use Apache commons-lang
StringUtils.isEmpty(String str) - Checks if a String is empty ("") or null.
or
StringUtils.isBlank(String str) - Checks if a String is whitespace, empty ("") or null.
the latter considers a String which consists of spaces or special characters eg " " empty too. See java.lang.Character.isWhitespace API

import com.google.common.base.Strings;
if(!Strings.isNullOrEmpty(String str)) {
// Do your stuff here
}

This way you check if the string is not null and not empty, also considering the empty spaces:
boolean isEmpty = str == null || str.trim().length() == 0;
if (isEmpty) {
// handle the validation
}

Related

How to check if a string contains certains letters/characters [duplicate]

This question already has answers here:
Test if a string contains any of the strings from an array
(15 answers)
Closed 2 years ago.
If I want to check whether a String contains "CVR", "CPR" and "NR". How do I do so? I tried with following method but got some issues
String testString = "cpr1210";
if (testString.contains("cpr||cvr||nr")) {
System.out.println("yes");
}
I might use String#matches() here, with a regex alternation:
String input = "cpr1210";
if (input.matches("(?i).*(?:cpr|cvr|nr).*")) {
System.out.println("MATCH");
}
If you really wanted to use String#contains(), then you would need to have three separate calls to that method, for each sequence.
As mentioned in my comment to your question, you may use String#contains().
String testString = "cor1210";
// will not print yes, because none of the sequences fit
if (testString.contains("cpr") || testString.contains("cvr") || testString.contains("nr")) {
System.out.println("yes");
}
Make sure your logic-syntax in the if-clause is correct.
You can check whether a String contains another String (a substring) with the String.contains() method. It returns a boolean value. Keep in mind that this method is case sensitive. If you want to do case-insensitive search then use the same technique, convert both input and search string in same case and then call the method.
String testString = "cor1210";
//checks whether testString contains CVR, CPR or NR
if (testString.contains("CVR")||testString.contains("CPR")||testString.contains("NR")){
System.out.println("yes");
}

Strange Behavior of Empty String in JAVA [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I am working on a Existing code and i found a Strange Behavior while checking a String is null or Empty. The existing code :
System.out.println("Length: " + value.length());
if (value != null && value != "") {
//code
}
Output:
Length: 0
But the if statement becomes true and its executing the code.
When i replaced the if statement with this one:
if (value != null && value.length() > 0) {
//code
}
It works perfectly. Any idea why the previous one failed and Why value != "" returns true?
Try to use equals method like this:
if (value != null && !"".equals(value)) {
Strings are not compared like this:
value != ""
Use equals:
!"".equals(value)
or isEmpty:
!value.isEmpty()
Because String is immutable
You should compare with value.isEmpty(). According to the source code, it will also compare the length.
What you are doing with != is comparing references, not equality.
When using == you are comparing the references which are not equal, that's why the expression evaluates to true.
You can use StringUtils.isNotEmpty
if (StringUtils.isNotEmpty(value)) {
...
}
true - if the String is not empty and not null
Reference
String is an Object in java, so you can't use == and != with it, because == and != comparing references, which is not equal. Use "".equals(value)
This is because you might have created value variable using new operator:
String value = new String();
So now if you use following :
System.out.println("Length: " + value.length());
if (value != null && value != "") {
System.out.println("hi")
}
It will print hi as value is from heap and literal "" is from string pool and you are making reference comparison. Use equals method instead .
value != ""
check for reference equality not the value equality.
if value is created like this:
String value=new String("");
then there is a high chance that the condition will fail.
For example if you have another String value2
String value2=new String("");
then
value==value2 // is false.
Have a look at this How do I compare strings in Java?
Your best bet is to use value != null && !value.isEmpty(), although you can ace this with the Yoda Expression
"".equals(value)
which saves you typing out the explicit check for null.
You can't use == since that would compare the object reference values (which might be different even if the string looks the same), not the string contents.

Java checking array contents

The problem I am having is using .contains() for an array. This is my current line of code:
if (strings[i].contains(symbol) = true){
strings[] is an array that stores user inputted data, the error message i get for this is "The left-hand side of an assignment must be a variable". I understand what this means, my question is, can I use one string from the array when using .contains() or am I going about this the wrong way?
Any help will be appreciated. Thanks.
The problem is that
strings[i].contains(symbol) = true
is an assignment because of the =. You probably mean
strings[i].contains(symbol) == true
and, because the left hand side is a boolean,
strings[i].contains(symbol)
is already sufficient.
my question is, can I use one string from the array when using .contains()
If you read the Java API for String (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html), contains() is a method from String class.
By knowing that, you can use .contains() on a single String element / a String variable.
String str = "abc";
str.contains(symbol); //This is ok.
String[] strs = {"abc", "def"};
str[0].contains(symbol); //This is ok too.
Both of the above are allowed, because both are String.
String[] strs = {"abc", "def"};
str.contains(symbol); //This is wrong!
One more thing which you should have noted by now in your codes is:
When comparison, use == and not single =
And when comparing strings or objects, use .equals()
Of course, you can also write it as:
if(strings.[i].contains(symbol)) //if this statement is true
if(!strings.[i].contains(symbol)) //if this statement is not true
instead of
if(strings.[i].contains(symbol) == true) //if this statement is true
if(strings.[i].contains(symbol) == false) //if this statement is not true

How to check a string that not empty in java? [duplicate]

This question already has answers here:
Check whether a String is not Null and not Empty
(35 answers)
Closed 7 years ago.
How to check a string in java that is empty or not?
For example :
string str = " " and string str2 = " " and str3 = ""
str includes 3 spaces, str2 includes 1 space, and str3 has no characters but all of them are empty.
How do I check this in Android?
Just check with str.isEmpty() as isEmpty() method will return true for actual length if 0.
As NULL refers to memory assignment of your String str. To check empty String use isEmpty() method.
Update:
In your case, best scenario should be,
if(str != null && str.trim().length() > 0)
{
// String str is not NULL or not Empty
}else
{
// String str is NULL or Empty
}
Null != empty.
Null means the variable is not initialized, like:
String s;
Your str,str2 and str3 are initialized, zo they are not null.
To check for same characters:
str.equals("foo"), ("foo" is in your case spaces :) )
NOT str == "foo". The last means you're checking same references.
You can see if the characters match
if (str.equals ("")) {
// true
}
if (str3.equals (" ")) {
// true
}

How does the comparison in Strings work? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
String comparison - Android [duplicate]
(17 answers)
Closed 8 years ago.
When I compare ("String"=="String"), what exactly I am comparing, the two objects or two references?
Please explain the output of following code snippets:
1) System.out.println("String".toString()=="String"); // output is true
2) System.out.println("String".trim()=="String"); // output is true
3) System.out.println("String ".trim()=="String"); // output is false
According to statement 1 and 2, the output of 3rd statement should also be true. Please explain what is going on here.
From my previous answer, You have to remember, == compares the object references, not the content.
trim() returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
in the first case the answer is true no surprise about that because the references are equal
in the second case there are no leading or trailing spaces so trim returns the same string again the references are equal
in the last case trim returns a copy as the string has a trailing white space which results in a different reference so your comparison will be false.
In java you should never compare strings with the equality operator ==, since that operator compares references rather than contents. The compiler is smart enough to reuse one reference for all equal literals found in the code (so the four occurrences of String in 1) and 2) are probably the same instance). However in 3) you have two different literals and there is no guarantee that "String ".trim() will be represented by the same instances as the literals.
See also: https://stackoverflow.com/a/513839/55787
Use .equals() instead.
== compares whether the two String references you are comparing point to same String instance or not.
To answer your question you need to check the source code of methods in String class
public String trim() {
int len = count;
int st = 0;
int off = offset; /* avoid getfield opcode */
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[off + st] <= ' ')) {
st++;
}
while ((st < len) && (val[off + len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < count)) ? substring(st, len) : this;
}
public String toString() {
return this;
}
As you can see it return this in case of trim if there is nothing to trim which is why you get true. Also toString simply returns this.
you have to use the method
equals()
to compare Strings. Instead with == you are comparing
references.
== compares memory location . In the first case , the toString method returns the same object ,and since both "String" objects being compared point to the same object on the constant pool, the result is true. In the second case, the trim method does no modification to the String so it returns the same object, with the same result. The third case and the second call to trim returns a different object, not located on the constant pool

Categories

Resources