How many Objects are created in this?

Hi,
How many objects are created in the flwg code:
String str = new String("Hello");
String str2 = "Hey there";
str = str + str2;

Depends if you're counting objects created at compile time.
"Hello" is created at compile time. That's 1.
new String("Hello") creates a new String object at runtime, pointing its backing array at the "Hello" in the constant pool. That's 2.
"Hey there" is created at compile time. 3.
str + str2 I might do everything at compile time, or it might do some at runtime. I don't know if str is considered a compile time literal here. I think not, but I'm not sure. You can check by using javap. If I'm correct, then at runtime you'll create a StringBuffer (4) and another String (5).
So I'd say 5 objects. But if the compiler treats str as a literal and therefore can do the str+str2 at compile time, then it might do so without creating the StringBuffer. Or it might still create it at compile time, use it, and throw it out.

Similar Messages

  • How many objects are created?

    I have this question which some one posted to me.
    He asked me how many objects are created when an object of a simple class is created for example
    class A{
    public static void main(String args[])
    A a1 = new A();
    Now how many objects are created? I think only one. Can anyone tell me if any other objects are also created.
    Plz tell me .

    No, the answer is indeed 1. All the other objects
    (including the String[] in the main method
    parameters) are created outside of the A
    class, either by the JVM itself or by some other
    class that calls the A.main() method. You can try
    this out for yourself by adding a constructor such as
    A()
    System.out.println("Creating class A");
    } and see what prints out.Take a closer look at the question:
    how many objects are created when an object of a
    simple class is created for exampleIt doesn't say "how many objects of type A are created".
    I.e. The VM has to load class A before you can create an object from it, and thus an object of type Class is created. There are also a bunch of other objects which needs to be created before you can instantiate A.
    Kaj

  • Garbage Collection: how many objects are created after for loop?

    Please see the fallowing java code
    1 public class Test1 {
    2     
    3     public static void main(String[] args) {
    4          
    5          MyObj obj = null;
    6          for(int i=0;i<5;i++){
    7               obj = new MyObj();
    8          }
    9 // do something
    10
    11     }
    12 }
    so my question is How may objects are eligible for garbage collection at line no: 9 (// do something)?

    so my question is How may objects are eligible for
    garbage collection at line no: 9 (// do something)?It's impossible to answer that question since we don't know how MyObj is implemented.
    Kaj

  • How many String are created?

    public String makinStrings() {
         String s = �Fred�;
         s = s + �47�;
         s = s.substring(2, 5);
         s = s.toUpperCase();
         return s.toString();
    }How many objects are created when this method is called?
    My answer is 5
    1. "Fred"
    2. "47"
    3. "Fred47"
    4. "ed4"
    5. "ED4"
    But my friend is telling it is 3.
    1. "Fred"
    2. "47"
    3. "Fred47"
    I know that any method called on String object creates a brand new String. Please help me with the solution whether it is 3 or 5.

    hi,
    First of all i want to thanks for all of your replies.
    My friend is saying that when we say "How many objects when method is invoked" it means at runtime. String literals are not created at run time.
    String s = �Fred�; // No object is creatd here
    s = s + �47�; // One object created "s"
    s = s.substring(2, 5); //Another object "s"
    s = s.toUpperCase(); //Another object "s"
    return s.toString();
    Hence total 3 objects.
    Now the i have got a doubt. Are String literals created at Complie time itself. Or since String s = "Fred" is a compile time constant field. And String literal "47" is also a compile time constant field.
    Suppose if the code is like this
    String s = new String("Fred")
    String s1 = s; ---------------- Then is this String object created at Run time.
    String s2 = "47" ----------- This object is created at Complie time.
    Please clarify my doubt.

  • How many tables are created in Master data loading ( Including hierchy )

    hi ,
    Please anybody , can you tell us how many tables are created in Master data loading ( Including hierchy )
    thanks
    Phani

    Hi PP,
    Depending upon the definition of an infoobject, the tables are created when the objects are activated.
    /BI<C OR DIGIT>/<TABLE CODE><INFOOBJECT>
    <C or digit>: C = Customer-defined InfoObjects
    digit = SAP-defined InfoObjects
    <table code>: S = SID table
    T = Text table
    P = Time-independent master data attributes
    Q = Time-dependent master data attributes
    M = Union of time-dependent and time-independent master
    data attributes
    X = SID table for time-independent navigational attributes
    Y = SID table for time-dependent navigational attributes
    H = Hierarchy table
    K = Hierarchy SID table
    I = Hierarchy SID structure table
    J = Hierarchy interval table
    Thnaks...
    Shambhu

  • Seing how many objects are selected.

    Hi! I'm having a problem seing how many objects are selected when I navigate in Finder's windows. In Snow Leopard, there used to be a grey bar at the bottom telling you these infos, but this seems to be gone in Lion. Anyone knows how to get it back?
    Thank you!

    Open the Document Info Palette.
    Find its secret little flyout menu.
    Select from that menu "Objects".
    Let go.
    Then go to that same menu all over again and select "Selection Only".
    Scroll through the list and sum the quantities shown. Except be careful not to include the count of "All Text Objects" with the counts of "Point Type Objects", "Area Type Objects", and "Type On A Path Objects".
    Repeat those steps every time you start a new work session in AI, because AI's palettes can't remember the way you set them between launches.
    How could you have overlooked that intuitive and straightforward routine?
    JET

  • How many sessions are created in Server ?

    Hi All developers,
    SCJP back again.........
    Anybody please tell me......
    Is there any way to find out how many sessions are created in server ?
    Thanks in advance ..............

    Only by keeping track of them yourself.
    The various session listeners - SessionListener, SessionBindingListener are usefule here.

  • How Many Objects Are Selected

    How can I tell how many objects are selected when I draw a selection marque around multiple objects?

    Open the Document Info Palette.
    Find its secret little flyout menu.
    Select from that menu "Objects".
    Let go.
    Then go to that same menu all over again and select "Selection Only".
    Scroll through the list and sum the quantities shown. Except be careful not to include the count of "All Text Objects" with the counts of "Point Type Objects", "Area Type Objects", and "Type On A Path Objects".
    Repeat those steps every time you start a new work session in AI, because AI's palettes can't remember the way you set them between launches.
    How could you have overlooked that intuitive and straightforward routine?
    JET

  • How many documents are there in this Package?

    Is there an easy way to determine how many documents are in an existing Package?
    At the moment I work around it by using Search on a character pretty much guaranteed to be in them all, but I'd expect it to be a property stored somewhere?
    Acrobat Pro v8.1.2

    Apple in a press release from 2012 claimed more than 45,000 movies, but did not provide any details as to that figure. And it changes rapidly, and it would be different for each country, so unless someone went in and counted them manually in your country's iTunes Store, there won't be an accurate figure available.
    Regards.

  • Trying to keep track of how many objects I create

    Hello everyone I'm trying to keep track of how many message objects I created and Assign them to a data member.
    Right now it assigns all the Message objects the same number at the end which is 3. I wanted it to assign 1 to the first object it create, 2 for the 2nd, and 3 for the 3rd.
    here's a small version of my code:
    package ss;
    import java.util.ArrayList;
    import java.util.Iterator;
    public class MainTest {
         public static void main(String [] args)
              Message msg = null;
              ArrayList<Message> msgList = new ArrayList<Message>();
              for(int i = 0; i < 3; i++)
                   msg = new Message();
                   msgList.add(msg);
              System.out.println(msgList);
    package ss;
    //this class will hold the Event/Message
    import java.util.List;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.ArrayList;
    import java.util.Set;
    import java.util.Iterator;
    public class Message {
         //these are datamembers that will be used during
         //the sending of the message to the reciever
         //PacketID should be incremented each time a new message is created
         static int PacketID = 0;
         Message()
              PacketID +=1;
         public String toString() {
              return("PacketID: " + this.PacketID
                        + "\n");
    }output:
    [PacketID: 3
    , PacketID: 3
    , PacketID: 3
    Any ideas what I'm doing wrong?
    Thanks!

    Thanks BigDaddyLovehandles,
    Well there's the problem, I just posted a simpler problem to a bigger one. So I am keeping them in a collection as you can see below.
    I'm keeping these message stored in a multi map, and it is multi-threaded. Everytime a user connects to my server I create a new thread, and start adding the "messages" to the database.
    But I must have a packetID, meaning every new message created I need to assign that number to the message object.
    I also see a problem with this like you said, its not thread safe, if 2 clients connect to the server, and both send me events, there are going to be 2 different maps, copying events from the client and storing them in their own seperate databases.
    This might not be a problem because after I get the events on each thread, i send them to another server for processing.
    Here's an example of what my database looks like that stores the messages:
    //this class should store all the Messages or "Events" and
    //you can access them based on their Serial key.
    public class MessageDB {
         //database to hold the information
         //     holds the Alerts/messages
         Map<String, List<Message>> AlertMap;
         //Constructor
         MessageDB() {
              AlertMap = new HashMap<String, List<Message>>();
         //print, outputs the contents of the hashMap
         public void print() {
              //want to print out the Key and all the Messages
              //associated with that key
              //print, outputs the contents of the hashMap
                   for (String key : AlertMap.keySet())
                        System.out.println("\n\nSerial (key): " + key
                                  + "\nValues in Map: \n" + AlertMap.get(key));
         void add(Message msg) {
              //getting the position of the List by EntityID if avaiable
              List<Message> AlertList = AlertMap.get(msg.Serial);
              //checking to see if there is a unique Key already in the Map.
              if (AlertList == null) {
                   //if there isnt a key in the map, add a new key, and a new List mapping
                   //to the key EntityID;
                   AlertList = new ArrayList<Message>();
                   AlertMap.put(msg.Serial, AlertList);
                   AlertList.add(msg);
              } else {
                   //adding message to List
                   AlertList.add(msg);
         }Any suggestions on what I can to number all these messages and it will be thread safe?

  • How many objects are in my map?

    hi all
    I nead help in a question about maps in java:
    In one map could be stored various references with diferent keys to just one real object. How can i count all objects referenced by my map? (not all references with map.size())
    Is it wise to use a set parallel to the map who contains just unique objects? Or is there an other, more beautiful solution?
    many thanx for your help
    benjamin

    If you want a more general solution you can use an interface. Now you can store any class in MyMap as long as it implements RefCount.
    interface RefCount {
       int getRef();
       void incRef();
       void decRef();
    class MyValue implements RefCount {
        private int ref;
        public int getRef() {return ref;}
        public void incRef() {ref++;}
        public void decRef() {ref--;}
    class MyMap extends HashMap {
        int objects = 0; 
        public Object put(Object key, Object value) {
            RefCount v = (RefCount) value;
            if (v.getRef() == 0)
                objects++;        // first time inserted
            v.incRef();
            return super.put(key,value); // call superclass put
        public Object remove(Object key) {
            RefCount v = (RefCount) super.remove(key); // super class remove
            if (v != null) {
                v.decRef();
                if (v.getRef() == 0)
                    objects--;        // last time removed
            return v;
        public int objectSize() { // returns number of objects.
            return objects;

  • How many tables are created?

              How tables does weblogic (7.0) create in database when using JMSJDBCStore? According
              to the DDL, there are only two tables; JMSSTORE and JMSSTATE.
              Jeba
              

    That's it. Two.
              And in the next release (named 9.0?) it will likely
              go down to one.
              Tom, BEA
              Jeba Bhaskaran wrote:
              > How tables does weblogic (7.0) create in database when using JMSJDBCStore? According
              > to the DDL, there are only two tables; JMSSTORE and JMSSTATE.
              >
              > Jeba
              

  • How many WAYS are there to CREATE an OBJECT?

    I simply know about implicit creation and explicit creation:
    String name = "Asim Munir"; //Implicit
    String name = new String("Asim Munir"); // Explicit
    Do you have any other way to create an object?

    Hi,
    Basically in Java, an object is created by using the new keyword. This is the actual object creation. So far String is concerned, there is a trick what you have mentioned.
    Plz go through it.
    String str = "India"; It is also String object. But internally, Java maintains a String Constant pool to maintain the String object. When you are writing the above statement, it will first check the value "India" in the String Constant pool and it it does not find, then it will create an object. If it finds, it will not create but simply it maintain a reference to that "India" object. So here only one object is created. But in the following case.
    String str = new String("India");
    Here two objects are created. Just try to understand how two objects are created. If you have any problem, feel free to mail
    Debadatta Mishra
    [email protected]

  • How Many Programs Are Preinstalled?

    How many apps are preinstalled on this thing when you buy it?

    Just go to the Apple Store page:
    Mac OS X v10.4 Tiger
    Tiger offers the amazing Spotlight search technology, handy Dashboard widgets and hundreds more features. Tiger also includes the following system applications:
    • Safari 2
    • Mail 2
    • Address Book 4
    • iChat AV 3
    • iCal 2
    • Font Book 2
    • DVD Player 4.5
    • Preview 3
    • Xcode 2
    Included software
    MacBook Pro comes with an incredible bundle of Universal applications that run on both Intel- and PowerPC-based Macs:
    • iLife ’06
    • iWork ’06 Trial
    • Front Row
    • Photo Booth
    • Comic Life
    • OmniOutliner
    But if you included ALL the apps such as utilities etc. it would add up to hundreds.
    Ian

  • How many java String objects are created in string literal pool by executin

    How many java String objects are created in string literal pool by executing following five lines of code.
    String str = "Java";
    str = str.concat(" Beans ");
    str = str.trim();
    String str1 = "abc";
    String str2 = new String("abc").intern();
    Kindly explain thanks in advance
    Senthil

    virtuoso. wrote:
    jverd wrote:
    In Java all instances are kept on the heap. The "String literal pool" is no exception. It doesn't hold instances. It holds references to String objects on the heap.Um, no.
    The literal pool is part of the heap, and it holds String instances.
    [http://java.sun.com/docs/books/jvms/second_edition/html/Overview.doc.html#22972]
    [http://java.sun.com/docs/books/jvms/second_edition/html/ConstantPool.doc.html#67960]
    You're referring to the JVM. That's not Java.It's part of Java.
    There is nowhere in Java where it is correct to say "The string literal pool holds references, not String objects."

Maybe you are looking for

  • No service for system SAPPRD, client010 in ID

    We are having trouble sending idocs from ECC5 system to XI 3.0 system. even though we have receiver determination, interface determination, sender agreement, receiver agreement etc. all configured for business system SAPPRD in IS, we still get error

  • Losing the ability to drag objects after 30 minutes. What's going on?

    Hi, I'm having a very strange problem. In InDesign, I'm losing the ability to drag objects around with the mouse after about 30 minutes of using the program. Everything else works fine, but I simply cannot perform this function. The box highlights, b

  • What is the keyboard shortcut to insert a table?

    what is the keyboard shortcut to insert a table?

  • Sync problem  with hdcam 24p

    We are experiencing a sync problem with captured material from hdcam in 24p in a 23.98 timeline. The reason the timeline is 23.98 (ProRes) is that most of the material for this show was shot in 23.98fps. The picture is sync if we look at the ouput fr

  • How do I open a CS5 site in CS6 (CC)?

    I just upgraded to CC and DW6.  I have a site in DW5, but for some reason I'm missing how to open it in CS6.