Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

public class Snippet16
{
    void execute()
    {
        String s = "ab";
        StringBuilder sb = new StringBuilder("ab");
        System.out.println(s.equals(sb.toString()) + " " + s.equals(sb));
    }

    public static void main(String[] args)
    {
        Snippet16 demo = new Snippet16();
        demo.execute();
    }
}

  • A.The program prints false true
  • B.The program prints false false
  • C.The program prints true true
  • D.The program prints true false

Answer: D

Converting the builder to a String gives a value equal to s, so the first test is true. The second passes the builder itself, and String.equals returns false for anything that is not a String, whatever it contains. StringBuilder does not override equals either.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.