I currently get the NullPointerException in my following code.
else if (isEmpty(href))
System.err.println("This is an empty link: " + href);
Where the isEmpty function is the following.
public boolean isEmpty(String HREF){
if (HREF.equals("") || HREF.equals("null") || HREF == null || HREF.isEmpty())
return true;
else
return false;
}
Is it because I can not compare a string to null? What can I do to make this function work?
Your isEmpty test is just doing things in the wrong order. Change this:
if (HREF.equals("") || HREF.equals("null") || HREF == null || HREF.isEmpty())
return true;
to:
if (HREF == null || HREF.equals("") || HREF.equals("null") || HREF.isEmpty())
return true;
If HREF is actually null, then the first test will short-circuit the rest of the if and you won't get a NPE.
(By the way, explicitly testing HREF.equals("") and also calling HREF.isEmpty() is redundant. You only need to do one or the other.)
By the by-the-way, I would recommend, as a matter of style simplifying your method to a single return statement:
public boolean isEmpty(String HREF){
return HREF == null || HREF.isEmpty()) || HREF.equals("null");
}
(Also, if testing against the string "null" was an attempt to check against a null value, you can drop that condition as well. In fact, you could then use something like Apache Commons' StringUtils.isEmpty(CharSequence) method to do what you want.)
changing the order in your if will solve it.
public boolean isEmpty(String HREF) {
return HREF == null || HREF.equals("") || HREF.equals("null") || HREF.isEmpty();
}
this way, when HREF == null, none of the other tests will be evaluated.
When HREF is null , referencing it with dot operator will throw a null pointer exception .
Different ways to solve this is as follows
public boolean isEmpty(String HREF){
if (HREF == null ||HREF.equals("") || HREF.equals("null") || HREF.isEmpty())
return true;
else
return false;
}
this is by just re arranging your conditions, by short cut of boolean operations, this will avoid referencing a null pointer in subsequent checks.
OR
public boolean isEmpty(String HREF){
//handling null case first of all
if(HREF == null) return true;
if(HREF.equals("") || HREF.equals("null") || HREF.isEmpty())
return true;
else
return false;
}
Also avoid redundant use of checks like HREF.equals("") and HREF.isEmpty() are similar.
Another best practice to check equals with a string object is to use the constant in the beginning as in "".equals(HREF) and "null".equals(HREF), here we are pretty sure that "null" is a valid string and which is not null
You cannot call methods of the null here HREF.equals("")
Common practice is to change the order "".equals(HREF) . This is null safe. And you will not need HREF.isEmpty() part this way.
So the code will become
public boolean isEmpty(String HREF){
return HREF == null || "".equals(HREF) || "null".equals(HREF);
}
I have removed the unnecessary if here as we are returning the result of boolean expression.
If HREF is null, then doing this:
HREF.equals("")
will throw a NPE.
Do the null check first:
HREF != null && /* rest of conditions */
Related
I am using Talend to filter out some rows from an excel file and they don't allow block statements. Everything has to be simple logic or using the ternary operator. So the problem is that the code/logic I need will be used across every cell in the column, BUT some of the cells are null, some are Strings and the rest are Strings that represent integers.
My logic needs to be this:
Return true if and only if PlanName == null || PlanName == 0 but as you can tell, it will fail when it tries to run this on a cell that contains the null or the cell that contains a String that isn't a number.
Is it possible to have this logic in java without the try-catch or block statements? This is what I have right now:
input_row.PlanName == null || Integer.parseInt(input_row.PlanName) == 0
Thanks!
Edit: Basically, I just need to write logic that does this:
Return true if input_row.PlanName == null OR if input_row.PlanName == 0
This needs to be done without using block-statements or try-catches because I am using Talend. So I can only use logical operators like && and || and I can use ternary operators as well.
In your situation, i'll go for routines : reusable bunch of code, handy for this kind of rules that would be hard to implement without if/else etc.
You can create two Routines in Talend, with static methods that you would be able to use in a tMap or a tJavaRow.
First Routine to know if your plan is a numeric or not :
public static boolean isNumeric(String strNum) {
if (strNum == null) {
return false;
}
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
Then another routine like :
public static boolean correctPlanName(String planName) {
if(Relational.ISNULL(planName)){
return false;
}
else{
if(!isNumeric(planName)){
return false;
}
else {
return true;
}
}
}
Then you call Routines.correctPlanName(input_row.planName) in tMap/tJavaRow.
It should do the trick.
You can use a regular expression to check if the String only contains digits, then check if num == 0.
input_row.PlanName == null || (input_row.PlanName != null && input_row.PlanName.matches("\\d+") && Integer.parseInt(input_row.PlanName) == 0)
Edit: Probably overkill but to cover other cases e.g. floating point types, numbers prefixed with +/-, you could also do:
input_row.PlanName != null && input_row.PlanName.matches("[-+]?\\d*\\.?\\d+") && Double.parseDouble(input_row.PlanName) == 0)
public boolean isValidCardDetails(CardDetailsTypeBean cardDetailsTypeBean) throws EnrollmentReqInvalidException {
if (cardDetailsTypeBean.getCardNumber() == null || "".equals(cardDetailsTypeBean.getCardNumber())) {
throw new EnrollmentReqInvalidException("ECDOO16", "card no is mandatory");
}
if (cardDetailsTypeBean.getNameOnCard() == null || "".equals(cardDetailsTypeBean.getNameOnCard())) {
throw new EnrollmentReqInvalidException("ECDOO17", "name on card is mandatory");
}
if (cardDetailsTypeBean.getCvv() == 0 || "".equals(String.valueOf(cardDetailsTypeBean.getCvv()))) {
throw new EnrollmentReqInvalidException("ECDOO18", "cvv is mandatory");
}
if (cardDetailsTypeBean.getExpDate() == null || "".equals(cardDetailsTypeBean.getExpDate())) {
throw new EnrollmentReqInvalidException("ECDOO19", "exp date must be required");
}
return false;
}
Well here i want to ask after getting card number and checking null,why we use "".equals there..?? can anyone explain me this? little confused?
This line of code:
cardDetailsTypeBean.getCardNumber() == null || "".equals(cardDetailsTypeBean.getCardNumber())
simply verifies if cardNumber is null or if is equal to the empty string. Empty string is different from null value, so this code checks if every field read by a getter returns a non-empty, non-null value.
It's superfluous, actually.
The reason for this is that the order of the equals statement on the other side of the logical comparison is guaranteed not to produce a NullPointerException, since String.equals(null) is engineered to produce false.
The reason it likely exists the way it does is that it's being made explicit that the code is checking for null and an empty string.
"" isn't the same as null because "" is a String value. Your card number might instantiated with ""
null means the reference of card number has no value.
I am trying to validate some input from a Swing form by checking for null values. However the checkFirstName method is always returning true. So for example if i leave the firstname blank on the form it will return true even though the field is null.
Here is my two methods, the first one is fired when the user clicks the save button.
public void saveNewCustomer() throws SQLException, ClassNotFoundException {
boolean dbOK = false;//boolean to check if data input is not null
System.out.println(dbOK);
String firstName = txtNCustomerFirstName.getText();
String lastName = txtNCustomerLastName.getText();
if (checkFirstName(firstName)) {
dbOK = true;
} else {
lblNCustFirstNameError.setText("First Name Must be Entered");
dbOK = false;
}
System.out.println(dbOK);
if (dbOK) {
dbConnector.insertSignup(firstName, lastName);
System.out.println("Success");
} else {
System.out.println("Error");
}
}
public boolean checkFirstName(String firstName) {
boolean allOK = false;
System.out.println(allOK);
if (firstName != null) {
allOK = true;
} else {
allOK = false;
}
return allOK;
}
Have i done something wrong cause this to me should be return false cause the firstname field is null.
The String will never be null, the String will be empty. Check firstName.isEmpty(). Still I suggest you keep the check for null too:
public boolean checkFirstName(String firstName) {
boolean allOK = false;
System.out.println(allOK);
if (firstName != null && !firstName.isEmpty()) {
allOK = true;
} else {
allOK = false;
}
return allOK;
}
EDIT: as pointed out by Windle you probably would like to check if the String has at least one non-whitespace:
if (firstName != null && !firstName.trim().isEmpty())
Also you may perform more complex verification - for instance if you want to make sure there are no whitespaces in the username after you trim it.
So for example if i leave the firstname blank on the form
You are just checking for null, you need to do empty ("") String check also.
It should be something like:
if (firstName != null && !"".equals(firstName.trim()) {
The txtNCustomerFirstName.getText method is returning an empty string. You might change your checkFirstName method's if statement to check for an empty string:
if (firstName != null && !firstName.isEmpty()) {
If you don't have Java 6+, you can use firstName.length() > 0 instead of isEmpty.
As far as I'm aware, the getText() method you're calling in the saveNewCustomer() will return an empty string rather than null.
So for example if i leave the firstname blank on the form it will
return true even though the field is null.
This is where your reasoning is wrong. When you leave a text field blank, getText() returns an empty string i.e. "" which is not null. You should check for emptiness instead of null.
if (!firstName.isEmpty()) { ... }
If firstName may also be null (e.g. when it comes from another source), you should check that beforehand:
if (firstName != null && !firstName.isEmpty()) { ... }
As other answers have suggested do a null check with an empty string check. I'd say trim the leading and trailing whitespaces also before doing an empty check because in reality you want to avoid such situation.
if (firstName != null && !firstName.trim().isEmpty()) { ... }
I have wriiten a method like this
public ArrayList<T> GetDoctorDetail(String name)
{
if (name!=null || !name.isEmpty() || name!="")
{
//Statements
}
}
but in eclipse !name by underline with a yellow line show
Null pointer access: The variable name can only be null at this location.
why? and what is the solution.
If name is non-null, the conditional || operator won't evaluate the second operand at all. So the only case in which the second operand can be evaluated is when name is null, in which case it will throw.
I suspect you want
if (name != null && !name.isEmpty())
{
// Use name
}
Or possibly:
if (name == null || name.isEmpty())
{
// Show an error message
}
Note that comparing strings with == and != is also almost always the wrong thing to do, as it compares references. You would normally use equals instead. Not only that, but it would be useless anyway here - it could only be equal to "" if it's empty, so it's the exact same condition as the second operand.
The first part of the oR condition will only fail if name = null. Hence the second part will throw a null pointer exception.
The correct way to write that condition is
if (name!=null && (!name.isEmpty() || name!=""))
if (name != null && !name.isEmpty()) {
// Now the name variable has valid content
}
Note - The logic is always much easier to understand if you create "positive" checks:
if (name == null || name.isEmpty()) {
// Now name is either null or empty
} else {
// Now the name has valid content
}
Try to avoid conditions that check for "negative" states, like "is not null" and "is not empty". They're nothing but brain twisters ;)
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)