I want to check for null or empty specifically in my code. Does empty and null are same for StringBuilder in Java?
For example:
StringBuilder state = new StringBuilder();
StringBuilder err= new StringBuilder();
success = executeCommand(cmd, state, err);
/* here executeCommand() returns empty or null in state, I cant make changes in <br/> executeCommand() so can I check it in my code somehow for state, if its null or empty? */<br/>
if (state == null) { //do blabla1 }
if (state.tostring().equals("")) { //do blabla2 }
Does above code make sense or how should I change it?
No, null and empty are different for StringBuilder.
StringBuilder nullBuilder = null;
if(nullBuilder == null) {
System.out.println("Builder is null");
}
&
StringBuilder emptyBuilder = new StringBuilder("");
if(emptyBuilder == null || emptyBuilder.toString().equals("")) {
System.out.println("Builder is empty");
}
In Java, null is a reference literal. If a variable is null then is not referring to anything.
So, if you have StringBuilder s = null, that means that s is of type StringBuilder but it is not referring to a StringBuilder instance.
If you have a non-null reference then you are free to call methods on the referred object. In the StringBuilder class, one such method is length(). In fact if you were to call length() using a null reference then the Java runtime will throw a NullPointerException.
Hence, this code is quite common:
If (s == null || s.length() == 0/*empty if the length is zero*/){
// do something
It relies on the fact that evaluation of || is from left to right and stops once it reaches the first true condition.
Null mean, there are no object in the heap for that reference variable. This is common to all java object, not specific to StringBuilder and Empty means, "".
In your code, you have created a StringBuilder object, so checking null is redundant. And, You can check empty by using isEmpty() method in from java String api
if(state.tostring().isEmpty()) {
//
}
And checking null is correct. Find the corrected version here
if (state == null) {
// ...bla 1
} else if (state.tostring().isEmpty()) {
//... bla 2
}
Your second if condition will throw NullPointerException, if the state is null. So if should be nested with if else
No. empty means, that there are no characters in the StringBuilder. null means that there is no StringBuilder object at all.
A variable is only null if it has a reference type (for example String, StringBuilder, Set, as a thumbrule: all capitalized types) and it is not initialised yet or has been set explicitly to null.
The below code may help you,
StringBuffer sb = new StringBuffer();
String str = sb.toString();
if(!"".equals(str)) {
System.out.println("String : " + str);
} else {
System.out.println("Empty Builder");
}
You can try like this
StringBuilder state = new StringBuilder();
if(StringUtils.isNotBlank(state .toString())){
//this will check for null, " ", ""
}
Related
The for loop in the code below only executes once. I was looking at similiar questions but those have something that breaks it like editing the list in the loop while I dont.
public String getProfileList(JSONObject obj, String uuid) {
JSONObject profile = (JSONObject) obj.get("profiles");
#SuppressWarnings("unchecked")
ArrayList<String> list = new ArrayList<String>(profile.keySet());
System.out.println(list);
for (String object: list) {
System.out.println(object);
String isUUID = (String) ((JSONObject) profile.get(object)).get("mpm-data:uuid");
System.out.println(object + " == " + isUUID);
if (isUUID.equals(uuid)) {
System.out.println("TRUE");
return object;
}
}
System.out.println("no profile found.");
return null;
}
This code outputs this:
[5fb4acd48e7d422eabecd82e32fb03c6, 44d01181eae635d31f2cefe5e1f75cd4,e0e96e422659dfdc1ad16d53a37ee618, a3ae7136f900457290e99bd657db0385]
5fb4acd48e7d422eabecd82e32fb03c6
5fb4acd48e7d422eabecd82e32fb03c6 == null
For your console output you can see that isUUID is null. This means that when you attempt to call its method equals there is actually no object to call it to and you should be getting a NullPointerException. That's why it is best to do equals assertions with the part you know will not be null on the left side:
uuid.equals(isUUID) would be better.
Notice that if you do an equals assertion with a variable and a static string then it is best to do it like so:
"myCompareString".equals(myVariable), since "myCompareString" can never be null whereas myVariable can.
if (isUUID.equals(uuid)) will throw a nullPointerException when isuuid is null.
You should check if the data is right, and handle the exception.
And you can use StringUtils.equals(String str1, String str2) in commons-lang.jar, then you don't need to handle the null yourself, see http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html
System.out.println(object + " == " + isUUID);
Code prints
5fb4acd48e7d422eabecd82e32fb03c6 == null and next statement you are using in if condition .If isUUID is null it should throw null pointer exception.Can you please check this point
if (isUUID.equals(uuid)) {
System.out.println("TRUE");
return object;
}
I am trying to check if the input in EditText in null or not .
if(editTextSum.getText().toString() != null) {
userStartingBalance = Integer.valueOf(editTextSum.getText().toString());
} else {
userStartingBalance = 0;
}
Here userStartingBalance is Integer type .
But I am getting an error everytime that
Can't convert " " into int , and the line is pointed to the 'if case' if I don't enter anything.
Why is it not going to else case?
What should be the workaround?
You are not properly handling the case in which your EditText simply has no content in it.
In this case, editTextSum.getText().toString() will not return null (in fact, that should never be null). Instead, it will return an empty string.
Instead, you might want to try editTextSum.getText().toString().isEmpty() instead,. isEmpty() will return true if the length is 0.
try:
Integer.parseInt(editTextSum.getText().toString())
Why is it not going to else case ?
Because you are calling ToString() on Null. If the field has no value present then it wil set NULL to it and if you try to run the toString() method you will receive this error. Do the Null check before retrieving the value.
Workaround
if( editTextSum.getText() != null )
{
userStartingBalance = Integer.parseInt(editTextSum.getText().toString());
}
else
{
userStartingBalance =0;
}
I need to see if a text field has an empty value. I need to see if
if(Double.parseDouble(distanceTf.getText())==0)
I know 0 won't work. I also know null won't work and I know .equals won't work.
Does anyone know how I can compare this line of code to a null value?
if (stageTf.getText().equals("") || Double.parseDouble(distanceTf.getText()) == null) {
JOptionPane.showMessageDialog(null, "You did not enter both a stage number and distance");
return;
}
Thanks for all the above replies but they don't work.
The part of the code I have trouble with is:
if (Double.parseDouble(distanceTf.getText())==null)
The rest of it is fine.
I have tried putting this outside the if statement and using distanceTf.getText().equals("")
in the if statement but this doesn't work either.
I just can't find out how to assign an empty value to the line of code for a double.
I know null, .equals or "" won't work.
You're not clear on which value could be null, so I'll assume both.
Since Double.parseDouble requires a non-null argument, you need to check it for null.
if(null != distanceTf.getText() && Double.parseDouble(distanceTf.getText()) != 0.0)
stageTf.getText() could return null too, but if you're guaranteed to be comparing a known non-null String against null, it would return false. So, this comparison is safer:
if("".equals(stageTf.getText())
The important thing to understand is: what you mean with null value? A null reference or an empty string?
You could do
stageTf.getText().isEmpty()
to check if the string is empty and parse it only if it contains something.
// here remember it's still wrong
if (!stageTf.getText().isEmpty() && Double.parseDouble(distanceTf.getText()) == null) {
Second problem: Double.parseDouble doesn't return null since it returns a native type.. it thrown an exception if something went wrong. So you can catch NumberFormatException.
Then you could write:
try {
double result;
if (!stageTf.getText().isEmpty() && (result = Double.parseDouble(distanceTf.getText()))) {
/* i think you need the result of the conversion, so i saved it in result */
}
}
catch (NumberFormatException e) { /* something went wrong! */ }
You need to test if the field is empty first. You did it correctly with your first conditional on the stageTf field. You need to do the same with the distanceTF field. This means nesting your conditional statements.
if(stageTF.getText().equals(""))
if(distanceTF.getText().equals("")){
/* ... */
} else {
//here it is safe to test for exceptions by using a try/catch
try{
//here you can parse the string to your Double
}catch(NumberFormatException nfe){ /* ... */ }
}
first of all you should check for null before empty because if the value is null you'll get a NullPointerException on the first one.
Second you'll get a NullPointerException if distanceTf.getText() is null on the Double.parseDouble
Double.parseDouble() doc
what I would do is create a method validate as follows:
private boolean validate(String field){ //where field = stageIf.getText() for example
if(field != null && field.trim().length() > 0)
return true;
else return false;
}
Parse outside if statment, then just compare :
if(distanceTf.getText() == "")
I have a simple issue related ==null and =="" ,i think everybody know this issue .
Here's an example:
#SuppressWarnings("unchecked")
public void reorderingCriteia() {
ListModelList<ReorderData> headerList = new ListModelList<ReorderData>();
List<String> headerId = new ArrayList<String>();
String userReorderSelection = Services.userPreferenceService().getUserPreference().getUserOption("PROCESS_CHECKLIST_COLUMN_REORDER");
if (userReorderSelection == null || userReorderSelection == "") {
int i = 0;
for (ReorderData rd : availableReorderList) {
headerList.add(rd);
headerId.add("" + i);
i++;
}
folderProcessModel.setHeaderList(headerList);
folderProcessModel.setHeaderId(headerId);
} else {
headerList = ReorderDialogViewModelNew.jsonStringToList("FOLDER_PERMIT_LIST_COLUMN_REORDER", userReorderSelection, false);
headerId = compHelper.intializeSequnce(headerList, folderProcessModel.getAvailableHeaders());
folderProcessModel.setHeaderList(headerList);
folderProcessModel.setHeaderId(headerId);
}
}
I have some questions:
Here this code use if (userReorderSelection == null || userReorderSelection == ""). Can i use this condition if (userReorderSelection == null) ?
What is the difference between two ?
== null checks for null reference.
== "" check for blank/empty string reference. Here you could use str.equals("") to check if the string is empty/blank or not. == is used for object reference checks. Or you can use the String.isEmpty() to check the same.
Also, if you use just if (userReorderSelection == null), then you'll only be checking if the userReorderSelection is null or not and it won't determine whether the String is empty or not.
As everyone replied:
"" checks for empty String.
null checks for null reference.
Use StringUtils from apache commons to eliminate two conditions. StringUtils.isEmpty(yourVariable) this condition will handle both cases.
"" --> indicates empty String in Java. Rather than using userReorderSelection == "" it is preferable to us
userReorderSelection.isEmpty() // But make sure that userReorderSelection is not null
null --> indicates Null references (can be reference of any object)
If you do not have this check it may result in NullPointerException if you try to use this reference. Empty String will not throw such exceptions.
== null checks to see if the object reference is null.
== "" checks to see if the object reference equals a blank string
str.equals ("") checks to see if your String object contains the empty string.
I guess what you want is
if (userReorderSelection == null || userReorderSelection.equals (""))
How to handle null when using Pattern.compile? I'm using the following line to compare strings:
Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find()
There are some cases where s1 can be null and obviously it throws NullPointerException. I know this could be handled by another if condition to s1, but I would like to know is there's an alternate solution.
EDIT
Iterator iter = sampleList().iterator();
while (iter.hasNext()) {
SampleObj so = (SampleObj) iter.next();
if (!s1.equalsIgnoreCase("")) {
if (Pattern.compile(Pattern.quote(s1), Pattern.CASE_INSENSITIVE).matcher(so.getS1()).find())
match = true;
else
match = false;
}
if (!s3.equalsIgnoreCase("")) {
if (Pattern.compile(Pattern.quote(s3), Pattern.CASE_INSENSITIVE).matcher(so.getS3()).find())
match = true;
else
match = false;
}
}
s1 and s3 are inputs which are matched over iterator.
You have to check for null; e.g.,
if(s1 != null && Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find()))
Pattern.matcher() will always throw a NullPointerException when you pass in null, so: no, there is no other way, you'll have to check for null explicitly.
I use
String.valueOf(s1)
which results in having "null" instead of null.