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 :(");
}
}
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 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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java String.equals versus ==
Why when we declare string in Java we can't use == to compare this string and it will always turn to false, but if we initialize the string from the beginning it will be true?
For example :
import java.util.Scanner;
public class MyString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String s = input.nextLine();
if(s=="Hello")
System.out.println("Hello");
String d = "Hello";
if(d=="Hello")
System.out.println("Hello");
}
}
What is the explanation for this behavior?
This is an example of String.intern() happening automatically for string literals but not in general.
If you change your code to
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String s = input.nextLine();
s = s.intern();
if(s=="Hello")
System.out.println("Hello");
String d = "Hello";
if(d=="Hello")
System.out.println("Hello");
}
you will see "Hello" printed twice upon entering "Hello" at the console, because then all the copies of the "Hello" will have been interned to the same copy.
You should of course not normally use == to compare Strings, but use
if (s.equals("Hello")
This "intern" process is a way of reducing memory usage supported by many languages including Java. When you call s.intern() the run-times looks for a copy of the string in a pool of interned strings, uses one if it's found, and makes one otherwise, so that there's only one copy of that string. For more on the general idea, see this Wikipedia article.
Use str.equals(str2). Otherwise you are comparing whether the objects have the same address.
The reason is that the string object returned by input.nextLine() is not interned. So, it's not the same string object as the one represented by the string literal "Hello".
With the following, if you enter "Hello", you should see the difference:
Scanner input = new Scanner(System.in);
String s = input.nextLine();
s = s.intern();
if (s == "Hello") {
System.out.println("Hello 1");
}
String d = "Hello";
if (d == "Hello") {
System.out.println("Hello 2");
}
use .equals() method to check string equality. == checks if two reference variables point to the same string object.
nextLine() adds a "\n" to the end of the entered string, rendering it unequal to "Hello".
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.
Hey guys im just messing around and I cant get this to work:
public static void main(String[] args){
Scanner input = new Scanner (System.in);
String x = "hey";
System.out.println("What is x?: ");
x = input.nextLine();
System.out.println(x);
if (x == "hello")
System.out.println("hello");
else
System.out.println("goodbye");
}
it is of course supposed to print hello hello if you enter hello but it will not. I am using Eclipse just to mess around. A little quick help please
Should be if (x.equals("hello")).
With java objects, == is used for reference comparison. .equals() for value comparison.
Don't use == when testing for equality of non basic types, it will test for reference equality. Use .equals(..) instead.
Look at the following diagram:
When using == you're comparing the addresses of the boxes, when using equals you're comparing their content.
You can't compare a string like that.Because String is a class.So if you want to compare its content use equals
if (x.equals("hello"))
System.out.println("hello");
else
System.out.println("goodbye");
x=="hello" compares the references not values , you will have to do x.equals("hello").
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>
Use "hello".equals(x) and never reverse since it does not handle null.
== operator checks equality of references (not values). In your case you have 2 String type object which have different reference but same value "hello". String class has "equals" method for checking values equality. The syntax is if(str1.equals(str2)).
Try this as the comparison:
if (x.equals("hello"))
Use x.equals("hello");
http://leepoint.net/notes-java/data/expressions/22compareobjects.html
Take this sample program:
public class StringComparison {
public static void main(String[] args) {
String hello = "hello";
System.out.println(hello == "hello");
String hello2 = "hel" + "lo";
System.out.println(hello == hello2);
String hello3 = new String(hello);
System.out.println(hello == hello3);
System.out.println(hello3.equals(hello));
}
}
Its output would be:
true
true
false
true
Objects hello and hello3 have different references that's why hello == hello3 is false, but they contain the same string, therefore equals returns true.
The expression hello == hello2 is true because Java compiler is smart enough to perform concatenation of two string constants.
So to compare String objects, you have to use equals method.