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.
Related
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.
This question already has answers here:
String comparison and String interning in Java
(3 answers)
How do I compare strings in Java?
(23 answers)
String.equals versus == [duplicate]
(20 answers)
Closed 10 years ago.
I'm new to this site and didn't realize there were other questions that answered what I'm asking. I've figured it out and I will delete this post as soon as it lets me. Thank you.
I just started learning java again and I have a quick question.
Usually, using == to compare strings would not work and you would have to use .equals instead.
But now while coding, I found they are doing the same thing when they are not supposed too and I'm trying to figure out why.
Here's the code.
String s = "Hello";
String x = "Hello";
if (x == s){
System.out.println("It is working!");
}//end if
else {
System.out.println("It is not working");
}//end else
if (x.equals(s)){
System.out.println("Match");
}//end if
else {
System.out.println("No match");
}//end else
Basically you're seeing the result of string interning. From section 15.28 of the JLS:
Compile-time constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern.
So your two variable values actually refer to the same strings. If you use:
String s = new String("Hello");
String x = new String("Hello");
... then you'll see the behaviour you expect.
Reason is that your vars x and s have the same reference hence == behaves same as .equals.
When Java compiler optimizes your string values (literals), it determines that both x and s have same value and hence you need only one String object. As result, both x and s point to the same String object and some little memory is saved. It's safe operation since String is an immutable object in Java.
well, In this particular case there is only one string object created and cached in the string constant pool and both of the reference variables refer to the same string object which is stored in the string constant pool . thus you == test passes
String s = "Hello"; Line 1
String x = "Hello"; Line 2
When line 1 is executed one string object (Hello) is created and cached in String Constant pool .
**String Constant Pool:** {s--->"Hello"}
when line 2 is executed, it first checks if there is any object with the same value in string constant pool, if there exists one. it simply points the reference to the already created object in the pool.
**String Constant Pool:** {s,x--->"Hello"}
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
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I compare strings in Java?
I am trying to make it so that when I type hope, b will save hope and then it will recognize c == b, and you get the picture. What do I do? I am new to Java and I apologize if this is a no brainer.
package encryption;
import java.util.Scanner;
public class Encrypt
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
String test1 = new String("Enter now: ");
String d = new String("Success!");
String e = new String("Failure");
String b = new String();
String c = "hope"
System.out.print("Enter text: ");
b = scan.next();
if (b == c)
System.out.println("\"" + d + "\"");
else
System.out.println("\"" + e + "\"");
}}
Use if b.equals(c) because b==c compares references in java. It tells that if both the objects are referring to same memory locations or not.
So, if you need to check whether their values are equal always use equals method.
if (b == c)
Use equals instead to compare strings:
if (b.equals(c))
== compares the references, not the values so you're getting false every time. Equals compares the values.
This link provides a good explanation between ==, equals, compareTo, ...
To test the equivalence of Strings in Java you want to use the equals method:
if(c.equals(b)) {
...
}
The == operator tests to see if both variables point to the same place in memory. You have two Strings that have the same "value" (read:text), but are stored in two different places in memory.
c == b tests reference equality -- i.e. do the references point to the same object. You want equals as in b.equals(c)
Two things:
Don't compare Strings using a == b, use a.equals(b). The == operator asks if two Strings are the same physical chunk of memory; the equals() method asks if they contain the same characters. You want that second one!
You never need to -- nor should you -- use new String() in Java; just a double-quoted string like "hope" is a String object. Using new String() just creates unneeded objects and bogs things down.
b==c checks whether b and c reference the same string, while b.equals(c) check whether their values are equal, which is what you're trying to do.
Your problem is not proper reading documentation.
Use String.equals() instead.
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.