aspose file tools*
The moose likes Beginning Java and the fly likes please found out the output for this simple string program Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "please found out the output for this simple string program" Watch "please found out the output for this simple string program" New topic
Author

please found out the output for this simple string program

s.palanivel rajan
Ranch Hand

Joined: Sep 22, 2009
Posts: 40
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”);
}
}


With Regards,
S.Palanivel Rajan B.E.
K. Tsang
Bartender

Joined: Sep 13, 2007
Posts: 2531
    
    8

Have you try it out with the compiler? The output is 1 and 3. Do you know why?


K. Tsang JavaRanch SCJP5 SCJD/OCM-JD OCPJP7 OCPWCD5 OCPBCD5
s.palanivel rajan
Ranch Hand

Joined: Sep 22, 2009
Posts: 40
i don't know why sir...
because i think string cant be compared as like integers isn't it...
pankaj vijay
Ranch Hand

Joined: Apr 01, 2008
Posts: 75
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


Pankaj Vijay (SCJP, SCBCD)
Learn Core Java,Learn Servlet Jsp, SCJP Questions,Struts Tutorial
s.palanivel rajan
Ranch Hand

Joined: Sep 22, 2009
Posts: 40
thank you pankaj great answer
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: please found out the output for this simple string program