Nitesh Verma Nitesh Verma - 1 month ago 10
Java Question

Comparing Stack value to String in java

I am trying the following code:

import java.util.Stack;
public class HelloWorld{

public static void main(String []args){
Stack s=new Stack();
s.push(5-4);
s.push(9);
s.push(51);
if(s.get(1).equals("9"))
System.out.println("yes its comparable");
System.out.println(s.get(1));

}
}


The actual output is:

9


I expect the output to be:

yes its comparable
9


I am unable to figure it out. I have tried s.get(1)=="9" also but it doesn't work too. What might be key behind this? Are they both not strings? or one is string one is object but still they are comparable. Can anybody enlighten me on this?

Answer Source

9 is an integer. "9" is a string.

s.get(1).equals("9"); // false
s.get(1).equals(9); // true