Compare two objects in Java with possible null values - java

I want to compare two strings for equality when either or both can be null.
So, I can't simply call .equals() as it can contain null values.
The code I have tried so far :
boolean compare(String str1, String str2) {
return ((str1 == str2) || (str1 != null && str1.equals(str2)));
}
What will be the best way to check for all possible values including null ?

Since Java 7 you can use the static method java.util.Objects.equals(Object, Object) to perform equals checks on two objects without caring about them being null.
If both objects are null it will return true, if one is null and another isn't it will return false. Otherwise it will return the result of calling equals on the first object with the second as argument.

This is what Java internal code uses (on other compare methods):
public static boolean compare(String str1, String str2) {
return (str1 == null ? str2 == null : str1.equals(str2));
}

For these cases it would be better to use Apache Commons StringUtils#equals, it already handles null strings. Code sample:
public boolean compare(String s1, String s2) {
return StringUtils.equals(s1, s2);
}
If you dont want to add the library, just copy the source code of the StringUtils#equals method and apply it when you need it.

For those on android, who can't use API 19's Objects.equals(str1, str2), there is this:
android.text.TextUtils.equals(str1, str2);
It is null safe. It rarely has to use the more expensive string.equals() method because identical strings on android almost always compare true with the "==" operand thanks to Android's String Pooling, and length checks are a fast way to filter out most mismatches.
Source Code:
/**
* Returns true if a and b are equal, including if they are both null.
* <p><i>Note: In platform versions 1.1 and earlier, this method only worked well if
* both the arguments were instances of String.</i></p>
* #param a first CharSequence to check
* #param b second CharSequence to check
* #return true if a and b are equal
*/
public static boolean equals(CharSequence a, CharSequence b) {
if (a == b) return true;
int length;
if (a != null && b != null && (length = a.length()) == b.length()) {
if (a instanceof String && b instanceof String) {
return a.equals(b);
} else {
for (int i = 0; i < length; i++) {
if (a.charAt(i) != b.charAt(i)) return false;
}
return true;
}
}
return false;
}

Using Java 8:
private static Comparator<String> nullSafeStringComparator = Comparator
.nullsFirst(String::compareToIgnoreCase);
private static Comparator<Metadata> metadataComparator = Comparator
.comparing(Metadata::getName, nullSafeStringComparator)
.thenComparing(Metadata::getValue, nullSafeStringComparator);
public int compareTo(Metadata that) {
return metadataComparator.compare(this, that);
}
Or you can also use the below method using Java
public static boolean compare(String first, String second) {
return(Objects.isNull(first) ? Objects.isNull(second) :
first.equals(second));
}

Since version 3.5 Apache Commons StringUtils has the following methods:
static int compare(String str1, String str2)
static int compare(String str1, String str2, boolean nullIsLess)
static int compareIgnoreCase(String str1, String str2)
static int compareIgnoreCase(String str1, String str2, boolean nullIsLess)
These provide null safe String comparison.

Compare two string using equals(-,-) and equalsIgnoreCase(-,-) method of Apache Commons StringUtils class.
StringUtils.equals(-, -) :
StringUtils.equals(null, null) = true
StringUtils.equals(null, "abc") = false
StringUtils.equals("abc", null) = false
StringUtils.equals("abc", "abc") = true
StringUtils.equals("abc", "ABC") = false
StringUtils.equalsIgnoreCase(-, -) :
StringUtils.equalsIgnoreCase(null, null) = true
StringUtils.equalsIgnoreCase(null, "abc") = false
StringUtils.equalsIgnoreCase("xyz", null) = false
StringUtils.equalsIgnoreCase("xyz", "xyz") = true
StringUtils.equalsIgnoreCase("xyz", "XYZ") = true

You can use java.util.Objects as following.
public static boolean compare(String str1, String str2) {
return Objects.equals(str1, str2);
}

boolean compare(String str1, String str2) {
if(str1==null || str2==null) {
//return false; if you assume null not equal to null
return str1==str2;
}
return str1.equals(str2);
}
is this what you desired?

boolean compare(String str1, String str2) {
if (str1 == null || str2 == null)
return str1 == str2;
return str1.equals(str2);
}

boolean compare(String str1, String str2) {
return (str1==null || str2==null) ? str1 == str2 : str1.equals(str2);
}

OK, so what does "best possible solution" mean?
If you mean most readable, then all the possible solutions are pretty much equivalent for an experienced Java programmer. But IMO the most readable is this
public boolean compareStringsOrNulls(String str1, String str2) {
// Implement it how you like
}
In other words, hide the implementation inside a simple method that (ideally) can be inlined.
(You could also "out-source" to a 3rd party utility library ... if you already use it in your codebase.)
If you mean most performant, then:
the most performant solution depends on the platform and the context,
one of the "context" issues is the relative (dynamic) frequency of occurrence of null arguments,
it probably doesn't matter which version is faster ... because the difference is probably too small to make a difference to the overall application performance, and
if it does matter, the only way to figure out which is fastest ON YOUR PLATFORM is to try both versions and measure the difference.

Related

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()));
}

Spring Expression Language (SpEL) in Spring Security to compare object use equals() or ==?

Spring Expression Language (SpEL) in Spring Security to compare object use equals() or ==?
For example(method equals () is not called!):
class SecurityObject {
public boolean equals(Object obj) {
//...
}
}
#PreAuthorize(" #secObject == #otherSecObject ")
public void securityMethod(SecurityObject secObject, SecurityObject otherSecObject) {
//...
}
This is normal!? I need to use #PreAuthorize(" #secObject.equals(#otherSecObject) ") everywhere?
UPDATE
Why in first case Spring Security calling .equals(), and the second not?
//TestObject
public class TestObject {
private static final Logger log = LoggerFactory.getLogger(TestObject.class);
private Long id;
public TestObject(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + Objects.hashCode(this.id);
return hash;
}
#Override
public boolean equals(Object obj) {
log.info("equals");
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TestObject other = (TestObject) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
}
//TestService
#PreAuthorize(" #one == #two ")
public String testEqualsInAnnotation(Long one, Long two) {
//...
}
#Override
#PreAuthorize(" #one == #two ")
public String testEqualsInAnnotation(TestObject one, TestObject two) {
//...
}
//Test
log.info("for Long");
Long one = new Long(500);
Long two = new Long(500);
log.info("one == two: {}", (one==two)? true : false); // print false
log.info("one equals two: {}", (one.equals(two))? true : false); // print true
testService.testEqualsInAnnotation(one, two); //OK
log.info("for TestObject");
TestObject oneObj = new TestObject(new Long(500));
TestObject twoObj = new TestObject(new Long(500));
log.info("oneObj == twoObj: {}", (oneObj==twoObj)? true : false); // print false
log.info("oneObj equals twoObj: {}", (oneObj.equals(twoObj))? true : false); // print true
testService.testEqualsInAnnotation(oneObj, twoObj); // AccessDeniedException: Access is denied
UPDATE 2
equals() never invoked at all
package org.springframework.expression.spel.ast;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.spel.ExpressionState;
import org.springframework.expression.spel.support.BooleanTypedValue;
/**
* Implements equality operator.
*
* #author Andy Clement
* #since 3.0
*/
public class OpEQ extends Operator {
public OpEQ(int pos, SpelNodeImpl... operands) {
super("==", pos, operands);
}
#Override
public BooleanTypedValue getValueInternal(ExpressionState state) throws EvaluationException {
Object left = getLeftOperand().getValueInternal(state).getValue();
Object right = getRightOperand().getValueInternal(state).getValue();
if (left instanceof Number && right instanceof Number) {
Number op1 = (Number) left;
Number op2 = (Number) right;
if (op1 instanceof Double || op2 instanceof Double) {
return BooleanTypedValue.forValue(op1.doubleValue() == op2.doubleValue());
} else if (op1 instanceof Long || op2 instanceof Long) {
return BooleanTypedValue.forValue(op1.longValue() == op2.longValue());
} else {
return BooleanTypedValue.forValue(op1.intValue() == op2.intValue());
}
}
if (left!=null && (left instanceof Comparable)) {
return BooleanTypedValue.forValue(state.getTypeComparator().compare(left, right) == 0);
} else {
return BooleanTypedValue.forValue(left==right);
}
}
}
As per spEL documentation, You need to create ExpressionParser instance, create an Expression instance and get the value like below
String name = "Nikola Tesla";
Expression exp = parser.parseExpression("name == 'Nikola Tesla'");
boolean result = exp.getValue(Boolean.class);
result evaluates to 'true'. That says when we need to compare any two objects, then we need to override the equals() method and pass the two objects in to parser#parseExpression("obj1 == obj2") and then call the exp#getValue(Boolean.class) to evaluate. In the similar way, the Expression instance can also have expression string containing Obj1.equals(Obj2) for checking the equality. so, both the ways of checking equality are possible with spEL.
You may have discovered this already, since it is in the OpEq code in 'Update 2' of the original post, but...
The comparison operators lt < gt > le <= ge >= eq == ne != are based on java's Comparable interface.
So, if you've got a custom type that you want to be able to compare using == or != in SpEL expressions, then you could write it to implement Comparable.
Of course, then you'll have to figure out some sane rule to decide which object is before the other when they're not equivalent.
That said, I can't find anything in Spring's current documentation indicating this.
rdm, I think you have to use permission evaluator to evaluate the expressions. I don't think you have really injected/passed values for the objects in the following expression.
#Override
#PreAuthorize(" #one == #two ")
public String testEqualsInAnnotation(TestObject one, TestObject two) {
//...
I tried to do the same thing, but I failed to pass values, hence couldn't able to evaluate the expressions. My suggestion is to implement your custom permission evaluator for the above expression, and inject/pass values from the evaluator. To generalize my idea, my suspect is the objects are null, that is why you couldn't able to evaluate it. Please let us know if you can really pass values of the objects inside here : #PreAuthorize(" #one == #two ")
Added:
I am using permission evaluator to evaluate expressions under #PreAuthorize(...) annotation. Because I couldn't able to pass values to the parameters as I explained above. If it is possible to pass/inject values, it will be good to reduce complexity that can come from using permission evaluator.
rdm or others, can you point me how to pass the values for the parameters under #PreAuthorize(...) if possible?
Sorry for asking another question on rdm's post, and thank you in advance for your help!.

Serialize Boolean to "1" and "0" instead of "true" and "false"

I can't find any method on the Boolean class to serialize a Boolean to "1" and "0" instead of "true" and "false".
Is there any native function to do that ? If not, what is the best way (most optimized way) ?
Update: I indeed mean to produce a String out of a Boolean.
If you're talking about producing a String from a given Boolean, then no, there is no built-in method that produces "0" or "1", but you can easily write it:
public static String toNumeralString(final Boolean input) {
if (input == null) {
return "null";
} else {
return input.booleanValue() ? "1" : "0";
}
}
Depending on your use case, it might be more appropriate to let it throw a NullPointerException if input is null. If that's the case for you, then you can reduce the method to the second return line alone.
You can use CompareTo:
public static Integer booleanToInteger(Boolean bool)
{
if(bool == null) return null;
else return bool.compareTo(Boolean.FALSE);
}
If you want to serialise to a char you can do
public static char toChar(final Boolean b) {
return b == null ? '?' : b ? '1' : '0';
}
I am not sure but just throwing it out. you can use your own Decorator class.
Use Thrift API:
TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
String json = serializer.toString(object);
It will boolean to 0 or 1 instead of true/false.

evaluate boolean values in Java

I am trying to evaluate the following from a string
boolean value = evaluate("false || true && true && false || true");
I need to get a boolean value of true for this one.
Any ideas on how to solve this problem in the most efficient way?
String value = ("false || true && true && false || true");
boolean result = false;
for (String conj : value.split("\\|\\|")) {
boolean b = true;
for (String litteral : conj.split("&&"))
b &= Boolean.parseBoolean(litteral.trim());
result |= b;
}
System.out.println(result); // prints true
If the only operators are && and ||, then I think this will work:
static boolean eval(String str) {
String s = str.replaceAll("\\s|\\|\\|false|false\\|\\|", "");
return !s.contains("false") || s.contains("||true");
}
For more complicated expressions, I found this library just for that.
Don't know how efficient it is though.
You'll need a small boolean expressions grammar. A bit of recursive parsing should do the trick.
If you don't know how to write such a parser, you may use JavaCC or something similar.
there are parsergenerators available for which you can define a grammar.
But if you only got || and && as operators and true and false as values you can easily do this by yourself, by implmenting a very simple finite state machine:
1.) Split the string into the tokens
2.) parse the left most value by using Boolean.parseBoolean(token) and safe it's value in some instance variable (your state)
3.) combine your instance variable with the next boolean token using the given operator
4.) Repeat step3 until you finished through the whole string
This seems to work although i havent thorougly tested it :)
public class BooleanFSParser {
private boolean parse(String data) {
String[] tokens=data.split("\\s");
boolean state=Boolean.parseBoolean(tokens[0]);
for (int i=1;i<(tokens.length / 2) + 1;i=i+2){
if (tokens[i].equals("&&")){
state=state && Boolean.parseBoolean(tokens[i+1]);
}else{
state=state || Boolean.parseBoolean(tokens[i+1]);
}
}
return state;
}
public static void main(String[] args) {
BooleanFSParser parser = new BooleanFSParser();
boolean val = parser.parse("true && true || false");
System.out.println(String.valueOf(val));
}
}
thats should give you a cirrectly parsed value, but it will get a bit more complex if you allow brackets for example ;)
have fun and check here for the theory
Finite-state_machine

How to check if String value is Boolean type in Java?

I did a little search on this but couldn't find anything useful.
The point being that if String value is either "true" or "false" the return value should be true. In every other value it should be false.
I tried these:
String value = "false";
System.out.println("test1: " + Boolean.parseBoolean(value));
System.out.println("test2: " + Boolean.valueOf(value));
System.out.println("test3: " + Boolean.getBoolean(value));
All functions returned false :(
parseBoolean(String) returns true if the String is (case-insensitive) "true", otherwise false
valueOf(String) ditto, returns the canonical Boolean Objects
getBoolean(String) is a red herring; it fetches the System property of the given name and compares that to "true"
There exists no method to test whether a String encodes a Boolean; for all practical effects, any non-"true"-String is "false".
return "true".equals(value) || "false".equals(value);
Apache commons-lang3 has BooleanUtils with a method toBooleanObject:
BooleanUtils.toBooleanObject(String str)
// where:
BooleanUtils.toBooleanObject(null) = null
BooleanUtils.toBooleanObject("true") = Boolean.TRUE
BooleanUtils.toBooleanObject("false") = Boolean.FALSE
BooleanUtils.toBooleanObject("on") = Boolean.TRUE
BooleanUtils.toBooleanObject("ON") = Boolean.TRUE
BooleanUtils.toBooleanObject("off") = Boolean.FALSE
BooleanUtils.toBooleanObject("oFf") = Boolean.FALSE
BooleanUtils.toBooleanObject("blue") = null
if ("true".equals(value) || "false".equals(value)) {
// do something
} else {
// do something else
}
Here's a method you can use to check if a value is a boolean:
boolean isBoolean(String value) {
return value != null && Arrays.stream(new String[]{"true", "false", "1", "0"})
.anyMatch(b -> b.equalsIgnoreCase(value));
}
Examples of using it:
System.out.println(isBoolean(null)); //false
System.out.println(isBoolean("")); //false
System.out.println(isBoolean("true")); //true
System.out.println(isBoolean("fALsE")); //true
System.out.println(isBoolean("asdf")); //false
System.out.println(isBoolean("01truefalse")); //false
The methods you're calling on the Boolean class don't check whether the string contains a valid boolean value, but they return the boolean value that represents the contents of the string: put "true" in string, they return true, put "false" in string, they return false.
You can surely use these methods, however, to check for valid boolean values, as I'd expect them to throw an exception if the string contains "hello" or something not boolean.
Wrap that in a Method ContainsBoolString and you're go.
EDIT
By the way, in C# there are methods like bool Int32.TryParse(string x, out int i) that perform the check whether the content can be parsed and then return the parsed result.
int i;
if (Int32.TryParse("Hello", out i))
// Hello is an int and its value is in i
else
// Hello is not an int
Benchmarks indicate they are way faster than the following:
int i;
try
{
i = Int32.Parse("Hello");
// Hello is an int and its value is in i
}
catch
{
// Hello is not an int
}
Maybe there are similar methods in Java? It's been a while since I've used Java...
Actually, checking for a Boolean type in a String (which is a type) is impossible. Basically you're asking how to do a 'string compare'.
Like others stated. You need to define when you want to return "true" or "false" (under what conditions). Do you want it to be case(in)sensitive? What if the value is null?
I think Boolean.valueOf() is your friend, javadoc says:
Returns a Boolean with a value represented by the specified String. The Boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
Example: Boolean.valueOf("True") returns true.
Example: Boolean.valueOf("yes") returns false.
Can also do it by regex:
Pattern queryLangPattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
Matcher matcher = queryLangPattern.matcher(booleanParam);
return matcher.matches();
Yes, but, didn't you parse "false"? If you parse "true", then they return true.
Maybe there's a misunderstanding: the methods don't test, if the String content represents a boolean value, they evaluate the String content to boolean.
String value = "True";
boolean result = value.equalsIgnoreCase("true") ? true : false;
Well for this, also have a look at org.apache.commons.lang.BooleanUtils#toBoolean(java.lang.String), along with many other useful functions.
return value.equals("false") || value.equals("true");
Something you should also take into consideration is character casing...
Instead of:
return value.equals("false") || value.equals("true");
Do this:
return value.equalsIgnoreCase("false") || value.equalsIgnoreCase("true");
I suggest that you take a look at the Java docs for these methods. It appears that you are using them incorrectly. These methods will not tell you if the string is a valid boolean value, but instead they return a boolean, set to true or false, based on the string that you pass in, "true" or "false".
http://www.j2ee.me/javase/6/docs/api/java/lang/Boolean.html
See oracle docs
public static boolean parseBoolean(String s) {
return ((s != null) && s.equalsIgnoreCase("true"));
}
function isBooleanString(val) {
if (val === "true" || val === "false"){
return true
} else {
return false
}
}
isBooleanString("true") // true
isBooleanString("false") // true
isBooleanString("blabla") // false

Categories