Issue with boolean test [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I seem to be having a problem with a boolean test. when I use this code:
public boolean setPkg (String inPkg)
{
boolean isValid;
if ((inPkg.toUpperCase() != "A" ) || (inPkg.toUpperCase() != "B" ) || (inPkg.toUpperCase() != "C"))
isValid = false;
else
{
pkg = inPkg;
isValid = true;
}
return isValid;
}
It returns false on "A". However when I only test for "A":
...
if (inPkg.toUpperCase() != "A" )
isValid = false;
else
{
pkg = inPkg;
isValid = true;
}
return isValid;
...
it returns true.
what am I missing?
I have also tried to use multiple if else statements to test for A, B, or C and i get false for A. B and C dont get tested as an exception of my making is getting thrown.

Two things over here :
replace != with equals method for comparison
replace || with &&

Always use oneString.equals(otherString), not oneString == otherString, when comparing strings.
For example, instead of:
(inPkg.toUpperCase() != "A" )
use this instead:
(!(inPkg.toUpperCase().equals("A")))
NEVER compare strings with == or !=. See: How do I compare strings in Java?

The issue is that you're using == to compare strings. This doesn't do what you think it does (it compares string references, not the character sequences).
Use s1.equals(s2) instead, as in
!inPkg.toUpperCase().equals("A")
etc.
See Java comparison with == of two strings is false?

== and != compares the Object references. they are not equal as they are not the same object.
String.equals(otherString) compares the content of the String. You want to use this function.

Related

Variable nonSmoking is always null. How to set it to 1 or 0? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
When the code is 20, nonSmoking should be 1, but always returns null. After debugging I saw that it always returns null
How to set a variable nonSmoking correctly?
public static String mapSmokingAmenities(ContentFragmentList list){
SolrContentFragment solrFragments = list.getFragment(SolrContentFragment.class);
List<String> ausstattungPositions = solrFragments.getAusstattungPosition();
String nonSmoking = new String();
for(String code : ausstattungPositions){
if(code == "20" || code == "36"){
nonSmoking = "1";
}
if(code == "51"){
nonSmoking ="0";
}
}
return nonSmoking;
}
Comparing objects using == compares the address. You can find out if a object points to the same instance you want to work with. Only primitive datatypes (int/...) can be compared with value like that.
For Strings as being object please use equals() method for the value compare.
If you have custom DTO/POJO where you want to compare value and not reference you need to overwrite the hashCode and equals method there.
Probably this could help
public static String mapSmokingAmenities(ContentFragmentList list){
SolrContentFragment solrFragments = list.getFragment(SolrContentFragment.class);
List<String> ausstattungPositions = solrFragments.getAusstattungPosition();
String nonSmoking = "";
for(String code : ausstattungPositions){
switch(code) {
case "20":
case "36":
nonSmoking = "1";
break;
case "51":
nonSmoking = "0";
break;
default:
// do nothing
break;
}
}
return nonSmoking;
}
You should use an enum for your codes and your result. Be aware, that you set nonSmoking every time being code 20, 36 or 51. Probably you should break your for loop. Don't create a new String but use an empty String "".

How to compare two Booleans in Java? [duplicate]

This question already has answers here:
Compare two objects with a check for null
(7 answers)
Closed 5 years ago.
I have to compare two Boolean wrappers with each other. As a result I want to know if they are equal or not.
This is what I came up with:
public static boolean areEqual(final Boolean a, final Boolean b) {
if (a == b) {
return true;
}
if (a != null && b != null) {
return a.booleanValue() == b.booleanValue();
}
return false;
}
Is there a better and/or shorter way to correctly compare two Boolean wrappers for equality?
First I wanted to use Object.equals() or Boolean.compareTo() but both ways could end up in a NullPointerException, right?
Maybe there is something that I don't see here, that's why I'm asking.
The shortest you can get, with null safety (works naturally for any other objects that implement equals()):
java.util.Objects.equals(a, b);
There is no need for you to reinvent the wheel.
If you are using Java 7 or later, use the java.util.Objects class (as mentioned by Kayaman).
If you are using an earlier version of java, use the Apache BooleanUtils class.
Try a google search for "apache booleanutils" to find out how to get it.
Edit: corrected java version.
It is working for me.
public class MyClass {
public static void main(String args[]) {
Boolean x=true;
Boolean y=true;
System.out.println(compare(x,y)); // true
x=false;
y=true;
System.out.println(compare(x,y)); // false
x=true;
y=false;
System.out.println(compare(x,y)); // false
x=false;
y=false;
System.out.println(compare(x,y)); // true
x=null;
y=null;
System.out.println(compare(x,y)); // true
}
public static boolean compare(final Boolean a, final Boolean b) {
if (a == null || b == null) {
return a == b;
}
return a.equals(b);
}
}
Probe with https://www.jdoodle.com/online-java-compiler
Edit: add exception to null values.

Why following code printing False? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
Replace will create new object and both side this new will be compared. then why it showing false.
When exactly created new string will be added in string pool?
if("String".replace("g", "G") == "String".replace("g", "G"))
{
System.out.println("True");
} else {
System.out.println("False");
}
because replace() will always return a new String instance. So the 2 same calls to replace method will return 2 different instances with same value.
use equals() instead of == if you want to compare value
Use intern() on both replaced values if you want to add the string to the string constants pool (and are bent on using == :P)
if ("String".replace("g", "G").intern() == "String".replace("g", "G").intern()) {
System.out.println("True");
} else {
System.out.println("False");
}
}
OP :
true

About substring testing in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm writing some codes that test if there is "xx" in a string. For instance, doubleX("aaxxbb") should return true, and doubleX("axabb") should return false.
Here is my code:
private static boolean doubleX(String str) {
for(int i=0;i<str.length()-1;i++){
System.out.println(str.substring(i,i+2));
if(str.substring(i,i+2) == "xx") return true;
}
return false;
}
Why does doubleX("aaxxbb") return false?
You have to use .equals instead of ==. For more information, follow the duplication message.
return str.contains("xx");
Is a lot clearer though.
You should understand the difference between == and equals: the first one compares references, the second compares actual values.
Your code is wildly inefficient.
I'd try something like this:
private static boolean doubleX(String str) {
return (str.indexOf("xx") != -1);
}
Use equals() for checking the content of a String to another rather than ==. == checks for reference equality.
private static boolean doubleX(String str) {
for(int i=0;i<str.length()-1;i++){
System.out.println(str.substring(i,i+2));
if(str.substring(i,i+2).equals("xx")) return true;
}
return false;
}
Even you can directly code like:
private static boolean doubleX(String str) {
return str.contains("xx");
}

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