how many objects?

by 9 replies
11
how many objects are created in the statement
String s=new String("Hello Java");
#programming #objects
  • Two, now tell us why
  • How is it two? I must be really rusty in Java.
    • [1] reply
    • Hi Sandeep Gupta, I think it is one.

      sql tutorials and online test papers on
      • [1] reply
  • Banned
    [DELETED]
  • It has to be One
  • its one object
    • [1] reply
    • new String() creates a copy of "Hello Java" (which is an object itself), thus a second object.

      If it was the same, then "Hello Java"==s would be true, but this isn't the case.

      If we did String s = "Hello Java", and then did "Hello Java"==s, it would be true.

      If we use the equals method, s.equals("Hello Java"), it will be true because that is comparing the contents of the strings.

      Here's a quick example:

      public static void main(String[] args) {
      String a = "Hello Java";
      String b = new String("Hello Java");
      String c = b;
      String d = a;

      System.out.println("Hello Java"==a);
      System.out.println("Hello Java"==b);
      System.out.println("Hello Java"==c);
      System.out.println("Hello Java"==d);

      }

      This prints out

      true - a references the object "Hello Java"
      false - b doesn't reference the object "Hello Java"
      false - c doesn't reference the object "Hello Java"
      true - d references the object "Hello Java"

      When you use a literal in a java program, it creates an interned string object. So in the following:

      String s = new String("Hello Java");

      You've created an interned String object with "Hello Java" and a copy of that object in s.
      • [ 1 ] Thanks
      • [1] reply

Next Topics on Trending Feed