JAVA N WEB TECH SYLLABUS

Tuesday, December 14, 2010

Difference between String s = "abc"; vs String s2 = new String("abc");

/*
 * NewMain.java
 *
 * Created on December 14, 2010, 11:43 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author Naveen
 */
public class NewMain {
  
    /** Creates a new instance of NewMain */
    public NewMain() {
    }
  
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        String s1="abc";
        String s2="abc";
        String s3=new String("abc");


Naveen Mirajkar December 15 at 12:16am
/*
* NewMain.java
*
* Created on December 14, 2010, 11:43 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

/**
*
* @author Naveen
*/
public class NewMain {

/** Creates a new instance of NewMain */
public NewMain() {
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String s1="abc";
String s2="abc";
/*
for these 2 above line in first for s1 runtime will create a new object and it is referenced by s1
4 nd line
already sequence of char "abc" is in mem pool at runtime so the java interpretor will not create a new object but to already exsisting object referred by s1 is assigned to s2
thats why when u use s1==s2 v use == wrt object to chech weather they are same or not wrt to memloc and their hashcode


in the line s3=new String("abc")
the runtime will create a new object in heap havin seq of chars "abc"

but
it has its own mem addr diff from s1 n s2
so if u use
s1==s3
it is false


but
s1.equals(s3)
is true coz v checkin the char seqncs in both the objs which r same

ok
i hope u got it..........*/




        String s4=s1;
        if(s1==s4) {
            System.out.println("Hi0");
        }
        if(s1.equals(s4)) {
            System.out.println("Hi00");
        }
      
        if(s1==s2) {
            System.out.println("Hi");
        }
        if(s1==s3) {
            System.out.println("Hello");
        }
        if(s1.equals(s2)) {
            System.out.println("Hi1");
        }
        if(s1.equals(s3)) {
            System.out.println("Hi2");
        }
      
      
      
        System.out.println(s1==s2); //true
        System.out.println(s1==s3); //false diff object identity
        System.out.println(s1.equals(s2)); //true
        System.out.println(s1.equals(s3)); //true
      
        System.out.println(System.identityHashCode(s1)); //they are
        System.out.println(System.identityHashCode(s2)); //the same object
        System.out.println(System.identityHashCode(s3)); //diff  object
      
      
      
    }
}
output

Hi0
Hi00
Hi
Hi1
Hi2
true
false
true
true
4072869
4072869
1671711



No comments:

Post a Comment