Why aren't my Strings showing as equal when they are? - java

I am currently working in Eclipse making a Android App. At the moment I have two Strings and I need to check if they are equal or not, the problem is the Strings are equal but it is showing them not to be which is really frustrating me.
if (newSource.equals(source)) {
Log.d("Equal:", "Strings are equal");
}
else {
Log.d("Not Equal: ", "Strings aren't equal");
}
When I run this it just prints in the log cat that the strings aren't equal. I have printed both strings in the log cat to check that they are 100% equal which they are. I was just wondering if any one could see an error in my code?
Thanks

Its because the strings aren't really equal. To see the byte representation of your strings, you can do
System.out.println(Arrays.toString(str1.getBytes()));
System.out.println(Arrays.toString(str2.getBytes()));

Use trim() which will eleminate spaces if any
if ((newSource.trim()).equals(source.trim()))

try as using String.equalsIgnoreCase
if (newSource.trim().equalsIgnoreCase(source.trim())) {
Log.d("Equal:", "Strings are equal");
}
else {
Log.d("Not Equal: ", "Strings aren't equal");
}
becuase it's possible string contains spaces,lower and uppercase letters

Related

String compare function equals not giving correct result

I am using eclipse with java
I am trying to compare two string removing all the space between them.
Here is my code
First I am removing whitespace within the Strings.
System.out.println("["+StringUtils.deleteWhitespace(s4)+"]");
System.out.println("["+StringUtils.deleteWhitespace(s3)+"]");
// comparing Strings
if(s4.equals(s3))
{
System.out.println("Text Match");'
}
Below is the output from lines 1 and 2 that is displaying on Eclipse console:
[gnarlyadj.Somethingthatisgnarlyhasmanyknotsandbumpyareasonitssurface.nudosoadj.Algonudosotienemuchosnudosyunasuperficiellenadebultos.]
[gnarlyadj.Somethingthatisgnarlyhasmanyknotsandbumpyareasonitssurface.nudosoadj.Algonudosotienemuchosnudosyunasuperficiellenadebultos.]
From what I can see, there is no difference between two string yet it is displaying string as a mismatch.
You did not assign the results of the deleteWhitespace() operation to anything. Your two strings will therefore remain unchanged.
Store the result like so, before printing it:
s4 = StringUtils.deleteWhitespace(s4);
The method StringUtils.deleteWhitespace(s4) does not change the String referenced by s4 (Strings are immutable) but returns a new string.
If you do the following code:
s3 = StringUtils.deleteWhitespace(s3);
s4 = StringUtils.deleteWhitespace(s4);
if (s4.equals(s3)) {
System.out.println("Text Match");'
}
Then you will see that the two strings are really equal and the "Text Match" is printed.

What will be the output from the following three code segments?

I'm currently on a self learning course for Java and have gotten completely stumped at one of the questions and was wonder if anyone can help me see sense...
Question: What will be the output from the following three code segments? Explain fully the differences.
public static void method2(){
String mystring1 = "Hello World";
String mystring2 = new String("Hello World");
if (mystring1.equals(mystring2)) {
System.out.println("M2 The 2 strings are equal");
} else {
System.out.println("M2 The 2 strings are not equal");
}
}
public static void method3(){
String mystring1 = "Hello World";
String mystring2 = "Hello World";
if (mystring1 == mystring2) {
System.out.println("M3 The 2 strings are equal");
} else {
System.out.println("M3 The 2 strings are not equal");
}
}
The answer I gave:
Method 2:
"M2 The 2 strings are equal"
It returns equal because even though they are two separate strings the (mystring1.equals(mystring2)) recognises that the two strings have the exact same value. If == was used here it return as not equal because they are two different objects.
Method 3:
"M2 The 2 strings are equal"
The 2 strings are equal because they are both pointing towards the exact same string in the pool. == was used here making it look at the two values and it recognises that they both have the exact same characters. It recognises that Hello World was already in the pool so it points myString2 towards that string.
I was pretty confident in my answer but it's wrong. Any help?
Both will return true.
1) 2 new string objects are created but use .equals which means their actual value is compared. Which is equal.
2) 1 new string object is created because they are both constant at compile time. This will result in them pointing to the same object.
This sentence might be your issue:
== was used here making it look at the two values and it recognises that they both have the exact same characters.
== checks for reference equality whereas you're describing value equality.
First two are equal, second two are not. But unless you put it into main() method there will be no output at all.
EDIT: second pair are not the same because "==" compares addresses in memory.
You're right about the first one.
However the second would return "M3 The 2 strings are not equal".
This is because == tests for reference equality and since they are two different variables, they would not equal.

android splinting Strings

I I have is a server witch is sending me a String such as "False~False~False~True~False~True~False~" or something of that nature so what I have done is I did a split on that string to the "~" so my code was String[] AString = A2MCString.split("~"); with the new string array I have I went to a cheack to see if each sections was true or false using an if else statment
if (AString[0] == "True") {
Log.d("ClientActivity","Light ON");
On1.setBackgroundResource(R.drawable.selected_on);
}
else Log.d("ClientActivity","Light OFF");
however even when the server send me true in the first part of my string array the array still bounces to else saying that it is false even though it was true? Any help for my problem thanks!
When comparing strings in java you must use the equals method. In your case something like
if (AString[0].equals("True")) {
Log.d("ClientActivity","Light ON");
On1.setBackgroundResource(R.drawable.selected_on);
}
else Log.d("ClientActivity","Light OFF");
When using the == operator on objects (in java a string is an object), it is comparing if the two object references point to the same object.

Beginners Java Question (string output)

So I'm reading input from a file, which has say these lines:
NEO
You're the Oracle?
NEO
Yeah.
So I want to output his actual lines only, not where it says NEO. So I tried this:
if(line.trim()=="NEO")
output=false;
if (output)
TextIO.putln(name + ":" + "\"" + line.trim() + "\""); // Only print the line if 'output' is true
But thats not working out. It still prints NEO. How can I do this?
When comparing strings in Java you have to use the equals() method. Here's why.
if ( "NEO".equals(line.trim() )
I think you're looking for line.trim().equals("NEO") instead of line.trim() == "NEO"
That said, you can get rid of the output variable by instead doing
if(!line.trim().equals("NEO"))
{
TextIO.putln(name + ":" + "\"" + line.trim() + "\""); // Only print the if it isn't "NEO"
}
Strings are objects in Java. This means you can't just use the == operator to compare them, since the two objects will be different even if they both represent the same string. That's why the String object implements an equal() method, which will compare the contents of the objects, instead of just their memory addresses.
Reference
String.equals() docs
In Java, Strings are objects. And the == operator checks for exact equality.
In other terms
final String ans = line.trim();
final String neo = "NEO";
if (ans == neo) ...
implies you want to check that the ans and the neo objects are the same. They are not, since Java allocated (instantiated) two objects.
As other said, you have to test for equality using a method created for the String object, that actually, internally, checks the values are the same.
if (ans.equals(neo)) ...
try the following:
if(line.trim().equals("NEO"))

Odd comparison problem in checking for anagram

I'm sorry, the title's awful; however, I couldn't think of any better way to summarize my plight.
In trying to solve a problem involving checking to see if one string is an anagram of another, I implemented a solution that involved removing all whitespace from both strings, converting them both to character arrays, sorting them and then seeing if they are equal to eachother.
If so, the program prints out "Is an anagram.", otherwise "Is not an anagram."
The problem is that even though my code compiles successfully and runs fine, the end result will always be "Is not an anagram.", regardless of whether or not the two original strings are indeed anagrams of each other. Quick code I inserted for debugging shows that, in a case with an actual anagram, the two character arrays I end up comparing are apparently identical, yet the result of the comparison is false.
I can't tell why exactly this is happening, unless I'm overlooking something incredibly obvious or there are some extra undisplayed characters in what I compare.
Here's the code:
import java.util.Arrays;
import java.util.Scanner;
public class Anagram {
public static void main(String[] args) {
char[] test1;
char[] test2;
Scanner input = new Scanner(System.in);
System.out.print("Enter first phrase>");
test1 = input.nextLine().replaceAll(" ", "").toCharArray();
Arrays.sort(test1);
System.out.print("Enter second phrase>");
test2 = input.nextLine().replaceAll(" ", "").toCharArray();
Arrays.sort(test2);
if (test1.equals(test2)) {
System.out.println("Is an anagram.");
}
else {
System.out.println("Is not an anagram.");
}
/* debugging */
System.out.println(test1);
System.out.println(test2);
System.out.println(test1.equals(test2));
}
}
And the resulting output from a test run:
Enter first phrase>CS AT WATERLOO
Enter second phrase>COOL AS WET ART
Is not an anagram.
AACELOORSTTW
AACELOORSTTW
false
Any and all help is greatly appreciated.
Use the Arrays.equals() method to compare two arrays. It will compare the elements of the arrays, whereas the default Object.equals() method will not.
Returns true if the two specified arrays of chars are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.
The .equals method of the array itself doesn't compare the contents of the array.
If you want to do that, you'll have to do it yourself - something like:
for(int i = 0; i < test1.length; i++) {
if(test1[i] != test2[i]) {
return false;
}
}
return true;
EDIT: Or use the static Arrays.equals.

Categories