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

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
}

Related

What will be output and explanation? [duplicate]

This question already has answers here:
Getting strange output when printing result of a string comparison
(3 answers)
Closed 3 years ago.
Below code return boolean false value. Any explanation for this ?
String str = "Bee";
String str2 = "Bee";
System.out.println("==" + str == str2);
Actual Result : false
Use equals to compare string, it will return true for this case.
The == operator compares that the Strings are exactly the same Object.
This might theoretically happen in case of internalized strings, but you cannot rely on this. For your case, comparing String values, use str.equals(str2).
str and str2 are both assigned the same String instance, since String literals are automatically stored in the String pool. Therefore str == str2 is true.
However, you are printing the expression "==" + str == str2. That expression is evaluated from left to right, so first "==" + str is evaluated, and results with the String "==Bee". Then the == operator is applied to "==Bee" and "Bee", which returns false.
If you change the statement to:
System.out.println("==" + (str == str2));
you'll get true, since now the comparison will take place prior to the String concatenation.

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.

Diffrence between String str = "' & String str =null [duplicate]

This question already has answers here:
Difference between null and empty ("") Java String
(22 answers)
What is null in Java?
(14 answers)
Closed 8 years ago.
What is the differences between String str1="" and String str2 =null?
When we print str1 there is no output and when we print str2 output is null.
"" is the empty string, null is the null reference.
The first is an empty String whereas the second is a null reference to a String.
An empty String is a String with no characters.
A null reference is a reference to a String that is not existent.
There Huge Difference "" means this empty String and Second one null means there is noting to assign and its noting exists.
"" means strings is created in string pool while for second one is nothing exist.
str1 there is no output
because string is empty so its printing nothing to output while second is null so its string value is null.
The first you are creating a new String object and assigning it "" or empty String. Your variable is pointing to this string object. The second you are not creating a new String object. You are creating a pointer that is not pointing to anything it is null. When you print using "" + yourstring it will print null because of the base Class objects toString() method.

Confused in appending Strings in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have a situation of appending String. And i'm confused ..
public static void foo() {
String s = "str4";
String s1 = "str" + s.length();
System.out.println("(s==s1) = " + (s1 == s));
}
And
public static void bar() {
String s = "str4";
String s1 = "str" + "4";
System.out.println("(s==s1) = " + (s1 == s));
}
In 1st case it's returning 'false' but in 2nd case 'true'
As i understand in both cases 'str4' object is being created on the heap. So it should return true in both cases. But it's not.
Kindly someone help me out why it's so. ? Thanks.!
Use
s1.equals(s)
to compare strings, otherwise you compare references.
In second case it returns true because String s1 = "str" + "4"; would be optimized to String s1 = "str4"; and s and s1 would refer to the same String.
The == operator in Java only returns true if both references refer to the same object. If you are trying to compare two Strings for equivalent content, you must use the equals() method.
you need to use .equals() for this
.equals() // if you dont want to ignore case
.equalsIgnoreCase() // if you want to ignore case
== compare the references.
In the second case both strings are equal .So references are also equal.
String s = "str4";
String s1 = "str" + "4"; .//finally str4
Here s1 ans s2 contents are equal.So they have same reference.
In my own understanding :
"str" => String
"4" => String
However,
s.length() => int
With ==, memory locations are compared.
Using the first example, Java creates another String which is in another memory location other than the location of 's' because you are trying to do String + int = String.
The second example returns true because it is just the same memory location as your 's' only that the value is changed. String + String = Concatenated String
Since you are trying to compare if the two strings have the same characters inside but not necessarily the same location, then s.equals(s1) is the best solution.
However, should you want to test if both variables are pointing to the same object then == must be used because of its shallow comparison.

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

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
}

Categories

Resources