Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

please found out the output for this simple string program

 
s.palanivel rajan
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.io.*;
class str
{
public static void main(String args[])
{
String a=”abc”;
String b=”abc”;
If(a==b)
System.out.println(“1”);
Else
System.out.println(“2”);
If a.equals(b)
System.out.println(“3”);
Else
System.out.println(“4”);
}
}
 
K. Tsang
Bartender
Posts: 3457
14
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you try it out with the compiler? The output is 1 and 3. Do you know why?
 
s.palanivel rajan
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i don't know why sir...
because i think string cant be compared as like integers isn't it...
 
pankaj vijay
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great question

Rajan you can find the answer of this question in any book of java.
anyway you wrote
String a=”abc”;
String b=”abc”;
in this case you are creating two references which denoting same object.
a & b both are reference which denoting object abc.
so a==b will compare that both reference are denoting same object Or diff. ?? so the answer is--1
&
a.equals(b) are checking that the value of these objects are same Or diif so answer is --3
If you do like this
String a=”abc”;
String b= new String("abc”);
now you have two difference object so
a==b will return false Then answer will be
2&3
 
s.palanivel rajan
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you pankaj great answer
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic