Can't get else if statement to work in Java - java

Ok I am trying to make this simple thing but it won't work. I am a beginner in Java and would like some help. Every time I run the code below I get the output That is not a valid option. What am I doing wrong?
package test;
import java.util.Scanner;
public class options {
public void options() {
Scanner scnr = new Scanner(System.in);
String slctn;
System.out.println("What would you like to do?");
System.out.println("a) Travel the expedition");
System.out.println("b) Learn more about the expedition");
slctn = scnr.nextLine();
if (slctn == "a"){
travel exeTravel = new travel();
exeTravel.travel();
}else if (slctn=="b"){
learn exeLearn = new learn();
exeLearn.learn();
}else{
System.out.println("That is not a valid option");
}
}
}

Well, first off, == is a fundamental operator in the language. The result type of the expression is a boolean. For comparing boolean types, it compares the operands for the same truth value. For comparing reference types, it compares the operands for the same reference value (i.e., refer to the same object or are both null). For numeric types, it compares the operands for the same integer value or equivalent floating point values. See the Java Language Specification.
In contrast, equals() is an instance method which is fundamentally defined by the java.lang.Object class. This method, by convention, indicates whether the receiver object is "equal to" the passed in object. The base implementation of this method in the Object class checks for reference equality. Other classes, including those you write, may override this method to perform more specialized equivalence testing. See the Java Language Specification.
The typical "gotcha" for most people is in using == to compare two strings when they really should be using the String class's equals() method. From above, you know that the operator will only return "true" when both of the references refer to the same actual object. But, with strings, most uses want to know whether or not the value of the two strings are the same -- since two different String objects may both have the same (or different) values.
slctn = scnr.nextLine();
if (slctn.equals("a")){
travel exeTravel = new travel();
exeTravel.travel();
}else if (slctn.equals("b")){
learn exeLearn = new learn();
exeLearn.learn();
}else{
System.out.println("That is not a valid option");
}

slctn.equals("a") will work.
Read this to understand why: What is difference between == and equals() in java?

In Java, when you need to compare two objects for equality (that is, to determine if they have the same value) you must use equals(). The == operator is used for testing if two objects are identical, that is: if they're exactly the same object in memory. In your code, replace this:
slctn == "a"
slctn == "b"
With this:
"a".equals(slctn)
"b".equals(slctn)
Also notice that it's a good idea to invert the order of the comparison ("a" before slctn), just in case slctn is null.

In java when matching any object the == operator will only match the reference of those two objects.
If we take your example slctn == "a". Say slctn has its reference value at abc123, your other sting "a" will have a different reference value as it is not the same object.
The method .equals checks what the letters in the string object are and matches the value of the letters in the two strings. Therefore if your object slctn contains "a", it will match with the string "a"

In java == operator compare reference of two objects, for sample :
String s_1 = new String("Sample");
String s_2 = new String("Sample");
System.out.println(s_1 == s_2);
result will is :
false
this happen because s_1 is a reference at memory and s_2 is difference refernce at memroy also.
For solve this issue , you have to compare tow objects by equals method. for sample
String s_1 = new String("Sample");
String s_2 = new String("Sample");
System.out.println(s_1.equals(s_2));
result will is :
true

Related

How to show !equals in if statement (Java)? [duplicate]

This question already has answers here:
How can I express that two values are not equal to eachother?
(4 answers)
Closed 8 years ago.
How is it possible to show if it's not equal (!=, something like this maybe) in an if statement?
For example:
for (int g = 0; g < doglist.size(); g++){
if(doglist.get(g).equals(name)){
System.out.println("There is no dog with that name: ");
}
}
So in this code I want to print the message if the entry in the list is not equal to name. So instead of equals(name) I'll have to use something different. How is this possible?
You can use the NOT operator ! with appropriate parentheses for clarity (though not strictly required).
if (!(condition))
so in your case....
if(!(doglist.get(g).equals(name)))
You should write
if (!doglist.get(g).equals(name))
About your idea of using !=: For primitive data types, yes, it's correct to test equality using !=. .equals() is for object data types. However, applying != to an object would be testing whether the memory location of the operands is the same, which is not the relevant information. .equals() is what tests for whether the objects are actually equal.
For example, when comparing ints (a primitive type), you would use !=:
int a = 0, b = 1;
if (a != b) doSomething(); //Calls the method
Primitive types do not recognize the .equals() method at all. But if you want to compare Strings (an object type), you would use !<object>.equals():
String s1 = "Hello", s2 = "World";
if (!s1.equals(s2)) doSomething(); //Calls the method
If you used != with an object, it would compile, but likely would not produce the desired output:
String s1 = "Hello!";
String s2 = "Hello!"; //Make a new object with the same data -- contains "Hello!"
if (s1 != s2) doSomething(); //Will run doSomething(), even though s1.equals(s2)

Java substring with one char

I have
String x = g.substring(0, 1);
if (x == "S") {
stuff
}
I have a string, "Safety", but "stuff" doesn't run and my watch say x value = S and x=="S" = false.
== is used for identity comparison, and it checks whether the two reference points to the same object (in your case the object is String).
You should use the equals method to compare the contents of your string:
if (x.equals("S"))
This compares references not string equality x=="S" you should use "S".equals(x).
Use equals() method of String class instead, not ==.
if(x.equals("S"))
== checks the reference and not the value.
You should use the .equals method to compare Strings (and any non-primitives in general).
if (x.equals("S")) {
//stuff
}
Many problems...
Your variable x is a String! You shouldn't use == operator with that, use .equals() instead
Also, while you're at it, you should use .equalsIgnoreCase() to ignore case.
By the way, I should note that there is the String.charAt(int) function too, which returns the character at the specified place...
But if you would like to select all Strings (your question didn't reveal your original intentions why and what you are trying to achieve), but I'd look into regular expressions, and using String.matches()
You need to use String.equals for comparing string content. The == operator is used for comparing object references.
Switching the positions of the arguments will avoid a NullPointerException:
if ("S".equals(x))
In Java equals() checks equality and == checks identity.
Why don't you use the charAt function and do it like this:
char x = g.charAt(0);
if (x == 'S') {
// Stuff
}
If you don't want to use char, use the equals method in the if block comparison as:
String x = g.substring(0, 1);
if (x.equals("S")) {
// stuff
}

how to check reference equality in an object which implements content equality?

...in other words:
let's suppose I have 2 Strings declared as so:
String one = new String("yay!");
String two = new String("yay!");
these two Strings are two different objects, but if I run
if(one.equals(two))
System.out.println("equals() returns true.");
I get "equals() returns true".
This is because the String class overrides the equals() method to implement a content level equality.
However, I need to access a reference level equality (like the one implemented in Object) to distinguish the object one form the object two.
How can I do that?
I tried this:
one.getClass().getSuperclass().equals();
to try to invoke the Object equals() method of the String one but it didn't work.
Any advice?
If you want to check reference just perform:
one == two
But be careful with strings. There is a thing called String constant pool so they may refer to the same object.
String in java uses a String Literal Pool, this means is: "When you try construct a string, first String class search in Literal Pool for traditional same string ,if exist return it, and if don't exist create it", so you can't check by equals method compare refernce of String instance, you have to use == operator as following:
String one = new String("yay!");
String two = new String("yay!");
if(one.equals(two))
System.out.println("equals() returns true.");
if(one == two)
System.out.println(" == operator returns true.");
result is :
equals() returns true.
see following link for more information:
http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/
Java String.equals versus ==
Use simple == comparison. However to avoid String interning you have to create your Strings using char arrays such as: String me = new String(new char[] { 'm', 'e' }); instead of using String literals "me" such as String me = new String("me");.
if (one == two)
System.out.println("one and two are the same object");
The only this you need is "==" equality operator.

Comparing two identical strings with == returns false [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am making an archive for my family. There are no syntax errors, however whenever I type in "Maaz", it evaluates realName == "Maaz" to false and goes to the else statement.
import java.util.Scanner;
public class MainFamily {
public static void main (String [] args) {
System.out.println("Enter you're name here");
Scanner name = new Scanner(System.in);//Scanner variable = name
String realName;
realName = name.nextLine();//String variable = user input
System.out.println("Name: "+ realName);
if (realName == "Maaz") {
System.out.println("Name: Maaz");
} else {
System.out.println("This person is not in the database");
}
}
}
TL;DR
You wrote (this doesn't work):
realName == "Maaz"
You meant this:
realname.equals("Maaz")
or this:
realname.equalsIgnoreCase("Maaz")
Explanation
In Java (and many other Object-Oriented programming languages), an object is not the same as a data-type. Data-types are recognized by the runtime as a data-type.
Examples of data-types include: int, float, short.
There are no methods or properties associated with a data-type. For example, this would throw an error, because data-types aren't objects:
int x = 5;
int y = 5;
if (x.equals(y)) {
System.out.println("Equal");
}
A reference is basically a chunk of memory that explicitly tells the runtime environment what that data-block is. The runtime doesn't know how to interpret this; it assumes that the programmer does.
For example, if we used Integer instead of int in the previous example, this would work:
Integer x = new Integer(5);
Integer y = new Integer(5);
if (x.equals(y)) {
System.out.println("Equal");
}
Whereas this would not give the expected result (the if condition would evaluate to false):
Integer x = new Integer(5);
Integer y = new Integer(5);
if (x == y) {
System.out.println("Equal");
}
This is because the two Integer objects have the same value, but they are not the same object. The double equals basically checks to see if the two Objects are the same reference (which has its uses).
In your code, you are comparing an Object with a String literal (also an object), which is not the same as comparing the values of both.
Let's look at another example:
String s = "Some string";
if (s == "Some string") {
System.out.println("Equal");
}
In this instance, the if block will probably evaluate to true. Why is this?
The compiler is optimized to use as little extra memory as is reasonable, although what that means depends on the implementation (and possibly runtime environment).
The String literal, "Some string", in the first line will probably be recognized as equivalent to the String literal in the second line, and will use the same place in memory for each. In simple terms, it will create a String object and plug it into both instances of "Some string". This cannot be relied upon, so using String.equals is always a better method of checking equivalence if you're only concerned with the values.
do this instead
if (realName.equals("Maaz"))
equals() should be used on all non-primitive objects, such as String in this case
'==' should only be used when doing primitive comparisons, such as int and long
use
if(realName.equals("Maaz"))
use == with primitive data type like int boolean .... etc
but if you want to compare object in java you should use the equals method
You have to compare objects with realName.equals ("Maaze"), not with ==.
It is best practice to compare Strings using str.equals(str2) and not str == str2. As you observed, the second form doesn't work a lot of the time. By contrast, the first form always works.
The only cases where the == approach will always work are when the strings are being compared are:
string literals or references to string literals, or
strings that have been "interned" by application-level code calling str = str.intern();.
(And no, strings are not interned by default.)
Since it is generally tricky to write programs that guarantee these preconditions for all strings, it is best practice to use equals unless there is a performance-related imperative to intern your strings and use ==.
Before that you decide that interning is a good idea, you need to compare the benefits of interning with the costs. Those costs include the cost of looking up the string in the string pool's hash table and the space and GC overheads of maintaining the string pool. These are non-trivial compared with the typical costs of just using a regular string and comparing using equals.
You can also use
realname.equalsIgnoreCase("Maaz")
This way you can accept Maaz, maaz, maaZ, mAaZ, etc.
== tests shallow equality. It checks if two objects reference the same location in memory.
Intriguing. Although, as others have stated, the correct way is to use the .equals(...) method, I always thought strings were pooled (irrespective of their creation). It seems this is only true of string literals.
final String str1 = new String("Maaz");
final String str2 = new String("Maaz");
System.out.println(str1 == str2); // Prints false
final String str3 = "Laaz";
final String str4 = "Laaz";
System.out.println(str3 == str4); // Prints true
Since you are working on strings, you should use equals to equalsIngnorecase method of String class. "==" will only compare if the both objects points to same memory location, in your case, both object are different and will not be equal as they dont point to same location. On the other hand, equals method of String class perform a comparison on the basis of the value which objects contains. Hence, if you will use equals method, your if condition will be satisfied.
== compares object references or primitive types (int, char, float ...)
equals(), you can override this method to compare how both objects are equal.
for String class, its method equal() will compare the content inside if they are the same or not.
If your examples, both strings do not have the same object references, so they return false, == are not comparing the characters on both Strings.
It seems nobody yet pointed out that the best practice for comparing an object with a constant in Java is calling the equals method of the constant, not the variable object:
if ("Maaz".equals (realName)) {}
This way you don't need to additionally check if the variable realName is null.
if(realName.compareTo("Maaz") == 0) {
// I dont think theres a better way do to do this.
}

Comparing java Strings with == [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java String.equals versus ==
Is it possible to compare Java Strings using == operator?
Why do I often see, that equals() method is used instead?
Is it because when comparing with literal Strings (like "Hello") using == doesn't imply calling equals()?
there is no custom operator overloading in java. [so you cannot overload it to call equals()]
the equals() ensures you check if 2 Objects are identical,while == checks if this is the exact same object. [so no, using == does not invoke equals()].
== checks if the two objects refer to the same instance of an object, whereas equals() checks whether the two objects are actually equivalent even if they're not the same instance.
No, it's not possible, because with == you compare object references and not the content of the string (for which you need to use equals).
In Java, you cannot overload operators. The == operator does identity equality. The equals(...) method, on the other hand can be be overridden to do type-specific comparisons.
Here's a code snippet to demonstrate:
String a = "abcdef";
String b = a;
String c = new String(a);
println(a == b); // true
println(a.equals(b)); // true
println(a == c); // false
println(a.equals(c)); // true
The one complication is with equals(...) you need to care about null, too. So the correct null-safe idiom is:
(a == null ? b == null : a.equals(b))
This is a loop you don't have to jump through in say C#
To expand on #amit's answer, the == operator should only be used on value types (int, double, etc.) A String is a reference type and should therefore be compared with the .equals() method. Using the == operator on a reference type checks for reference equality in java (meaning both object references are pointing to the same memory location.)
String is a class.So if you try to compare a String with its object that holding a string value you can't use == as it is looking for an object.For comparing the contents of the object you have to use equals
Operator == compares for string object references ,whereas String.equals method checks for both object references + object values . Moreover , String.equals method inturn uses == operator inside its implementation.
From what I know the '==' operator is used to check whether or not to objects are identical.
The presumable compared strings might have the same value(nr of chars etc), but be in fact two totally different objects, thus rendering the comparison false.
== returns true if the memory address is equal on both sides, except for primitive types.
equals should be used on everything that isn't a primitive. classes for the main part.
== operator checks the bit pattern of objects rather than the contents of those objects, but equals function compare the contents of objects.
String str1=new String("abc");
String str2=new String("abc");
System.out.println(str1==str2); will return false because str1 and str2 are different object created with "new" .
System.out.println(str1.equals(str2)) will return true because equals() checks for contents of object.
As amit already said, == checks for being the same object whereas equals() checks for the same content (ok, the basic implementation is equal to == but String overrides this).
Note:
"Hello" == "Hello" //most probably would be true
"Hello".equals( "Hello" ) //will be true
String s1, s2; //initialize with something different than a literal, e.g. loading from a file, both should contain the same string
s1 == s2 //most probably will NOT be true
s1.equals( s2) //will be true, if both contain the same string, e.g. "Hello"
Besides that, the same holds true for object wrappers of primitives, e.g.
Long l1 = 1L;
Long l2 = 1L;
l1 == l2 //will most likely be true for small numbers, since those literals map to cached instances
l1.equals(l2) //will be true
new Long(1) == new Long(1) //will NOT be true
new Long(1).equals(new Long(1)) //will be true

Categories