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.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I'm new to Java/programming and I'm trying to write a simple program that gets an element from a list IF that element is equal to some user input. I'm using a for-loop and if-statement to achieve this but even though the user input and element matches up the programming won't print the element to screen. If someone could explain why this is not working it would be very appreciated. Cheers
public static void main(String[] args){
ArrayList<String> names = new ArrayList<String>();
String tempObject;
String findName;
names.add("John");
names.add("Ronny");
names.add("Gona");
names.add("Gina");
Scanner Input = new Scanner(System.in);
System.out.print("Search list for: ");
findName = Input.nextLine();
for (int i = 0; i < names.size(); i++){
tempObject = names.get(i);
if (tempObject == findName){
System.out.print("\n" + tempObject);
}
}
}
Here you go:
if (tempObject.equals(findName)){
System.out.print("\n" + tempObject);
}
For objects, which String is, always use method equals(), since == will compare references, not values (or what is set in equals() method - in String, it will compare the size, and then compare each char on the same place if they are equal - also, if you need, you have a method called equalsIgnoreCase - sometimes, its better to use that for user inputs).
For primitives, you will have to use ==.
There is difference between equality and identity, in your code above you used identity instead of equality, if you change your code (to use equality) as the below you will get what you need
if (tempObject.equal(findName)){
System.out.print("\n" + tempObject);
}
You should use String equals to compare two Strings for equality, not operator == which just compares the references.
Try the if statement like this:
if (tempObject.equals(findName)){...}
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.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
String firstanswer = scan.nextLine();
if(firstanswer == answer2)
{
System.out.println("OK lets get started");
}
else
{
System.out.println("That is incorrect, of course you want to play");
}
//answer2 is set to "yes", i declared it above
make it firstanswer.equals(answer2) instead of firstanswer == answer2.
When you want to check for equality of String in java then use equals method instead of == operator.
equals method checks whether the contents of String objects are same
== operator checks whether both the reference variables refer to same String object
To understand about strings and equality, read String comparison with equals and assignment operator It will help you understand the concept well.
Use equals() instead of == to compare strings.
if(firstanswer.equals(answer2)) is what you're looking for.
firstanswer and answer2 are pointers to string objects. == checks to see whether the pointers are equal (whether they point to the same object), while equals() compares the contents of the two strings and returns a boolean representing whether or not the contents are equal.
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"}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
String is not equal to string?
I'm new to java and I can't figure out what's wrong with this code block.
I know the array isn't null I'm testing it elsewhere. Maybe there is a syntax problem I'm used to program in c#.
Scanner input = new Scanner(System.in);
System.out.println("Enter ID :");
String employeeId = input.nextLine();
int index = -1;
for(int i = 0 ; i < employeeCounter ; i++)
{
if(employeeId == employeeNumber[i])
{
index = i;
}
}
if(index == -1)
{
System.out.println("Invalid");
return;
}
I always get to the 'Invalid' part. Any idea why ?
Thanks in advance
employeeNumber[0] is "12345"
employeeId is "12345"
but I can,t get into the first if statement although employeeId IS equal to employeeNumber[0].
Don't compare strings with ==.
Use
if (string1.equals("other")) {
// they match
}
Compare strings like that
if(employeeId.equals(employeeNumber[i]) {
}
As others have pointed - full code will be helpful, but my guess would be this line of the code:
if(employeeId == employeeNumber[i])
You don't compare 2 strings by using ==. Use equals() or equalsIgnoreCase() instead. == only checks for object equality i.e. are employeeId and employeeNumber referencing to the same object in memory. So, for objects always use the equals() method..for Strings you can also use equalsIgnoreCase() for a case insensitive match. == should be used on primitive types like int, long etc.
When you use == with two string, it compares pointer addresses
You should use firststring.equals(secondstring) in order to compare two strings
Use equals() method to compare Strings
if(employeeId.equals(employeeNumber[i])){}
When you compare strings, use
String1.equals(String2);
This should give you the result
"==" checks whether the reference for two objects are same. But equals() method checks whether the content is same or different.