Reputation: 1
public class run
{
public static void main(String args[])
{
boolean b;
int i=3;
b=Integer.toString(i)=="3";
System.out.println(b);
}
}
according to my code it should return true,but outputting false.
Upvotes: 0
Views: 152
Reputation: 67320
You need to use equals
instead of ==
for comparing String
. Here's a good explanation as to why.
You should get into the habit of writing equals
like this:
x= "3".equals(Integer.toString(i));
Notice how the literal value is on the left hand side and not the right hand side like all these other answers. The benefit here is this avoids a possible null pointer exception if the value passed into equals()
is a null. "3"
can never be null. If you wrote your code like the other answers, to be as safe as possible, you'd have to add extra lines like this:
String s = ...
x = s != null && s.equals("3");
It's less work to write it like this:
String s = ...
x = "3".equals(s);
Upvotes: 0
Reputation: 54672
public class run
{
public static void main(String args[])
{
boolean b;
int i=3;
x=Integer.toString(i).equals.("3"); // change in this line
System.out.println(x);
}
}
== compares the reference of object while equals method comapres the value.
Upvotes: 0
Reputation: 41281
Youre using ==
when you should use:
b=Integer.toString(i).equals("3");
I don't know why you use x
. I'm assuming a typo.
Basically the ==
compares the reference used by the literal's being compiled in to the reference to a new string object created from an integer that, due to implementation details, may or may not have been interned.
Upvotes: 1