How many string objects - please suggest

Hi there,
Can you somebody please tell how many String objects will be created when the following method is invoked?
public String makinStrings() {
String s = “Fred”;
s = s + “47”;
s = s.substring(2, 5);
s = s.toUpperCase();
return s.toString();
Thanks
Shan

Hi VShan,
This is your code
public String makinStrings() {
String s = “Fred”;     //1
s = s + “47”;            //2
s = s.substring(2, 5);//3
s = s.toUpperCase(); //4
return s.toString();     //5
EXPLANATION : String is an immutable object, that means the String object cannot change it's contents.It might sound very unfamiliar but it is TRUE. In line 1: You declare a String object by assigning a a String literal "Fred" to the variable s. Now when you concat "47" with the original contents of s , a new memory space is allocated where s is assigned.+It is important to note+ that the previous reference of s i.e. "Fred" will be lost and now s refers to a new memory location where the contents are "Fred47" , so you have created another object in Line 2. Similarly you create another object in line3 & 4.As far my calculations you have created 4 objects.
I would like you to kindly note that s is already a String so you can directly return s and hence there is no need of s.toString() in Line 5.You should also note that each object is also an eligible candidate for Grabage Collection.
So as soon as Line2 gets executed , the object in Line1 becomes eligible for garbage collection.. that means when GC runs that object will be reclaimed and hence memory will be freed.

Similar Messages

  • "a"+"b"+"c", how many String objects created?

    Hello everyone,
    String s = "a" + "b" +"c";
    How many String objects are created?
    I guess 5, is it right?
    regards

    > How many String objects are created?
    >
    I guess 5, is it right?
    Nope. Just one.

  • How many String objects will be created when this method is invoked?

    public String makinStrings() {
    String s = �Fred�;
    s = s + �47�;
    s = s.substring(2, 5);
    s = s.toUpperCase();
    return s.toString();
    }

    Teachers.Obviously. Why? Is it really important?
    Not in my experience. StringBuffer can be important, occasionally. Very occasionally: about 4 times in the last 10 years for me. How many Strings? not important.

  • How many view object instances can create from Single Entity ?

    Hi All,
    JDev Ver : 11.1.1.5
    I want to How Many view objects can i create from the single entitiy ?
    Is there any limit ?
    Thanks,
    Gopinath

    No, there is no limit

  • We are upgrading to apple 5s from android i have an ituns account. will i need anothe account for my wife. 2 apple phones how many itunes acconts Please Thank-you Moose in Utah

    We are upgrading to apple 5s from android i have an ituns account. will i need anothe account for my wife. 2 apple phones how many itunes acconts Please Thank-you Moose in Utah

        Hello mooseinutah, getting a new phone is always exciting! You will want to make sure to setup 2 separate Apple Id & passwords for each phone so that contacts & stored information are not merged between both devices.
    WiltonA_VZW
    VZW Support
    Follow us on twitter @VZWSupport

  • 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 Connections objects????

    Hi
    I am creating a GUI application which contains several GUI classes(e.g. frames and dialog boxes) which are instantiated depending on the choice of the user. I also have a Database class which contains the code which enables the connection to the database. The code creating the connection is within the constructor,therefore creating a connection whever I create an instance of the database class.
    Most of the GUI classes need to obtain or update information held in a database.
    Currently I create an instance of the Database class in every GUI class which needs to access the database. Obviously however every time a new database object is created, a new connection is also created.
    I am worried about all these database objects all containing their own connections.
    Should I have just one connection object in existence at any one time?
    If so,can I declare the Connection variable in the Database class as static?
    Any help/comments would be gratefully received.
    LGS

    From what I know, there should be no problem with maintaining multiple connections to the database. This is a property of the database itself, most allow about 256 connections. The only problem you face is a lost transaction. As long as you keep the queries serialized, you shouldn't encounter any problems.
    If you did want to only have one connection open... why not have another class for that (DBConn) and not instantiate a new connection in the constructor of your Database class. This way, each Database object can use the one connection by all referencing the DBConn object.
    Just a thought...

  • How many string tokens do I have?

    String line = "00:05,  4 May 2007;
    StringTokenizer st = new StringTokenizer(line);Four or five?
    I am not sure whether ":" or "," is a default delimiter?
    Thanks

    http://java.sun.com/javase/6/docs/api/java/util/StringTokenizer.html#countTokens()
    Also, "StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code."
    ~

  • String object Confussion

    Given the following,
    13. String x = new String("xyz");
    14. y = "abc";
    15. x = x + y;
    how many String objects have been created?
    A. 2
    B. 3
    C. 4
    D. 5

    Line 13 creates two String objects: the constant "xyz" and the "new String".
    Line 14 creates one String object, the constant "abc".
    Line 15 creates one String object for theOne could argue that "xyz" and "zbc" exist in the constant pool and are created no later than the class that contains this code. Therefore line 13 creates only one String and line 14 none.

  • String Object  VERY  Urgent

    I have code
    String s1="5+5=10";
    s1.trim();
    s1.replace('+','-');
    then how many String Objects are created.

    For that matter, how do you make a moot do anything?A "moot" is a collection of lawyers gathered together
    to discuss a hypothetical point. So how do you get a
    collection of lawyers to do anything? A court order
    might work.
    PC�That would get them to do something, but whether it would be what you actually wanted them to do is another matter. :-)

  • 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?

  • Many db objects error after Upgrate EBS 12.1.1 to EBS 12.1.3

    Hi,
    recently we have upgraded our EBS from 12.1.1 to 12.1.3 and there are almost 777 invalid objects after recompiling using adadmin.
    I tried to recompile INVALID objects using utlrp.sql but I am getting below error.
    SQL> @utlrp.sql
    SELECT dbms_registry_sys.time_stamp('utlrp_bgn') as timestamp from dual
    ERROR at line 1:
    ORA-00904: "DBMS_REGISTRY_SYS"."TIME_STAMP": invalid identifier
    DOC> The following PL/SQL block invokes UTL_RECOMP to recompile invalid
    DOC> objects in the database. Recompilation time is proportional to the
    DOC> number of invalid objects in the database, so this command may take
    DOC> a long time to execute on a database with a large number of invalid
    DOC> objects.
    DOC>
    DOC> Use the following queries to track recompilation progress:
    DOC>
    DOC> 1. Query returning the number of invalid objects remaining. This
    DOC> number should decrease with time.
    DOC> SELECT COUNT(*) FROM obj$ WHERE status IN (4, 5, 6);
    DOC>
    DOC> 2. Query returning the number of objects compiled so far. This number
    DOC> should increase with time.
    DOC> SELECT COUNT(*) FROM UTL_RECOMP_COMPILED;
    DOC>
    DOC> This script automatically chooses serial or parallel recompilation
    DOC> based on the number of CPUs available (parameter cpu_count) multiplied
    DOC> by the number of threads per CPU (parameter parallel_threads_per_cpu).
    DOC> On RAC, this number is added across all RAC nodes.
    DOC>
    DOC> UTL_RECOMP uses DBMS_SCHEDULER to create jobs for parallel
    DOC> recompilation. Jobs are created without instance affinity so that they
    DOC> can migrate across RAC nodes. Use the following queries to verify
    DOC> whether UTL_RECOMP jobs are being created and run correctly:
    DOC>
    DOC> 1. Query showing jobs created by UTL_RECOMP
    DOC> SELECT job_name FROM dba_scheduler_jobs
    DOC> WHERE job_name like 'UTL_RECOMP_SLAVE_%';
    DOC>
    DOC> 2. Query showing UTL_RECOMP jobs that are running
    DOC> SELECT job_name FROM dba_scheduler_running_jobs
    DOC> WHERE job_name like 'UTL_RECOMP_SLAVE_%';
    DOC>#
    DECLARE
    ERROR at line 1:
    ORA-04067: not executed, package body "APPS.UTL_RECOMP" does not exist
    ORA-06508: PL/SQL: could not find program unit being called: "APPS.UTL_RECOMP"
    ORA-06512: at line 4
    SELECT dbms_registry_sys.time_stamp('utlrp_end') as timestamp from dual
    ERROR at line 1:
    ORA-00904: "DBMS_REGISTRY_SYS"."TIME_STAMP": invalid identifier
    PL/SQL procedure successfully completed.
    DOC> The following query reports the number of objects that have compiled
    DOC> with errors (objects that compile with errors have status set to 3 in
    DOC> obj$). If the number is higher than expected, please examine the error
    DOC> messages reported with each object (using SHOW ERRORS) to see if they
    DOC> point to system misconfiguration or resource constraints that must be
    DOC> fixed before attempting to recompile these objects.
    DOC>#
    select COUNT(*) "OBJECTS WITH ERRORS" from obj$ where status = 3
    ERROR at line 1:
    ORA-00942: table or view does not exist
    DOC> The following query reports the number of errors caught during
    DOC> recompilation. If this number is non-zero, please query the error
    DOC> messages in the table UTL_RECOMP_ERRORS to see if any of these errors
    DOC> are due to misconfiguration or resource constraints that must be
    DOC> fixed before objects can compile successfully.
    DOC>#
    select COUNT(*) "ERRORS DURING RECOMPILATION" from utl_recomp_errors
    ERROR at line 1:
    ORA-00942: table or view does not exist
    DECLARE
    ERROR at line 1:
    ORA-00942: table or view does not exist
    ORA-06512: at line 31
    BEGIN dbms_registry_sys.validate_components; END;
    ERROR at line 1:
    ORA-06550: line 1, column 7:
    PLS-00201: identifier 'DBMS_REGISTRY_SYS.VALIDATE_COMPONENTS' must be declared
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignored
    Please advise for further.
    Thanks in advance,
    Nish

    950358 wrote:
    Thanks Husain,
    I have run utlrp.sql but still there 777 invalid objects available in my system.
    Please advise.
    Thanks,
    NishWhat is the error you get when you compile those objects?
    How many invalid objects you have under each schema?
    Please see old threads for the invalid objects MOS docs (after R12 upgrade and generic ones).
    https://forums.oracle.com/forums/search.jspa?threadID=&q=Invalid+AND+Objects+AND+12.1.3&objID=c3&dateRange=all&userID=&numResults=15&rankBy=10001
    https://forums.oracle.com/forums/search.jspa?threadID=&q=Invalid+AND+Objects+AND+R12&objID=c3&dateRange=all&userID=&numResults=15&rankBy=10001
    Thanks,
    Hussein

  • How many homeobjects will be created when we deploy a ejb

    when we deploy ejb(session) in the server how many home objects the server will create and if multiple clients request the same beanhome object how the server will maintain plz anybody help me out

    One String object is created when the class is loaded.
    No objects are created when that line is executed.

  • String object vs String literal

    Hi ,
    I understand how the string objects are created using new operator and using literal.I also understand how they are stored in memory.All I want to know is that when and why should I create a String object using new and when I should create an object using literal.Is there any specific reason for creating an object using new operator when objects created by both the ways are immutable.
    Thanks for the help in advance.
    Thanks
    Mouli

    If you look at the String source code (particularly the constructors) youll learn a lot.
    String objects contain a char[] array - and this is the most important part --> a start and length value.
    I believe they were attempting to optimize, but this has important implications for developers.
    String objects dont necessarily store just the text you see, it may just reference a much bigger char array.
    For example, say an API passes you a string that is (lets pretend) a file path (C:\files\java\...\file.txt) that is 1,000,000 characters long.
    Now say that you call getFileName() and want to save the filename in a list.
    String filename = API.getFile("...").getFileName();
    List.add(filename);
    Say you do this about 250,000 times.
    You estimate that the average file name is 10 chars and ensure there is that much RAM.
    You run out of memory. Why?
    Well, this example actually happened to me in a real program I was writing to archive drive files.
    File.getFilename() returns a substring() of the entire File path.
    However, substring is implemented to return a String that just references the original char[] array!
    So the really long file path never gets garbage collected!
    I was able to fix the program by coding it:
    String filename = new String(API.getFile("...").getFileName()); // Copies only the needed chars!
    List.add(filename);
    So thats really all you need to watch out for. If memory is a concern in your program you want to
    make sure you arent referencing large char[] arrays unnecessarily.
    But like all things, this is rarely anything to give much thought to.
    Only something to remember if you run into problems after coding sensibly and profiling
    (or in my case, crashing with OOM exceptions, lol).

  • Looking for CURSOR replacement, please suggest!

    Hello Experts,
    I having some master tables "#ACTION_MASTER" & "#RPT_MILE_MASTER" and a link table "#ACTION_MILE_RPT_LINK" showing their relationship.
    And again I having a derive table "#TBL" to finally update the master table ''#ACTION_MASTER".
    I am able to do the task with below approach and I would like to know how to optimize it, please suggest and let me know for any other information. Thanks! 
    CREATE TABLE #ACTION_MASTER (UID INT, ACTION_ID INT, IS_ACTV BIT)
    INSERT INTO #ACTION_MASTER VALUES (1, 102, 1), (2, 103, 1)
    --SELECT * FROM #ACTION_MASTER
    CREATE TABLE #RPT_MILE_MASTER (UID INT, RPT_ID INT, MILE_ID INT, MILE_STATUS INT)
    INSERT INTO #RPT_MILE_MASTER VALUES (1, 12, 1, 5), (2, 13, 2, 2)
    --SELECT * FROM #RPT_MILE_MASTER
    CREATE TABLE #ACTION_MILE_RPT_LINK (LINK_ID INT, ACTION_ID INT, RPT_ID INT, MILE_ID INT)
    INSERT INTO #ACTION_MILE_RPT_LINK VALUES (1, 102, 12, 1), (2, 102, 13, 2), (3, 103, 13, 2)
    --SELECT * FROM #ACTION_MILE_RPT_LINK
    CREATE TABLE #TBL (RPT_ID INT, MILE_ID INT, MILE_STATUS INT)
    INSERT INTO #TBL VALUES (13, 1, 5), (13, 2, 5)
    --SELECT * FROM #TBL
    DECLARE @ACTION_ID INT
    DECLARE DB_CURSOR CURSOR FOR
    SELECT DISTINCT ACTION_ID FROM #ACTION_MILE_RPT_LINK WHERE MILE_ID IN (SELECT MILE_ID FROM #TBL WHERE MILE_STATUS = 5)
    OPEN DB_CURSOR
    FETCH NEXT FROM DB_CURSOR INTO @ACTION_ID
    WHILE @@FETCH_STATUS = 0
    BEGIN
    IF EXISTS(
    SELECT * FROM #ACTION_MILE_RPT_LINK
    WHERE MILE_ID IN (SELECT MILE_ID FROM #TBL WHERE MILE_STATUS = 5)
    AND RPT_ID NOT IN (SELECT DISTINCT RPT_ID FROM #TBL)
    AND ACTION_ID = @ACTION_ID)
    BEGIN
    DECLARE @COMPARE TABLE (RPT_ID INT, MILE_ID INT, MILE_STATUS INT)
    INSERT INTO @COMPARE
    SELECT RPT_ID, MILE_ID, 5 'MILE_STATUS' FROM #ACTION_MILE_RPT_LINK
    WHERE MILE_ID IN (SELECT MILE_ID FROM #TBL WHERE MILE_STATUS = 5)
    AND RPT_ID NOT IN (SELECT DISTINCT RPT_ID FROM #TBL)
    AND ACTION_ID = @ACTION_ID
    IF NOT EXISTS(
    SELECT RPT_ID, MILE_ID, MILE_STATUS FROM #RPT_MILE_MASTER WHERE RPT_ID IN (SELECT RPT_ID FROM @COMPARE)
    EXCEPT
    SELECT RPT_ID, MILE_ID, MILE_STATUS FROM @COMPARE)
    BEGIN
    UPDATE #ACTION_MASTER SET IS_ACTV = 0 WHERE ACTION_ID = @ACTION_ID
    END
    END
    ELSE
    BEGIN
    UPDATE #ACTION_MASTER SET IS_ACTV = 0 WHERE ACTION_ID = @ACTION_ID
    END
    FETCH NEXT FROM DB_CURSOR INTO @ACTION_ID
    END
    CLOSE DB_CURSOR
    DEALLOCATE DB_CURSOR
    --SELECT * FROM #ACTION_MASTER
    DROP TABLE #ACTION_MASTER
    DROP TABLE #RPT_MILE_MASTER
    DROP TABLE #ACTION_MILE_RPT_LINK
    DROP TABLE #TBL

    I don't understand the values in #TBL. Why are the manually inserted? Shouldn't they be the same as in #RPT_MILE_MASTER?
    Further more I don't understand the condition in the cursor. Both tables have RPT_ID and MILE_ID in common. Either this is a real multivalued relationship, then why do you only filter by MILE_ID? It looks wrong.
    You can rewrite your cursor internals without IF's to
    WITH Compare ( RPT_ID, MILE_ID, MILE_STATUS )
    AS ( SELECT RPT_ID ,
    MILE_ID ,
    5
    FROM #ACTION_MILE_RPT_LINK
    WHERE MILE_ID IN ( SELECT MILE_ID
    FROM #TBL
    WHERE MILE_STATUS = 5 )
    AND RPT_ID NOT IN ( SELECT DISTINCT
    RPT_ID
    FROM #TBL )
    AND ACTION_ID = @ACTION_ID
    UPDATE #ACTION_MASTER
    SET IS_ACTV = 0
    WHERE ACTION_ID = @ACTION_ID
    AND NOT EXISTS ( SELECT RPT_ID ,
    MILE_ID ,
    MILE_STATUS
    FROM #RPT_MILE_MASTER
    WHERE RPT_ID IN ( SELECT RPT_ID
    FROM Compare )
    EXCEPT
    SELECT RPT_ID ,
    MILE_ID ,
    MILE_STATUS
    FROM Compare )
    AND EXISTS ( SELECT *
    FROM #ACTION_MILE_RPT_LINK
    WHERE MILE_ID IN ( SELECT MILE_ID
    FROM #TBL
    WHERE MILE_STATUS = 5 )
    AND RPT_ID NOT IN ( SELECT DISTINCT
    RPT_ID
    FROM #TBL )
    AND ACTION_ID = @ACTION_ID );
    UPDATE #ACTION_MASTER
    SET IS_ACTV = 0
    WHERE ACTION_ID = @ACTION_ID
    AND NOT EXISTS ( SELECT *
    FROM #ACTION_MILE_RPT_LINK
    WHERE MILE_ID IN ( SELECT MILE_ID
    FROM #TBL
    WHERE MILE_STATUS = 5 )
    AND RPT_ID NOT IN ( SELECT DISTINCT
    RPT_ID
    FROM #TBL )
    AND ACTION_ID = @ACTION_ID );
    You can now remove the cursor and JOIN the cursors SELECT into both UPDATEs.

Maybe you are looking for