-8

If you compile and execute an application with the following code in its main() method: In this program why the " s" create the two objects.

   String s = new String( "Computer" );

   if( s == "Computer" )
   System.out.println( "Equal A" );
   if( s.equals( "Computer" ) )
   System.out.println( "Equal B" );
Mohsin Shaikh
  • 494
  • 1
  • 4
  • 11

2 Answers2

1

The first s == "Computer" test will fail, since s and the literal string "Computer" are sitting at different addresses.

The second s.equals("Computer") will succeed. The two strings have equal contents.

Any good tutorial book on Java would explain that better than we have time to.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

To compare String objects you should do:

if( s.equals("Computer" ))

instead of == operator.

anubhava
  • 761,203
  • 64
  • 569
  • 643