How to check a string is not null? - java

if(string.equals(""))
{
}
How to check if the string is not null?
if(!string.equals(""))
{
}

Checking for null is done via if (string != null)
If you want to check if its null or empty - you'd need if (string != null && !string.isEmpty())
I prefer to use commons-lang StringUtils.isNotEmpty(..)

You can do it with the following code:
if (string != null) {
}

Checking for null is done by:
string != null
Your example is actually checking for the empty string
You can combine the two like this:
if (string != null && !string.equals("")) { ...
But null and empty are two different things

Nothing really new to add to the answers above, just wrapping it into a simple class. Commons-lang is quite all right but if all you need are these or maybe a few more helper functions, rolling your own simple class is the easiest approach, also keeping executable size down.
public class StringUtils {
public static boolean isEmpty(String s) {
return (s == null || s.isEmpty());
}
public static boolean isNotEmpty(String s) {
return !isEmpty(s);
}
}

Use TextUtils Method.
TextUtils.isEmpty(str) : Returns true if the string is null or 0-length. Parameters: str the string to be examined Returns: true if str is null or zero length
if(TextUtils.isEmpty(str)){
// str is null or lenght is 0
}
Source of TextUtils class
isEmpty Method :
public static boolean isEmpty(CharSequence str) {
if (str == null || str.length() == 0)
return true;
else
return false;
}

if(str != null && !str.isEmpty())
Be sure to use the parts of && in this order, because java will not proceed to evaluating the the second if the first part of && fails, thus ensuring you will not get a null pointer exception from str.isEmpty() if str is null.
Beware, it's only available since Java SE 1.6.
You have to check str.length() == 0 or str.equals("")
on previous versions.

As everyone is saying, you'd have to check (string!=null), in objects you're testing the memory pointer.
because every object is identified by a memory pointer, you have to check your object for a null pointer before testing anything else, so:
(string!=null && !string.equals("")) is good
(!string.equals("") && string !=null) can give you a nullpointerexception.
if you don't care for trailing spaces you can always use trim() before equals()
so " " and "" gives you the same result

The best way to check a String is :
import org.apache.commons.lang3.StringUtils;
if(StringUtils.isNotBlank(string)){
....
}
From the doc :
isBlank(CharSequence cs) :
Checks if a CharSequence is empty (""), null
or whitespace only.

You can use Predicate and its new method (since java 11) Predicate::not
You can write code to check if string is not null and not empty:
Predicate<String> notNull = Predicate.not(Objects::isNull);
Predicate<String> notEmptyString = Predicate.not(String::isEmpty);
Predicate<String> isNotEmpty = notNull.and(notEmptyString);
Then you can test it:
System.out.println(isNotEmpty.test("")); // false
System.out.println(isNotEmpty.test(null)); // false
System.out.println(isNotEmpty.test("null")); // true

A common way for testing null string in Java is with Optionals:
Optional.ofNullable(myString).orElse("value was null")
Optional.ofNullable(myString).ifPresent(s -> System.out.println(s));
Optional.ofNullable(myString).orElseThrow(() -> new RuntimeException("value was null"));
And to test if it is null or empty you can use Apache org.apache.commons.lang3 library that gives you the following methods:
StringUtils.isEmpty(String) / StringUtils.isNotEmpty(String): It tests if the String is null or empty (" " is not empty)
StringUtils.isBlank(String) / StringUtils.isNotBlank(String): Same as isEmpty bt if the String is only whitespace it is considered blank
And applied to Optional you get:
Optional.ofNullable(myString).filter(StringUtils::isNotEmpty).orElse("value was null or empty");

Try using Strings.isNullOrEmpty("") from com.google.common.base.Strings this method returns boolean value and checks for both null and empty string.

if(string != null)
or
if(string.length() == 0)
or
if(("").equals(string))

u can try this
if(string != null)

Related

can use ObjectUtils.identityToString() for checking the Object null

Please find my below code that am checking for null using ternary operator before am setting the value to my bean class attributes.
doc.setCatalog_description(sourceAsMap != null && sourceAsMap.get("catalog_description") != null ? sourceAsMap.get("catalog_description").toString() : null);
Is there anyother way to simplify this code like below., Am just exploring by using org.apache.commons.lang3.ObjectUtils; methods. But am not sure that it is correct or not.
doc.setCatalog_description(ObjectUtils.identityToString(sourceAsMap.get("catalog_description")));
I think you are looking for the method ObjectUtils.toString(Object).
if (sourceAsMap != null) {
final String description = ObjectUtils.toString(sourceAsMap.get("catalog_description"));
doc.setCatalog_description(description);
}
If you are using jdk7 or higher, you can replace the method by java.util.Objects.toString(Object).
if (sourceAsMap != null) {
final String description = Objects.toString(sourceAsMap.get("catalog_description"));
doc.setCatalog_description(description);
}
I don't know if sourceAsMap can be null, but if you are setting several parameters, you should check if it is null just once.
In the interest of readability and clarity I would suggest just extracting this bit of functionality into its own method:
String getDescOrNull(Map<String, Object> sourceAsMap) {
final String key = "catalog_description";
if (sourceAsMap == null || !sourceAsMap.containsKey(key)) {
return null;
}
return sourceAsMap.get(key);
}
then:
doc.setCatalog_description(getDescOrNull(sourceAsMap));
am checking for null using ternary operator before am setting the value to my bean class attributes
So I think you need to set multiple bean attributes from the map.
Best and simple solution will be to check null condition on sourceMap for once and then use ternary operator for setting attributes.
if(sourceAsMap != null){
doc.setCatalog_description(sourceAsMap.get("catalog_description") != null ? sourceAsMap.get("catalog_description").toString() : null);
doc.setAnother_description(sourceAsMap.get("another_description") != null ? sourceAsMap.get("another_description").toString() : null);
}

Cant identify blank string value [duplicate]

How can I check whether a string is not null and not empty?
public void doStuff(String str)
{
if (str != null && str != "**here I want to check the 'str' is empty or not**")
{
/* handle empty string */
}
/* ... */
}
What about isEmpty() ?
if(str != null && !str.isEmpty())
Be sure to use the parts of && in this order, because java will not proceed to evaluate the second part if the first part of && fails, thus ensuring you will not get a null pointer exception from str.isEmpty() if str is null.
Beware, it's only available since Java SE 1.6. You have to check str.length() == 0 on previous versions.
To ignore whitespace as well:
if(str != null && !str.trim().isEmpty())
(since Java 11 str.trim().isEmpty() can be reduced to str.isBlank() which will also test for other Unicode white spaces)
Wrapped in a handy function:
public static boolean empty( final String s ) {
// Null-safe, short-circuit evaluation.
return s == null || s.trim().isEmpty();
}
Becomes:
if( !empty( str ) )
Use org.apache.commons.lang.StringUtils
I like to use Apache commons-lang for these kinds of things, and especially the StringUtils utility class:
import org.apache.commons.lang.StringUtils;
if (StringUtils.isNotBlank(str)) {
...
}
if (StringUtils.isBlank(str)) {
...
}
Just adding Android in here:
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)) {
...
}
To add to #BJorn and #SeanPatrickFloyd The Guava way to do this is:
Strings.nullToEmpty(str).isEmpty();
// or
Strings.isNullOrEmpty(str);
Commons Lang is more readable at times but I have been slowly relying more on Guava plus sometimes Commons Lang is confusing when it comes to isBlank() (as in what is whitespace or not).
Guava's version of Commons Lang isBlank would be:
Strings.nullToEmpty(str).trim().isEmpty()
I will say code that doesn't allow "" (empty) AND null is suspicious and potentially buggy in that it probably doesn't handle all cases where is not allowing null makes sense (although for SQL I can understand as SQL/HQL is weird about '').
str != null && str.length() != 0
alternatively
str != null && !str.equals("")
or
str != null && !"".equals(str)
Note: The second check (first and second alternatives) assumes str is not null. It's ok only because the first check is doing that (and Java doesn't does the second check if the first is false)!
IMPORTANT: DON'T use == for string equality. == checks the pointer is equal, not the value. Two strings can be in different memory addresses (two instances) but have the same value!
Almost every library I know defines a utility class called StringUtils, StringUtil or StringHelper, and they usually include the method you are looking for.
My personal favorite is Apache Commons / Lang, where in the StringUtils class, you get both the
StringUtils.isEmpty(String) and the
StringUtils.isBlank(String) method
(The first checks whether a string is null or empty, the second checks whether it is null, empty or whitespace only)
There are similar utility classes in Spring, Wicket and lots of other libs. If you don't use external libraries, you might want to introduce a StringUtils class in your own project.
Update: many years have passed, and these days I'd recommend using Guava's Strings.isNullOrEmpty(string) method.
This works for me:
import com.google.common.base.Strings;
if (!Strings.isNullOrEmpty(myString)) {
return myString;
}
Returns true if the given string is null or is the empty string.
Consider normalizing your string references with nullToEmpty. If you
do, you can use String.isEmpty() instead of this method, and you won't
need special null-safe forms of methods like String.toUpperCase
either. Or, if you'd like to normalize "in the other direction,"
converting empty strings to null, you can use emptyToNull.
There is a new method in java-11: String#isBlank
Returns true if the string is empty or contains only white space codepoints, otherwise false.
jshell> "".isBlank()
$7 ==> true
jshell> " ".isBlank()
$8 ==> true
jshell> " ! ".isBlank()
$9 ==> false
This could be combined with Optional to check if string is null or empty
boolean isNullOrEmpty = Optional.ofNullable(str).map(String::isBlank).orElse(true);
String#isBlank
How about:
if(str!= null && str.length() != 0 )
Returns true or false based on input
Predicate<String> p = (s)-> ( s != null && !s.isEmpty());
p.test(string);
Use Apache StringUtils' isNotBlank method like
StringUtils.isNotBlank(str)
It will return true only if the str is not null and is not empty.
For completeness: If you are already using the Spring framework, the StringUtils provide the method
org.springframework.util.StringUtils.hasLength(String str)
Returns:
true if the String is not null and has length
as well as the method
org.springframework.util.StringUtils.hasText(String str)
Returns:
true if the String is not null, its length is greater than 0, and it does not contain whitespace only
You can use the functional style of checking:
Optional.ofNullable(str)
.filter(s -> !(s.trim().isEmpty()))
.ifPresent(result -> {
// your query setup goes here
});
You should use org.apache.commons.lang3.StringUtils.isNotBlank() or org.apache.commons.lang3.StringUtils.isNotEmpty. The decision between these two is based on what you actually want to check for.
The isNotBlank() checks that the input parameter is:
not Null,
not the empty string ("")
not a sequence of whitespace characters (" ")
The isNotEmpty() checks only that the input parameter is
not null
not the Empty String ("")
If you don't want to include the whole library; just include the code you want from it. You'll have to maintain it yourself; but it's a pretty straight forward function. Here it is copied from commons.apache.org
/**
* <p>Checks if a String is whitespace, empty ("") or null.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* #param str the String to check, may be null
* #return <code>true</code> if the String is null, empty or whitespace
* #since 2.0
*/
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
test equals with an empty string and null in the same conditional:
if(!"".equals(str) && str != null) {
// do stuff.
}
Does not throws NullPointerException if str is null, since Object.equals() returns false if arg is null.
the other construct str.equals("") would throw the dreaded NullPointerException. Some might consider bad form using a String literal as the object upon wich equals() is called but it does the job.
Also check this answer: https://stackoverflow.com/a/531825/1532705
Simple solution :
private boolean stringNotEmptyOrNull(String st) {
return st != null && !st.isEmpty();
}
As seanizer said above, Apache StringUtils is fantastic for this, if you were to include guava you should do the following;
public List<Employee> findEmployees(String str, int dep) {
Preconditions.checkState(StringUtils.isNotBlank(str), "Invalid input, input is blank or null");
/** code here **/
}
May I also recommend that you refer to the columns in your result set by name rather than by index, this will make your code much easier to maintain.
You can use StringUtils.isEmpty(), It will result true if the string is either null or empty.
String str1 = "";
String str2 = null;
if(StringUtils.isEmpty(str)){
System.out.println("str1 is null or empty");
}
if(StringUtils.isEmpty(str2)){
System.out.println("str2 is null or empty");
}
will result in
str1 is null or empty
str2 is null or empty
I've made my own utility function to check several strings at once, rather than having an if statement full of if(str != null && !str.isEmpty && str2 != null && !str2.isEmpty). This is the function:
public class StringUtils{
public static boolean areSet(String... strings)
{
for(String s : strings)
if(s == null || s.isEmpty)
return false;
return true;
}
}
so I can simply write:
if(!StringUtils.areSet(firstName,lastName,address)
{
//do something
}
In case you are using Java 8 and want to have a more Functional Programming approach, you can define a Function that manages the control and then you can reuse it and apply() whenever is needed.
Coming to practice, you can define the Function as
Function<String, Boolean> isNotEmpty = s -> s != null && !"".equals(s)
Then, you can use it by simply calling the apply() method as:
String emptyString = "";
isNotEmpty.apply(emptyString); // this will return false
String notEmptyString = "StackOverflow";
isNotEmpty.apply(notEmptyString); // this will return true
If you prefer, you can define a Function that checks if the String is empty and then negate it with !.
In this case, the Function will look like as :
Function<String, Boolean> isEmpty = s -> s == null || "".equals(s)
Then, you can use it by simply calling the apply() method as:
String emptyString = "";
!isEmpty.apply(emptyString); // this will return false
String notEmptyString = "StackOverflow";
!isEmpty.apply(notEmptyString); // this will return true
If you are using Spring Boot then below code will do the Job
StringUtils.hasLength(str)
With Java 8 Optional you can do:
public Boolean isStringCorrect(String str) {
return Optional.ofNullable(str)
.map(String::trim)
.map(string -> !str.isEmpty())
.orElse(false);
}
In this expression, you will handle Strings that consist of spaces as well.
To check if a string is not empty you can check if it is null but this doesn't account for a string with whitespace. You could use str.trim() to trim all the whitespace and then chain .isEmpty() to ensure that the result is not empty.
if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
I would advise Guava or Apache Commons according to your actual need. Check the different behaviors in my example code:
import com.google.common.base.Strings;
import org.apache.commons.lang.StringUtils;
/**
* Created by hu0983 on 2016.01.13..
*/
public class StringNotEmptyTesting {
public static void main(String[] args){
String a = " ";
String b = "";
String c=null;
System.out.println("Apache:");
if(!StringUtils.isNotBlank(a)){
System.out.println(" a is blank");
}
if(!StringUtils.isNotBlank(b)){
System.out.println(" b is blank");
}
if(!StringUtils.isNotBlank(c)){
System.out.println(" c is blank");
}
System.out.println("Google:");
if(Strings.isNullOrEmpty(Strings.emptyToNull(a))){
System.out.println(" a is NullOrEmpty");
}
if(Strings.isNullOrEmpty(b)){
System.out.println(" b is NullOrEmpty");
}
if(Strings.isNullOrEmpty(c)){
System.out.println(" c is NullOrEmpty");
}
}
}
Result:
Apache:
a is blank
b is blank
c is blank
Google:
b is NullOrEmpty
c is NullOrEmpty
Simply, to ignore white space as well:
if (str == null || str.trim().length() == 0) {
// str is empty
} else {
// str is not empty
}
Consider the below example, I have added 4 test cases in main method. three test cases will pass when you follow above commented snipts.
public class EmptyNullBlankWithNull {
public static boolean nullEmptyBlankWithNull(String passedStr) {
if (passedStr != null && !passedStr.trim().isEmpty() && !passedStr.trim().equals("null")) {
// TODO when string is null , Empty, Blank
return true;
}else{
// TODO when string is null , Empty, Blank
return false;
}
}
public static void main(String[] args) {
String stringNull = null; // test case 1
String stringEmpty = ""; // test case 2
String stringWhiteSpace = " "; // test case 3
String stringWhiteSpaceWithNull = " null"; // test case 4
System.out.println("TestCase result:------ "+nullEmptyBlankWithNull(stringWhiteSpaceWithNull));
}
}
BUT test case 4 will return true(it has white space before null) which is wrong:
String stringWhiteSpaceWithNull = " null"; // test case 4
We have to add below conditions to make it work propper:
!passedStr.trim().equals("null")
If you use Spring framework then you can use method:
org.springframework.util.StringUtils.isEmpty(#Nullable Object str);
This method accepts any Object as an argument, comparing it to null and the empty String. As a consequence, this method will never return true for a non-null non-String object.
To check on if all the string attributes in an object is empty(Instead of using !=null on all the field names following java reflection api approach
private String name1;
private String name2;
private String name3;
public boolean isEmpty() {
for (Field field : this.getClass().getDeclaredFields()) {
try {
field.setAccessible(true);
if (field.get(this) != null) {
return false;
}
} catch (Exception e) {
System.out.println("Exception occurred in processing");
}
}
return true;
}
This method would return true if all the String field values are blank,It would return false if any one values is present in the String attributes
I've encountered a situation where I must check that "null" (as a string) must be regarded as empty. Also white space and an actual null must return true.
I've finally settled on the following function...
public boolean isEmpty(String testString) {
return ((null==testString) || "".equals((""+testString).trim()) || "null".equals((""+testString).toLowerCase()));
}

Best way to verify string is empty or null

i am sure this must have been asked before in different ways - as isEmptyOrNull is so common yet people implement it differently. but i have below curious query in terms of best available approach which is good for memory and performance both.
1) Below does not account for all spaces like in case of empty XML tag
return inputString==null || inputString.length()==0;
2) Below one takes care but trim can eat some performance + memory
return inputString==null || inputString.trim().length()==0;
3) Combining one and two can save some performance + memory (As Chris suggested in comments)
return inputString==null || inputString.trim().length()==0 || inputString.trim().length()==0;
4) Converted to pattern matcher (invoked only when string is non zero length)
private static final Pattern p = Pattern.compile("\\s+");
return inputString==null || inputString.length()==0 || p.matcher(inputString).matches();
5) Using libraries like -
Apache Commons (StringUtils.isBlank/isEmpty)
or Spring (StringUtils.isEmpty)
or Guava (Strings.isNullOrEmpty)
or any other option?
Useful method from Apache Commons:
org.apache.commons.lang.StringUtils.isBlank(String str)
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank(java.lang.String)
To detect if a string is null or empty, you can use the following without including any external dependencies on your project and still keeping your code simple/clean:
if(myString==null || myString.isEmpty()){
//do something
}
or if blank spaces need to be detected as well:
if(myString==null || myString.trim().isEmpty()){
//do something
}
you could easily wrap these into utility methods to be more concise since these are very common checks to make:
public final class StringUtils{
private StringUtils() { }
public static bool isNullOrEmpty(string s){
if(s==null || s.isEmpty()){
return true;
}
return false;
}
public static bool isNullOrWhiteSpace(string s){
if(s==null || s.trim().isEmpty()){
return true;
}
return false;
}
}
and then call these methods via:
if(StringUtils.isNullOrEmpty(myString)){...}
and
if(StringUtils.isNullOrWhiteSpace(myString)){...}
Just to show java 8's stance to remove null values.
String s = Optional.ofNullable(myString).orElse("");
if (s.trim().isEmpty()) {
...
}
Makes sense if you can use Optional<String>.
This one from Google Guava could check out "null and empty String" in the same time.
Strings.isNullOrEmpty("Your string.");
Add a dependency with Maven
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
with Gradle
dependencies {
compile 'com.google.guava:guava:20.0'
}
Haven't seen any fully-native solutions, so here's one:
return str == null || str.chars().allMatch(Character::isWhitespace);
Basically, use the native Character.isWhitespace() function. From there, you can achieve different levels of optimization, depending on how much it matters (I can assure you that in 99.99999% of use cases, no further optimization is necessary):
return str == null || str.length() == 0 || str.chars().allMatch(Character::isWhitespace);
Or, to be really optimal (but hecka ugly):
int len;
if (str == null || (len = str.length()) == 0) return true;
for (int i = 0; i < len; i++) {
if (!Character.isWhitespace(str.charAt(i))) return false;
}
return true;
One thing I like to do:
Optional<String> notBlank(String s) {
return s == null || s.chars().allMatch(Character::isWhitepace))
? Optional.empty()
: Optional.of(s);
}
...
notBlank(myStr).orElse("some default")
Apache Commons Lang has StringUtils.isEmpty(String str) method which returns true if argument is empty or null
springframework library Check whether the given String is empty.
f(StringUtils.isEmpty(str)) {
//.... String is blank or null
}
Optional.ofNullable(label)
.map(String::trim)
.map(string -> !label.isEmpty)
.orElse(false)
OR
TextUtils.isNotBlank(label);
the last solution will check if not null and trimm the str at the same time
In most of the cases, StringUtils.isBlank(str) from apache commons library would solve it. But if there is case, where input string being checked has null value within quotes, it fails to check such cases.
Take an example where I have an input object which was converted into string using String.valueOf(obj) API. In case obj reference is null, String.valueOf returns "null" instead of null.
When you attempt to use, StringUtils.isBlank("null"), API fails miserably, you may have to check for such use cases as well to make sure your validation is proper.
Simply and clearly:
if (str == null || str.trim().length() == 0) {
// str is empty
}
With the openJDK 11 you can use the internal validation to check if the String is null or just white spaces
import jdk.internal.joptsimple.internal.Strings;
...
String targetString;
if (Strings.isNullOrEmpty(tragetString)) {}
You can make use of Optional and Apache commons Stringutils library
Optional.ofNullable(StringUtils.noEmpty(string1)).orElse(string2);
here it will check if the string1 is not null and not empty else it will return string2
If you have to test more than one string in the same validation, you can do something like this:
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class StringHelper {
public static Boolean hasBlank(String ... strings) {
Predicate<String> isBlank = s -> s == null || s.trim().isEmpty();
return Optional
.ofNullable(strings)
.map(Stream::of)
.map(stream -> stream.anyMatch(isBlank))
.orElse(false);
}
}
So, you can use this like StringHelper.hasBlank("Hello", null, "", " ") or StringHelper.hasBlank("Hello") in a generic form.
We can make use of below
Optional.ofNullable(result).filter(res -> StringUtils.isNotEmpty(res))
.ifPresent( s-> val.set(s));

null pointer exception in writing file in java

I am facing an exception while writing to the file. i am giving the code below.
private static void readCsvFromFileAmazon(List<String> filelist)
throws BiffException, IOException,NullPointerException {
FileWriter fw = new FileWriter("total_number_of_products_amazon.txt", true);
String numberOfProducts = getProductNumber(url);
System.out.println(category);
System.out.println("##############" + numberOfProducts);
// call function to get the number of products. \
if (!numberOfProducts.equals(null) || !numberOfProducts.equals(" "))
{
fw.write(numberOfProducts);
}
else
{
System.out.println("cant write null product");
}
fw.close();
}
the value getting in number of products is null then exception happening
Exception in thread "main"
##############null
java.lang.NullPointerException
exception happening in this line
if(!numberOfProducts.equals(null)||!numberOfProducts.equals(" "))
You must check numberOfProducts content in different way:
if(null != numberOfProducts ||!"".equals(numberOfProducts))
instead of if(!numberOfProducts.equals(null)||!numberOfProducts.equals(" "))
because if numberOfProducts is null, then invoke a method equals on null object throws a nullPointerException.
Hope this helps,
in your if statement numberOfProducts.equals(null)
you are comparing a string to a null string. this doesnt have any effect since you are comparing a null object.
remember that String is an object and you need to check object if they are null in this kind of way numberOfProducts == null or numberOfProducts != null
You cannot check if null.equals(null) - it throws an exception, NullPointerException, for tying to access the equals() method of null. First, make sure numberOfProducts is not null itself, using the == operator:
if (numberOfProducts == null) {
//do something
} else {
...
}
Also note that the line
if(!numberOfProducts.equals(null)||!numberOfProducts.equals(" "))
Makes no sense logically. Assuming null.equals(null) would work (IT DOES NOT), The second (right) operand - !numberOfProducts.equals(" "), will be evaluated only if numberOfProducts == null, so whenever the right operand is evaluated - it will always yield false.
This means your condition could be shortened to simply:
if (numberOfProducts != null)
As you posted for:
System.out.println("##############"+numberOfProducts);
Output is:
##############null
This means numberOfProducts is null hence if you attempt to call any non-static method on it like this:
numberOfProducts.equals(null)
will throw a NullPointerException. If you want to check if it's null, do it like this
if (numberOfProducts != null && !numberOfProducts.equals(" ")) {
fw.write(numberOfProducts);
}
I think this will work
if(numberOfProducts!=null && !numberOfProducts.rquals(" ")){
//doSomething
}else{
//doSomethingElse
}

Checking if condition for 'null'

I have a doubt regarding checking null condition.For eg :
if(some conditon)
value1= value; //value1 is string type
else
value1= "";
Similarly some 4 other string value has similar condition.
What i need is i want to check whether all those 5 string value is null or not,Inorder to do some other specific part.
i did it like this
if(value1 == null)
{
}
but the pgm control didnot entered the loop eventhough value1="".
then i tried
if(value1 ==""){
}
this also didnt worked.
Cant we check null and "" value as same??
can anyone help me??
If you want to check is a String is null, you use
if (s == null)
If you want to check if a string is the empty string, you use
if (s.equals(""))
or
if (s.length() == 0)
or
if (s.isEmpty())
An empty string is an empty string. It's not null. And == must never be used to compare string contents. == tests if two variables refere to the same object instance. Not if they contain the same characters.
To check both "is not null" and "is not empty" on a String, use the static
TextUtils.isEmpty(stringVariableToTest)
It looks like you want to check wether a String is empty or not.
if (string.isEmpty())
You can't check that by doing if (string == "") because you are comparing the String objects. They are never the same, because you have two different objects. To compare strings, use string.equals().
When you are working on String always use .equals.
equals() function is a method of Object class which should be overridden by programmer.
If you want to check the string is null then if (string.isEmpty()) else you can also try if (string.equals(null))
You can use:
we can check if a string is empty in 2 ways:
if(s != null && s.length() == 0)
if(("").equals(s))
prefer below.
String str;
if(str.length() > 0)
{
Log.d("log","str is not empty");
}
else
{
Log.d("log","str is empty");
}

Categories