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");
}
Related
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.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
public static boolean stringToBoolean (String horv) {
if (horv == "H") {
return true;
} if (horv == "V") {
return false;
} else {
return true;
}
This is a small part of a program I am creating. The program is reading from a file and inputting the data into an array. For this part it is reading what will either be a "H" or "V" from the file and converting it to a boolean value. The problem is when I run the program I am only getting true for every value, even the ones that have a "V" as their variable.
Change the code to be:
if ("H".equals(horv)) { return true; }
...
Try This
public static boolean stringToBoolean (String horv) {
if ("H".equals(horv)) { // use equals method for string comparison
return true;
} if ("V".equals(horv)) {
return false;
} else {
return true;
}
String variables should be compared with equals() method in java.
In Java you have compare String with a method equals() Like this
public static boolean stringToBoolean (String horv) {
if (horv.equals("H")) return true;
if (horv.equals("V")) return false;
return true;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
public static void main(String args[]) throws IOException
{
String s1="abc";
String s2="xyz";
String s3="abcxyz";
String s4=s1.concat(s2);
System.out.println(s4);
#SuppressWarnings("unused")
String s5=s1+s2;
if(s3==s4)
{
System.out.println("true");
}
else
System.out.println("false");
}
Why the o/p is coming as false? According to me it should be true. Can someone please explain
java.lang.String concat() function return new String() object Here s3 and s4 are two different references pointing to two different objects.
== just checks for refernces wheras .equals() checks for the actual content.
s3.equals(s4) will return true.
From javadoc, concat() function.
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
== operator compares String value as well as String memory location. Here, s3 and s4 are using different memory locations.
If you want to compare values of String then you should use s3.equals(s4). It will result into true condition.
I have two arrayLists<myObject>, where myObject is an object of a custom class I've created. I want to be able to compare those arrayLists using the equals() method.
After reading and looking for answers, I've read that certain objects like int[] are only considered equal by the equals() method when they are referencing the same thing.
To fix that, I tried to override the equals method in my custom object. My objects have 3 atributes (all basic types), so my equals method now returns true if all the 3 atributes are equal to those of the object compared, and false otherwise. However, comparing the arraylists still doesn't work. What am I doing wrong?
Excuse me for explaining the code instead of posting it, I do it because the variables and names aren't in English.
EDIT: Ok, here's the code. Compra is my custom class; cantidad,concepto and id are its atributes.
#Override
public boolean equals(Object obj) {
boolean result = true;
if (obj == null) {
result = false;
}else{
Compra comprobada = (Compra) obj;
if(!(this.id == comprobada.getId())){
result = false;
}
if(!(this.cantidad == comprobada.getCantidad())){
result = false;
} if(!this.concepto.equals(comprobada.getConcepto())){
result = false;
}
}
return result;
}
Based on this one :
How can I check if two ArrayList differ, I don't care what's changed
If you have implemented your custom object equals correct (you actually override it and have your one) and the size of the arrayList is the same and each of the pair of the objects is equal then it will return equal. In other words what you are trying to do is totally correct but your arrayLists are not actually having exactly the equal objects in exact order.
Make sure that your equal is called when you check for collection equality by doing a System.out.println() to investigate what is going on.
If you don't mind please send the equals of your object.
I run your code in an isolated example and works fine (outtputs true) - I improved the equals method so it doesn't do so many if checks as if only one of them is not equal it should return false.
class stackoverflow {
public static void main(String args[]){
ArrayList<Compra> array1 = new ArrayList<>();
ArrayList<Compra> array2 = new ArrayList<>();
array1.add(new Compra(1,2,"test"));
array2.add(new Compra(1,2,"test"));
System.out.println(array1.equals(array2));
}
}
class Compra {
int id;
int cantidad;
String concepto;
public Compra(int id, int cantidad, String concepto){
this.id = id;
this.cantidad = cantidad;
this.concepto = concepto;
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}else{
Compra comprobada = (Compra) obj;
if(!(this.id == comprobada.getId())){
return false;
}
if(!(this.cantidad == comprobada.getCantidad())){
return false;
}
if(!this.concepto.equals(comprobada.getConcepto())){
return false;
}
}
return true;
}
public int getId() {
return id;
}
public int getCantidad() {
return cantidad;
}
public String getConcepto() {
return concepto;
}
}
Some things to check:
Are you sure you don't change the order of the things in ArrayList??:
Do you print to make sure that these equals checks happen and return true or false as expected?
Are you sure that concepto Strings are exactly the same, with the same case and don't contain extra spaces etc?
As you haven't posted code i suggest you to check into Comparable class and method compareTo and how to use it for custom classes.
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.