0
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.

3 Answers3

1

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.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
0
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.

stinepike
  • 54,068
  • 14
  • 92
  • 112
0
  1. You need to use equals instead of == for comparing String. Here's a good explanation as to why.

  2. 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);
    
Community
  • 1
  • 1
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356