This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have made a program to tell what season it is based on the month. However, no matter what i input, it says that it is Fall. Here is the code:
import java.util.Scanner;
public class SeasonChecker {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("What month is it??");
String month = input.nextLine();
System.out.println(month);
if (month == "december"||month == "January"||month=="February"){
System.out.println("Then it is Winter?");
}
else if (month=="March"||month=="May"||month=="April"){
System.out.println("Then it is Spring!!!");
}
else if (month=="June"||month=="July"||month=="August"){
System.out.println("Then it is Summer!");
}
else {
System.out.println("Then it is Autumn!");
}
input.close();
}
}
month == "december"||month == "January"
use equals() method while comparing Strings.
Example:
"december".equals(month) || "January".equals(month)
== checks for reference equality (both references pointing to same object are not). equals() checks for content of the object.
In Java, with strings, you should use the equals method to make comparison, not the literal == comparison. So month.equals("January") Using == will compare the memory references and see if they are the same reference for objects. == is meant for comparing literals like int or double
use equals method instead of ==
if (month.equals("december")||month.equals("January")||month.equals("February")){
in java == compares the reference. But equals method compares the value of String.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
the java subSequence is clearly true but only returns the false value. why?
trying to see if a sequence is equal to a subsequence of a bigger string
package testifthen;
public class TestIfThen {
public static void main(String[] args) {
String result = "01900287491234567489";
String result1 = "90028749";
if (result.subSequence(2, 10) == result1) {
System.out.println("excel");
}else {
System.out.println("not found");
}
}}
It's hard to say without more information (for example what language is this in).
Assuming this is Java, I would say your problem is using == with strings instead of the .equals function.
== doesn't check the contents of the string, only if they are referencing the same object. .equals should be used instead as it actually checks whether the characters match in the two strings
Try using
if (result.subSequence(2, 10).equals(result1)) {
System.out.println("excel");
} else {
System.out.println("not found");
}
The == symbol might be the one causing it to return false because of the different references.
This post should explain more about differences between == and equals(): What is the difference between == vs equals() in Java?
In Java, the .equals method should be preferred to the == operator when checking for semantic equality. .equals should be used when you are checking if two values "mean" the same thing, whereas == checks if they're the same exact object.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I tried with the following class :
public class EqualMethodTestWithNew {
public static void main(String[] args) {
String value = "xxx";
String name = new String("xxx") ;
System.out.println("hascode : value : "+value.hashCode());
System.out.println("hascode : name : "+name.hashCode());
if (value == name) {
System.out.println("equal == 1");
} else {
System.out.println("false == 1");
}
}
}
though the hasCode is same for the both variable it prints the false == 1. could some one explain the reason why?
thanks
You need to understand what exactly is happening when you execute the 2 string statements.
String value = "xxx";
The above line creates a new compile time constant string which does into the String intern pool.
String name = new String("xxx") ;
But in this case, since you're using the new operator, it creates a new String object which goes in the object heap. It does not have the same address as the one which was created in the previous statement.
The hashCode() method is based on the contents of the String which are the same, but that doesn't mean that they both refer to the same String object in the memory.
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] // would return same value for all String objects having the same content
To compare the values, you need to use equals() method.
And if you want to compare the object references use the == operator. In your case, since both refer to difference objects, you get the output as false.
Alternatively, you can ask the compiler to check and fetch the reference of a String with the same value already existing in the String pool by using the intern() method.
String value = "xxx";
String name = new String("xxx");
name = name.intern(); // getting reference from string pool
Now you'll get the output as equal == 1 when your do if (value == name) {.
You should be using equals method instead of == opertaor.
if (value.equals(name)) {
System.out.println("equal == 1");
} else {
System.out.println("false == 1");
}
Note that:
== tests for reference equality.
.equals() tests for value equality.
Please see here for more information.
The reason why your code is not working is that == tests whether the reference to the object is the same, and that is not your case. To compare the value of the string, you need to use the .equals(String str) method.
if (value.equals(name)) {
...
}
String should be compared with equals() method, not ==. You are trying the check the equality of the memory address of both instances (actually they are not) instead of the value in the String instances. So, use
if(value.equals(name)) {
System.out.println("equal == 1");
}
Strings are compared using equal() method. == compares the two objects are equal are not.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm only new to java and trying to make an equals code, but it won't work with ==, only with .equals() not sure why.
import java.lang.*;
import java.util.*;
public class password
{
public static void main(String args[])
{
Scanner Keyboard = new Scanner(System.in);
String guess = Keyboard.newLine();
String password = "1password";
if (guess == password) {
System.out.println("Welcome");
} else {
System.out.println("Login Failed");
}
}
}
I'm only new to java and trying to make an equals code, but it won't work with ==, only with .equals() not sure why
because == compares object references NOT the contents of the string.
You can find a great explanation at theJavaGeek
== checks whether two variables refer to the same object.
equals() method checks whether the contents of the object are same or not.
so If == returns true, then equals() method also returns true because they are referring to the same object hence they are equal(By equals() contract one object should be equal to itself)
Use the String.equals(String otherString) function to compare strings, not the == operator.
The reason is that == just compares object references,where as .equals() checks equality.
Strings should only be compared with .equals(), because with == you compare the Objects which are different.
trying to do == with string is checking reference equals. if the strings are exactly the same, meaning referenced to the same place, then it will be true, otherwise false
doing equals() check if the string matches, so if the strings contains the same values then you'll get true
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
This seems to be pretty simple, but I have been stucked here for a couple of hours.
I have a doubt when you have to compare two Strings in Java.
if I just do something like this:
String var1 = "hello";
String var2 = "hello";
and then compare these two words in another function, the result will clearly be true.
But the problem is when I have to compare two words that come from an input. Here is my code:
import java.util.Scanner;
public class Compare{
public static void main(String[] args){
Scanner Scanner = new Scanner (System.in);
System.out.println("Enter first word: ");
String var1 = Scanner.nextLine();
System.out.println("Enter second word: ");
String var2 = Scanner.nextLine();
if (same (var1, var2))
System.out.println("Yes");
else
System.out.println("No");
}
public static boolean same (String var1, String var2){
if (var1 == var2)
return true;
else
return false;
}
}
I have tried several times (clearly entering the same word) and the result is always False.
I don't know why this happens. What am I missing?
This is my first time in Java. I will appreciate any kind of help. Thanks
You should change
if (var1 == var2)
{
return true;
}
else
{
return false;
}
to
if (var1.equals(var2))
{
return true;
}
else
{
return false;
}
See this answer for the difference between the two
To be more accurate, with Strings in Java sometimes you can use == instead of .equals, if your string has been interned. Remember that == always compares the object references, not the contents of the object. Interning a String means that you will get the same object reference back and this is why == works with interned Strings.
Please read the Javadoc here to understand this more clearly:
String.intern()
In Java the == is a reference equality operator.
It works with the following.
String var1 = "hello";
String var2 = "hello";
boolean cmp = var1 == var2;
just because they are string literals and they are allocated in the same place inside the string table, so both variables point to the same string.
If you are fetching data from another source the strings are dynamically allocated, hence you should use the var1.equals(var2) (and you should ALWAYS use that one when comparing two objects).
Instead of if (same (var1, var2)) use if (v1.equals(v2)). No need to create a new method to compare two Strings. That's what equals() does.
== is used to compares references, not the contents of each String object.
The equality operator(==) checks the refernce of string first then checks value of string.
While equals method checks the value first.
So,in this case equals method should be used instead of equality operator.
String s="hello";
String s1="hello";
String s3=new String("hello")
In the above code snippet if you use If(s==s1){System.out.print("Equal");}it would print equal.But if you check If(s==s3){System.out.print("unqual");}it wouldn't print unequal.
so,you can see that even strings s and s3 are equal,output is wrong.Therefore,in this scenario like program in question
Equals method must be used.
var1 == var2
sometimes works because VM allocates the same memory both the variables for memory optimization and thus having same reference. That cannot be always the case so it's better to use
var1.equals(var2)
If you want to compare their values and doesnt care about reference.
I have this code:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String answer = input.nextLine();
if(answer == "yes"){
System.out.println("Yea I programmed this right!");
}else{
System.out.println("Awww :(");
}
}
}
But when I run it and type yes, it should be saying
"Yea I programmed this right!"
but it says
"Awww :("
You're comparing strings incorrectly. You must use the equals() method, like this:
if (answer.equals("yes"))
When you're programming in Java, the operator == is generally used for comparing primitive data types (int, double, etc.). If you use == for comparing two object types (like strings), you're comparing them for identity, that is, checking if they reference the same object in memory. In your case, what you need is to compare if they're equal: if they have the exact same value (a string of characters in this case) even if they're two different objects - and for that you must use the equals() method.
EDIT :
Even better, for preventing a NullPointerException, it's considered a good practice flipping the order of the comparison and writing first the string you're comparing with, like this:
if ("yes".equals(answer))
The explanation is simple: if for some reason answer is null, the above comparison will evaluate to false (meaning: answer is not "yes"), whereas the first version of the code would cause a NullPointerException when trying to call the equals() method on a null value.
if(answer == "yes"){
should be
if("yes".equals(answer)){
(== is not correct for String equality, and we handle the case where answer is null)
Use String.equals() instead of ==.
In Java, == is testing that the 2 Strings are the exact same instance, where "a" != "a". Instead, you need to test for "a".equals("a").
So replace
if(answer == "yes"){
with:
if("yes".equals(answer)){
Note that flipping the order here is intentional, as this can prevent a NullPointerException if answer was null - as "yes".equals(null) will simply return false, instead of throwing an exception. (Calling an operation on null would throw a NullPointerException, I.E. null.equals("yes").)
Change this
if(answer.equals("yes")){
System.out.println("Yea I programmed this right!");
}else{
System.out.println("Awww :(");
}
The equals() method compares this string (answer in your example) to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
It is important to understand that the equals() method and the == operator perform two different operations. As just mentioned, the equals() method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance.
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String answer = input.nextLine();
/*Edit your next line as mine,u'll get the correct ans...*/
if("yes".equals(answer)){
System.out.println("Yea I programmed this right!");
}else{
System.out.println("Awww :(");
}
}
}
or you can try to use "compareTo()" function
private static Scanner input;
private static String choice;
public static void main(String[] args) {
// TODO Auto-generated method stub
input = new Scanner(System.in);
choice = input.nextLine();
if (choice.compareTo("yes") == 0) {
System.out.println("Yea I programmed this right!");
} else {
System.out.println("Awww :(");
}
}