I Do not Understand What Is wrong with the following code [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
savedInstanceState = getIntent().getExtras();
String type = savedInstanceState.getString(TYPE);
if(type == "tree")
{
setContentView(R.layout.activity_sound_tree);
}
else
{
TextView tv = (TextView) findViewById(R.id.heading_sound);
tv.setText("'"+type+"'");
}
I have used this code in the second activity. I know for sure that type == tree. So I do not understand why the first "if" block fails. It always goes to the "else" block, even though I am 100% sure that type == "tree". Can someone point me in the right direction?

Never compare string values with the == operator. Use the equals method instead.
The == operator compares object by references, not by values.
Javadoc: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)
Fixed code:
savedInstanceState = getIntent().getExtras();
String type = savedInstanceState.getString(TYPE);
if(type.equals("tree"))
{
setContentView(R.layout.activity_sound_tree);
}
else
{
TextView tv = (TextView) findViewById(R.id.heading_sound);
tv.setText("'"+type+"'");
}

use
type.equals("tree")
instead of
type == "tree"
Reason
equls method check the values of the object where == operator check whether they are the same instance of object.

This looks like classic String comparison question, try
"tree".equals(type); // This is also safe from NullPointerException since you are comparing type with a constant 'tree', which is not null
Why Equals?
A detailed explanation regarding using == vs equals() can be found here

Related

Why the order is reverse in equals() [duplicate]

This question already has answers here:
String.equals() argument ordering
(10 answers)
Closed 3 years ago.
In part of the code for check empty string the programmer use equals() like this:
if ("".equals(name)) {
// some logic
}
Why is it executed from a string value directly? What is the difference from this;
if (name.equals("")) {
// some logic
}
Both of them have the same result, but what is the idea behind doing the first one?
The idea behind using;
"".equals(name)
is that "" can never be null, whereas name can be. equals() accepts null as a parameter, but trying to execute a method from a null variable will result in a NullPointerException.
So this is a shorthand way to evade such possible exceptions. Same goes for any such constant object.
e.g.
final Integer CONSTANT_RATE = 123456;
....
if (CONSTANT_RATE.equals(someVariable)) { .. }
rather than doing;
if (someVariable != null && someVariable.equals(CONSTANT_RATE)) { .. }

can someone explain why this returns the "else" value and not the "then" value? [duplicate]

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.

Why BigInteger.ONE not equals to new BigInteger("1") in java? [duplicate]

This question already has answers here:
Compare two objects with .equals() and == operator
(16 answers)
Closed 7 years ago.
While using BigInteger class in Java8, i wrote this piece of code
System.out.println(new BigInteger("1")==BigInteger.ONE);
Ideally it should print true but its output is false. Why its output is false?
== checks if the objects point the same reference, so that if a = b the condition a == b. It's recommended to only do this with primitive types.
To check if the objects' content is the same, use the function equals(Object otherObject). For example:
new BigInteger("1").equals(BigInteger.ONE);
This will return true, as both objects' content is the same. Using == will return false though, as each object have different references.
Another example would be this:
MyObject object1 = new MyObject(30);
MyObject object2 = object1; //this will make them have the same reference
// This prints true, as they have the same content.
System.out.println(object1.equals(object2));
// This will print true, as they point the same thing, because they have the same reference
System.out.println(object1 == object2);
// We can see they have the same reference because if we edit one's field,
// the other's one will change too.
object1.number = 10;
System.out.println(object1.number); // prints 10
System.out.println(object2.number); // prints 10 too
new BigInteger("1")==BigInteger.ONE
Can rewrite as
BigInteger bigint =new BigInteger("1");
BigInteger bigint2= BigInteger.ONE;
Now
System.out.println(bigint ==bigint2); //false
Because they points to different references.
== checks the reference. Not the value inside them.
You can try using equals() method to check their equality.
Because you're using == instead of .equals(yourNumberToBeCompared)
You should do:
System.out.println(new BigInteger("1").equals(BigInteger.ONE));

Error for String Comparison in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I have this
public void otis() {
println("What is Otis?");
String otis = readLine(">");
println("You said " + otis);
println(otis);
println(otis);
if (otis == "dog"){
println("you got it right!");
}
else {
println("try it again!");
otis();
}
}
But for some reason even when I respond "dog" it doesn't find a match. I can print the "otis" variable and it says "dog" but apparently that's not equivalent to "dog" somehow?
Can you try the code below? Java doesn't recognize strings as equivalent from two different instantiations even if their values are equivalent. This is because each string is a pointer, and their pointer values aren't equivalent. Try using the String.equal method!
otis.equals( "dog" )
Because == means "is the same exact object in memory", the constant string "dog" and the string it reads from the console are not the same object, even if they have the same contents. When doing comparisons in Java, always use .equals().
As a possible side effect of this, you have to be careful when comparing things that might be null in Java. If you try to do
String dog = null;
if(dog.equals("dog")) { do_something(); }
You'll end up with a NullPointerException. For this reason, many coders prefer to compare strings like this:
if("dog".equals(dog)) { do_something(); }
since you always know the constant string will not be null.

Wrong results while String comparison [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm in little trouble. The problem is when I'm trying to compare 2 strings(type String) operator '==' returns FALSE, but actually strings are equal.
Here's the code with its problem:
//before the following code I filled the "LinkedList <String> command" and there is
//a node with value of args[0]
String deal="";
Iterator it = commands.listIterator();
if(it.hasNext() == true)
{
if(it.next() == args[0])
{
deal += it.next();
it.hasNext();
break;
}
}
Thank You!!!
To compare two strings u should use the method equals() or equalsIgnoreCase().
in your case:
if(it.next().equals(args[0]))
the operator == returns true if the two object are the same object, same address in memory.
You use .equals when comparing two strings. So use
(it.next()).equals(args[0])
You have to use .equals method:
String deal="";
Iterator it = commands.listIterator();
if(it.hasNext() == true)
{
String next = it.next();
if(next.equals(args[0]))
{
deal += next;
break;
}
}
Be careful, .next() returns the value once and move its internal cursor to the next value.
The == cannot be used for String because the == is true if the same object instance is on both sides. The same string content can be in many String instances.
There are two ways of comparing strings.
Comparing the value of the strings (achieved using .equals ).
Comparing the actual object (achieved using == operator).
In your code you are comparing the references referred by it.next() & args[0]whereas you should compare the value of the two using it.next().equals(args[0]).
if you use == to compare two int values, then it is compare the two values, because int is primitive data type. If you use "==" to compare String object, it is check whether both String reference are referring the same String object or not. It do not consider values of the String objects.
If you want to compare values of String objects you have to use equals() of the String class. This method is comparing content of both String objects.

Categories