Why create a String object no need to use constructor?

If we create a Java String object, we will do:
String s = "Hello";
And we won't do:
String s = new String("Hello");
In API doc, String() constructor description says "Initializes a newly created String object so that it represents an empty character sequence. Note that use of this constructor is unnecessary since Strings are immutable."
I am not sure how immutable is related to this??
Also, I wonder if the compiler will convert
String s = "Hello" to
String s = new String("Hello");
Thanks!

String s = new String("Hello");
This is a valid statement too..... But the compiler will not convert String s = "Hello" to String s = new String("Hello") as you suggested. The reason is that java has a sort of a String Bag. Everytime you do a String s = "Hello" it will check the bag and see if such a string already exists. If it does, it merely creates a pointer to it, because strings are immutable, it doesn't need to worry about others modifying that string. If the string doesn't exist then it creates the necessary memory for the string object and adds the reference to the bag.
However, once you do a String s = new String("Hello") what you are saying to the compiler is, "Hey, don't check the bag just create the String." This is all fine and dandy, except that it increases the memory size of your program unnecessarily.
V

Similar Messages

  • New to ABAP Objects. Need help using events

    Hi all,
    I got a program from one of the text books which has the output as
             pursur helps pilot
             stewardess helps passenger on seat 11
             stewardess helps passenger on seat 17
    I am trying to modify this program to get an output:
    purser helps pilot
    stewardess helps passenger on seat 11 to have 2 foodservice.
    stewardess helps passenger on seat 11 to have 2 drinkservice.
    stewardess helps passenger on seat 17
    stewardess helps passenger on seat 17 to have 1 foodservice.
    stewardess helps passenger on seat 17 to have 1 drinkservice.
    stewardess helps passenger on seat 21
    stewardess helps passenger on seat 21 to have 3 foodservice.
    stewardess helps passenger on seat 21 to have 3 drinkservice.
    stewardess helps passenger on seat 25
    stewardess helps passenger on seat 25 to have 1 foodservice.
    stewardess helps passenger on seat 25 to have 1 drinkservice.
    stewardess helps passenger on seat 31
    stewardess helps passenger on seat 31 to have 2 foodservice.
    stewardess helps passenger on seat 31 to have 2 drinkservice.
    I have modified the program and am getting some errors. The program is:
    REPORT  Z_KMADHUR_PROGRAM5.
    class declarations.
    class pilot definition.
    public section.
    methods: call_flight_attendant.
    EVENTS: call_button_presses.
    endclass.
    class passenger definition.
    public section.
    methods: constructor importing value(i_seatnumber) type i,
             service_number importing value(i_servicenumber) type i,
             service_type importing value(i_servicetype) type i,
             call_for_help.
    EVENTS: call_button_pressed exporting value(e_seatnumber) type i,
            call_service_number exporting value(e_servicenumber) type i,
            call_service_type exporting value(e_servicetype) type i.
    PROTECTED SECTION.
    data seatnumber type i.
    data servicenumber type i.
    data servicetype type i.
    endclass.
    class flight_attendant DEFINITION.
    PUBLIC SECTION.
    METHODS: constructor
             importing i_id type string,
             help_the_pilot for EVENT
             call_button_presses OF pilot,
             help_a_passenger FOR EVENT
             call_button_pressed OF passenger
             IMPORTING e_seatnumber, e_wervicenumber, e_servicetype.
             PROTECTED SECTION.
    DATA id TYPE string.
    ENDCLASS.
    class Implementations
    class pilot implementation.
    method call_flight_attendant.
    RAISE EVENT call_button_presses.
    ENDMETHOD.
    ENDCLASS.
             class passenger implementation.
             method: constructor.
             seatnumber = i_seatnumber.
             servicenumber = servicenumber.
             servicetype = servicetype.
             endmethod.
             method: call_for_help.
                      RAISE EVENT: call_button_pressed
                      EXPORTING e_seatnumber = seatnumber,
                      RAISE EVENT call_service_number
                      exporting e_servicenumber = servicenumber,
                      RAISE EVENT call_service_type
                      exporting e_servicetype = servicetype.
                      endmethod.
                      endclass.
    class flight_attendant implementation.
    method constructor.
    id = i_id.
    endmethod.
    method help_the_pilot.
    write: / id, 'helps pilot'.
    endmethod.
    method: help_a_passenger.
    write: / id, 'helps passenger on seat',
    e_seatnumber.
    write:  'to have', e_servicenumber.
    write: e_servicetype.
    endmethod.
    endclass.
    global data
    DATA: o_pilot type ref to pilot,
          o_passenger_1 type ref to passenger,
          o_passenger_2 type ref to passenger,
          o_passenger_3 type ref to passenger,
          o_passenger_4 type ref to passenger,
          o_passenger_5 type ref to passenger.
    DATA: o_purser type ref to flight_attendant,
          o_stewardess type REF to flight_attendant,
          0_foodservice type REF to flight_attendant.
          0_drinkservice type REF to flight_attendant.
    classical processing blocks
          start-of-selection.
          create object: o_pilot,
          o_passenger_1 exporting i_seatnumber = 11,
          o_passenger_2 exporting i_seatnumber = 17,
          o_passenger_2 exporting i_seatnumber = 21,
          o_passenger_2 exporting i_seatnumber = 25,
          o_passenger_2 exporting i_seatnumber = 31.
    create object: o_purser
                   exporting i_id = 'purser',
                   o_stewardess
                   exporting i_id = 'stewardess',
                   o_foodservice
                   exporting i_id = 'foodservice',
                   o_drinkservice
                   exporting i_id = 'drinkservice'.
    set handler: o_purser->help_the_pilot for o_pilot,
                 o_stewardess->help_a_passenger for all instances.
    call method: o_pilot->call_flight_attendant,
    o_passenger_1->call_for_help,
    o_passenger_2->call_for_help.
    I am getting an error "object type passenger doesnot have an event RAISE".
    Any help is appreciated.
    Thanks in advance
    Thanks..

    Hi Madhuri,
    the error that you are getting 'statement is not accessible' is just because u didnt end the data statements with '.'...it is ','...check that
    one more thing when you are creating the object passenger you have to export the 'service number' and the 'service type' also along with 'seatnumber' as you have declared that way in the constructor.
    i made the changes...please check the code..there are no errors but please pass suitable values according to your requirement. right now all the events are getting triggered.
    check this changed code..code in bold
    *& Report  ZTEST_EVENTS
    REPORT  ZTEST_EVENTS.
    class declarations.
    CLASS PILOT DEFINITION.
      PUBLIC SECTION.
        METHODS: CALL_FLIGHT_ATTENDANT.
        EVENTS: CALL_BUTTON_PRESSES.
    ENDCLASS.                    "pilot DEFINITION
          CLASS passenger DEFINITION
    CLASS PASSENGER DEFINITION.
      PUBLIC SECTION.
        METHODS: CONSTRUCTOR IMPORTING VALUE(I_SEATNUMBER) TYPE I
                                      VALUE(I_SERVICENUMBER) TYPE I
                                         VALUE(I_SERVICETYPE) TYPE I,
        CALL_FOR_HELP.
        EVENTS: CALL_BUTTON_PRESSED EXPORTING VALUE(E_SEATNUMBER) TYPE I,
        CALL_SERVICE_NUMBER EXPORTING VALUE(E_SERVICENUMBER) TYPE I,
        CALL_SERVICE_TYPE EXPORTING VALUE(E_SERVICETYPE) TYPE I.
      PROTECTED SECTION.
        DATA SEATNUMBER TYPE I.
        DATA SERVICENUMBER TYPE I.
        DATA SERVICETYPE TYPE I.
    ENDCLASS.                    "passenger DEFINITION
          CLASS flight_attendant DEFINITION
    CLASS FLIGHT_ATTENDANT DEFINITION.
      PUBLIC SECTION.
        METHODS: CONSTRUCTOR
        IMPORTING I_ID TYPE STRING,
        HELP_THE_PILOT FOR EVENT
        CALL_BUTTON_PRESSES OF PILOT,
        HELP_A_PASSENGER FOR EVENT
        CALL_BUTTON_PRESSED OF PASSENGER
        IMPORTING E_SEATNUMBER,
    <b>    CALL_SERVICE_PRESSED FOR EVENT
        CALL_SERVICE_NUMBER OF PASSENGER
        IMPORTING E_SERVICENUMBER,
        CALL_TYPE_PRESSED FOR EVENT
        CALL_SERVICE_TYPE OF PASSENGER
        IMPORTING  E_SERVICETYPE.</b>
      PROTECTED SECTION.
        DATA ID TYPE STRING.
    ENDCLASS.                    "flight_attendant DEFINITION
    class Implementations
    CLASS PILOT IMPLEMENTATION.
      METHOD CALL_FLIGHT_ATTENDANT.
        RAISE EVENT CALL_BUTTON_PRESSES.
      ENDMETHOD.                    "call_flight_attendant
    ENDCLASS.                    "pilot IMPLEMENTATION
          CLASS passenger IMPLEMENTATION
    CLASS PASSENGER IMPLEMENTATION.
      METHOD: CONSTRUCTOR.
        SEATNUMBER = I_SEATNUMBER.
        SERVICENUMBER = I_SERVICENUMBER.
        SERVICETYPE = I_SERVICETYPE.
      ENDMETHOD.                    "constructor
      METHOD: CALL_FOR_HELP.
        RAISE EVENT: CALL_BUTTON_PRESSED
        EXPORTING E_SEATNUMBER = SEATNUMBER.
    <b>    RAISE EVENT: CALL_SERVICE_NUMBER
        EXPORTING E_SERVICENUMBER = SERVICENUMBER.
        RAISE EVENT: CALL_SERVICE_TYPE
        EXPORTING E_SERVICETYPE = SERVICETYPE.</b>
      ENDMETHOD.                    "call_type_help
    ENDCLASS.                    "passenger IMPLEMENTATION
          CLASS flight_attendant IMPLEMENTATION
    CLASS FLIGHT_ATTENDANT IMPLEMENTATION.
      METHOD CONSTRUCTOR.
        ID = I_ID.
      ENDMETHOD.                    "constructor
      METHOD HELP_THE_PILOT.
        WRITE: / ID, 'helps pilot'.
      ENDMETHOD.                    "help_the_pilot
      METHOD: HELP_A_PASSENGER.
        WRITE: / ID, 'helps passenger on seat',
        E_SEATNUMBER.
      ENDMETHOD.                    "help_a_passenger
    <b>  METHOD CALL_SERVICE_PRESSED.
        WRITE: 'to have serviceno', E_SERVICENUMBER.
      ENDMETHOD.                    "call_service_pressed
      METHOD CALL_TYPE_PRESSED..
        WRITE: 'service type' ,E_SERVICETYPE.
      ENDMETHOD.</b>                    "call_type_pressed
    ENDCLASS.                    "flight_attendant IMPLEMENTATION
    global data
    DATA: O_PILOT TYPE REF TO PILOT,
    O_PASSENGER_1 TYPE REF TO PASSENGER,
    O_PASSENGER_2 TYPE REF TO PASSENGER,
    O_PASSENGER_3 TYPE REF TO PASSENGER,
    O_PASSENGER_4 TYPE REF TO PASSENGER,
    O_PASSENGER_5 TYPE REF TO PASSENGER.
    DATA: O_PURSER TYPE REF TO FLIGHT_ATTENDANT,
    O_STEWARDESS TYPE REF TO FLIGHT_ATTENDANT,
    O_FOODSERVICE TYPE REF TO FLIGHT_ATTENDANT,
    O_DRINKSERVICE TYPE REF TO FLIGHT_ATTENDANT.
    classical processing blocks
    START-OF-SELECTION.
      CREATE OBJECT: O_PILOT,
      O_PASSENGER_1 EXPORTING I_SEATNUMBER = 11
                              I_SERVICENUMBER = 12
                              I_SERVICETYPE = 13,
       O_PASSENGER_2 EXPORTING I_SEATNUMBER = 14
                              I_SERVICENUMBER = 15
                              I_SERVICETYPE = 16,
       O_PASSENGER_3 EXPORTING I_SEATNUMBER = 17
                              I_SERVICENUMBER = 18
                              I_SERVICETYPE = 19,
       O_PASSENGER_4 EXPORTING I_SEATNUMBER = 20
                              I_SERVICENUMBER = 21
                              I_SERVICETYPE = 22,
    O_PASSENGER_5 EXPORTING I_SEATNUMBER = 23
                              I_SERVICENUMBER = 24
                              I_SERVICETYPE = 25.
    *o_passenger_2 exporting i_seatnumber = 17,
    *o_passenger_2 exporting i_seatnumber = 21,
    *o_passenger_2 exporting i_seatnumber = 25,
    *o_passenger_2 exporting i_seatnumber = 31.
      CREATE OBJECT: O_PURSER
      EXPORTING I_ID = 'purser',
      O_STEWARDESS
      EXPORTING I_ID = 'stewardess',
      O_FOODSERVICE
      EXPORTING I_ID = 'foodservice',
      O_DRINKSERVICE
      EXPORTING I_ID = 'drinkservice'.
      SET HANDLER: O_PURSER->HELP_THE_PILOT FOR O_PILOT,
      O_STEWARDESS->HELP_A_PASSENGER FOR ALL INSTANCES,
    <b> O_STEWARDESS->CALL_SERVICE_PRESSED FOR ALL INSTANCES,
      O_STEWARDESS->CALL_TYPE_PRESSED FOR ALL INSTANCES.</b>
      CALL METHOD: O_PILOT->CALL_FLIGHT_ATTENDANT,
      O_PASSENGER_1->CALL_FOR_HELP.
    similarly call the methods for the other objects also.
    Regards,
    Vidya

  • Createing string objects

    String s= new String("abc");
    String s1="abc";Is there any performence issue between these two?
    I think both will take same time to create objects.

    Yes, there is a performance implication.
    When using the first line String s = new String("abc"); you are actually creating two objects. As a general rule, you should never use a String class constructor when initializing to a literal value. Even doing String s = new String("abc" + someVariable) is creating one more object than needed. "abc" is the firs object, the result of "abc" + someVariable is the second object, and the String created by the constructor is the third.
    It should be noted most recent JVMs use some level of caching of String Literal value objects (I believe this goes as far back as JDK 1.3), such that "abc" is only be created once by the JVM (though I'm not sure if it will cache all literal String objects or use some type of LRU algorthm to discard some of them). Regardless, there is some level of efficiency you get from the JVM doing this. Thus if a method containing String s = "abc" is called repeatedly, a reference to the same String object should be used everytime; there will be no further creations of the object as long as the JVM keeps it in cache.
    Using String s= new String("abc") will leverage the cached literal reference to "abc", but also creates a new instance of String to refer to the literal everytime your method is called. This is much less efficient.
    Run the following code (I did it using JDK 6):
    package org.einsteinium.samples;
    public class StringTest {
         public static void main(String[] args) {
              String s1 = "abc";
              String s2 = "abc";
              boolean equalMethodTest = s1.equals(s2);
              System.out.println("Are the objects the same using the equals method? " + equalMethodTest);
              boolean equalOperatorTest = (s1 == s2);
              System.out.println("Are the objects the same using the equal operator? " + equalOperatorTest);
    }It will print:
    Are the objects the same using the equals method? true
    Are the objects the same using the equal operator? trueNow if you re-write it to:
    package org.einsteinium.samples;
    public class StringTest {
         public static void main(String[] args) {
              String s1 = new String("abc");
              String s2 = "abc";
              boolean equalMethodTest = s1.equals(s2);
              System.out.println("Are the objects the same using the equals method? " + equalMethodTest);
              boolean equalOperatorTest = (s1 == s2);
              System.out.println("Are the objects the same using the equal operator? " + equalOperatorTest);
    }it will print:
    Are the objects the same using the equals method? true
    Are the objects the same using the equal operator? falseI hope this helps some.

  • Why create "new Object()"

    Why would anyone want to create a Object?
    Object obj = new Object();
    I've seen people use it during synchronization locks but why create a new object instead of any other alternatives?
    synchronized(obj) {
    Are there any other uses for Object?

    This is one of the most usual use for new Object() that I've come across - it's used to provide something to lock against that can be shared between various instances. An Object instance is considered lightweight (ie, the minimal thing you can lock against) and it doesn't imply that it will be used in your code for anything else (since it doesn't do much else).
    You're right that there are other alternatives (often overlooked), such as synchronising on a Class instance (this.getClass() or MyClass.class) - this is at least guaranteed to exist and therefore its being lightweight doesn't really matter. But it's not always appropriate, especially if you've got various levels of locking going on. As usual, you've got to choose what best suits your own situation and your own personal style.
    Another use for an Object instance is to provide an enumeration of constants whose value isn't important:
    public class MyLayoutManager implements LayoutManager
      public static final Object NORTH = new Object();
      public static final Object SOUTH = new Object();
    }I'm not suggesting that my example is ideal (personally I'd choose a constant whose toString at least made sense for debugging) but it does demonstrate how you can use an Object to provide constants for use by other bits of code (or even internally, say as keys into a Map) - they simply do something like MyLayoutManager.NORTH to indicate something to my code.
    Clearly there are other uses for Object (such as being the base class for everything) and providing default implementations of hashCode, equals and all the locking stuff. But I can't think of any other uses of an Object instance that I've had before. No doubt other people have come across some...
    Hope this helps.

  • 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).

  • String objects' behavior

    Hello,
    I have two classes
    testA
    public class testA {
    public static void main(String args[]) {
    String s1 = "abc";
    String s2 = "abc";
    if(s1 == s2)
    System.out.println(1);
    else
    System.out.println(2);
    if(s1.equals(s2))
    System.out.println(3);
    else
    System.out.println(4);
    testB
    public class testB {
    public static void main(String args[]) {
    String s1 = "abc";
    String s2 = new String("abc");
    if(s1 == s2)
    System.out.println(1);
    else
    System.out.println(2);
    if(s1.equals(s2))
    System.out.println(3);
    else
    System.out.println(4);
    Why is the first test (s1==s2) evaluating to true (haven't we got two string objects here??) and the second evaluating to false?
    Thanks in advance,
    Balteo.

    The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. The JVM can reuse and share string references because strings are immutable and, therefore, by definition thread-safe. In fact string objects will be stored in a pool whenever you create a string object JVM will check if it exists in the pool otherwise it creates. If it exists in the pool then JVM gets it from the pool and there is no harm in doing so, because strings are immutable - can't be changed. When you explicitly create a string object like String str = new String()...It will create a new object (it may or maynot exist in the pool). The equals() method of Object class does the indepth comparison i.e it compares the actual objects unlike the object reference in the case of == operator.
    I would like to tell you to visit the Javaworld site (URL: http://www.javaworld.com/javaqa/2002-09/01-qa-0906-strings.html?#) where similar questions are answered.
    I hope this helps out you better.
    Sree Ramakrishna
    That's a nice design; although a design you must be aware of and treat accordingly.

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

  • StringBuffer v.s. String objects

    When creating a string object, I realize that when you concatenate an existing string object, a new reference is created for the concatenation and the old reference is dereferenced. Does this mean that it's destroyed and the memory used by this old String object is returned?

    In the statements
    String a = "A";
    String b = "B";
    a = a+b;
    the old object referenced by 'a' is no longer referenced by 'a' as it is now referencing a new String containing the result of buliding a StringBuffer from "A" and appending "B" then converting to a String with .toString(). The old String object that is no longer referenced will be garbage collected eventually.

  • Which is the best way to create a connection object

    hi,
    Eventhough i am not new to java I just wanted to know that which is the best way for creating sql connection object.
    Is it using the DriverManager.getConnection(..,..,..) or using a datasource and getting the connection.
    Which is more efficient or Is there any other way to create sql connection which is even more better.
    thanks in advance.
    pradeepbhargav

    AFAIK all connections, DataSource ones included are created by calling the DriverManager. A DataSource is a factory for Connection objects (from JavaDocs)
    If you're talking about managing connections then it depends on the application. A DataSource is great for apps that can support many clients or are multi-threaded, but may require a JNDI implementation to get to it.
    If however you have an single threaded app that hits the database in a serial fashion, then DataSource is probably an overkill.
    Dave

  • Why r we allowed to create String objects with & without using new operator

    While creating any object, usage of the new operator is a must...but only for the string object we can create it with and also without new operator how is it possible to create an object without using new operator.

    Because Mr. (Dr.?) Gosling is a kindly soul who realizes that programmers have deadlines and, when he designed Java, was not so rigid or unbending as not to realize that from time to time, certain shortcuts are warranted, even in a relatively pure language such as Java. The direct String literal assignments are a shortcut over using the new operator making Java programming (and execution; there's also a performance benefit) more streamlined.
    So look not the gift horse in the mouth, but simply bask in the simplification and ease on the eyes and directly assign your little literals to your heart's content.

  • Why jvm maintains string pool only for string objects why not for other objects?

    why jvm maintains string pool only for string objects why not for other objects? why there is no pool for other objects? what is the specialty of string?

    rp0428 wrote:
    You might be aware of the fact that String is an immutable object, which means string object once created cannot be manipulated or modified. If we are going for such operation then we will be creating a new string out of that operation.
    It's a JVM design-time decision or rather better memory management. In programming it's quite a common case that we will define string with same values multiple times and having a pool to hold these data will be much efficient. Multiple references from program point/ refer to same object/ value.
    Please refer these links
    What is Java String Pool? | JournalDev
    Why String is Immutable in Java ? | Javalobby
    Sorry but you are spreading FALSE information. Also, that first article is WRONG - just as OP was wrong.
    This is NO SUCH THING as a 'string pool' in Java. There is a CONSTANT pool and that pool can include STRING CONSTANTS.
    It has NOTHING to do with immutability - it has to do with CONSTANTS.
    Just because a string is immutable does NOT mean it is a CONSTANT. And just because two strings have the exact same sequence of characters does NOT mean they use values from the constant pool.
    On the other hand class String offers the .intern() method to ensure that there is only one instance of class String for a certain sequence of characters, and the JVM calls it implicitly for literal strings and compile time string concatination results.
    Chapter 3. Lexical Structure
    In that sense the OPs question is valid, although the OP uses wrong wording.
    And the question is: what makes class Strings special so that it offers interning while other basic types don't.
    I don't know the answer.
    But in my opinion this is because of the hybrid nature of strings.
    In Java we have primitive types (int, float, double...) and Object types (Integer, Float, Double).
    The primitive types are consessons to C developers. Without primitive types you could not write simple equiations or comparisons (a = 2+3; if (a==5) ...). [autoboxing has not been there from the beginning...]
    The String class is different, almost something of both. You create String literals as you do with primitives (String a = "aString") and you can concatinate strings with the '+' operator. Nevertheless each string is an object.
    It should be common knowledge that strings should not be compared with '==' but because of the interning functionality this works surprisingly often.
    Since strings are so easy to create and each string is an object the lack ot the interning functionality would cause heavy memory consumption. Just look at your code how often you use the same string literal within your program.
    The memory problem is less important for other object types. Either because you create less equal objects of them or the benefit of pointing to the same object is less (eg. because the memory foot print of the individual objects is almost the same as the memory footpint of the references to it needed anyway).
    These are my personal thoughts.
    Hope this helps.
    bye
    TPD

  • Failed to create object.Help needed

    Hi, I have some program here, the BPDU class and also the RootBridge class. The BPDU class is just a simple class with all the getMethods and the setMethods. For the RootBridge class, it is suppose to connect to the JDBC ODBC database, and create arraylist and retrieve the mac address, priority and also the port id from the database. However, when I tried to create a BPDU object, it gives me an error saying :
    --------------------Configuration: j2sdk1.4.2_01 <Default>--------------------
    F:\new Project FYP\RootBridge.java:43: BPDU(java.lang.String,double,java.lang.String,int,java.lang.String,java.lang.String) in BPDU cannot be applied to ()
                        BPDU bpdu =new BPDU();
    ^
    1 error
    Here are the classes:
    BPDU class:
    public class BPDU
         private String BridgeIDMac;
         private double BridgeIDPriority;
         private String MsgType;
         private int CostPath;
         private String PortID;
         private String ComputerName;
         public BPDU(String BridgeIDMac, double BridgeIDPriority,String MsgType,int CostPath, String PortID, String ComputerName)
              this.BridgeIDMac=BridgeIDMac;
              this.BridgeIDPriority=BridgeIDPriority;
              this.MsgType=MsgType;
              this.CostPath=CostPath;
              this.PortID=PortID;
              this.ComputerName=ComputerName;
         public String getBridgeIDMac()
              return BridgeIDMac;
         public double getBridgeIDPriority()
              return BridgeIDPriority;
         public String getMsgType()
              return MsgType;
         public int getCostPath()
              return CostPath;
         public String getPortID()
              return PortID;
         public String getComputerName()
              return ComputerName;
         //SET METHODS
         public void setBridgeIDMac(String mac)
              BridgeIDMac=mac;
         public void setBridgeIDPriority(double priority)
              BridgeIDPriority=priority;
         public void setMsgType(String msg)
              MsgType=msg;
         public void setCostPath(int costpath)
              CostPath=costpath;
         public void setPortID(String portid)
              PortID=portid;
         public void setComputerName(String computername)
              ComputerName=computername;
    RootBridge Class:
    import java.util.*;
    import java.sql.*;
    import java.io.*;
    import java.net.*;
    import java.lang.*;
    public class RootBridge
         private Connection con;
         private String macaddress;
         private int priority;
         private int portid;
         public RootBridge()
              try
                   //ESTABLISH THE JDBC DATABASE CONNECTION
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   con = DriverManager.getConnection("jdbc:odbc:BPDU");
              catch(ClassNotFoundException c)
                   System.out.println(c+": JDBC Driver Could Not Be Loaded.");
              catch(SQLException s)
                   System.out.println(s+": Database Connection Could Not Be Established.");
         //TO RETRIEVE THE COMPUTER NAME  IN DATABASE
         public ArrayList retrieveComputerName()
              ArrayList arraylist=new ArrayList();
              try
                   PreparedStatement p=con.prepareStatement("Select ComputerName from BPDU");
                   ResultSet rs= p.executeQuery();
                   if(rs.next())
                        //************Here is the error
                                                                                         BPDU bpdu =new BPDU();                    bpdu.setComputerName(rs.getString("ComputerName"));
                        arraylist.add(bpdu);
              catch(SQLException s)
                   System.out.println(s+": Could not retrieve computer name from database");
              return arraylist;
         //to get the mac address that belong to the computer
         public BPDU retrieveMacAddress(String computername)
              System.out.println("DB1"+computername);
              try
                   PreparedStatement p=con.prepareStatement("Select BridgeIDMAC from BPDU where ComputerName=?" );
                   System.out.println("DB2"+computername);
                   p.setString(1,computername);
                   p.setString(2,computername);
                   p.setString(3,computername);
                   ResultSet rs=p.executeQuery();
                   if(rs.next())
                        macaddress=rs.getString("BridgeIDMAC");
                   System.out.println("DB4"+macaddress);
              catch(SQLException s)
                   System.out.println(s+": Could not retrieve the mac address from database");
         //to retrieve priority from database
         public BPDU retrievePriority(String computername)
              System.out.println("DB1"+computername);
              try
                   PreparedStatement p=con.prepareStatement("Select BridgeIDPriority from BPDU where ComputerName=?" );
                   System.out.println("DB2"+computername);
                   p.setString(1,computername);
                   p.setString(2,computername);
                   p.setString(3,computername);
                   ResultSet rs=p.executeQuery();
                   if(rs.next())
                        priority=rs.getInt("BridgeIDPriority");
                   System.out.println("DB4"+priority);
              catch(SQLException s)
                   System.out.println(s+": Could not retrieve the priority from database");
         //to retrieve port id from database
         public BPDU retrievePortID(String computername)
              System.out.println("DB1"+computername);
              try
                   PreparedStatement p=con.prepareStatement("Select PortID from BPDU where ComputerName=?" );
                   System.out.println("DB2"+computername);
                   p.setString(1,computername);
                   p.setString(2,computername);
                   p.setString(3,computername);
                   ResultSet rs=p.executeQuery();
                   if(rs.next())
                        portid=rs.getInt("PortID");
                   System.out.println("DB4"+portid);
              catch(SQLException s)
                   System.out.println(s+": Could not retrieve the port id from database");
    }Please see //************Here is the error in the Root Bridge class.Help me to solve the problem.Thank You very much

    Hi,
    The error message means that the BPDU class doesn't have an empty constructor. You must pass the in needed arguments to the BPDU constuctor.
    /Kaj

  • Why String Objects are immutable ?

    From the JLS->
    A String object is immutable, that is, its contents never change, while an array of char has mutable elements. The method toCharArray in class String returns an array of characters containing the same character sequence as a String. The class StringBuffer implements useful methods on mutable arrays of characters.
    Why are String objects immutable ?

    I find these answers quite satisfying ...
    Here's a concrete example: part of that safety is ensuring that an Applet can contact the server it was downloaded from (to download images, data files, etc) and not other machines (so that once you've downloaded it to your browser behind a firewall, it can't connect to your company's internal database server and suck out all your financial records.) Imagine that Strings are mutable. A rogue applet might ask for a connection to "evilserver.com", passing that server name in a String object. The JVM could check that this server name was OK, and get ready to connect to it. The applet, in another thread, could now change the contents of that String object to "databaseserver.yourcompany.com" at just the right moment; the JVM would then return a connection to the database!
    You can think of hundreds of scenarios just like that if Strings are mutable; if they're immutable, all the problems go away. Immutable Strings also result in a substantial performance improvement (no copying Strings, ever!) and memory savings (can reuse them whenever you want.)
    So immutable Strings are a good thing.
    The main reason why String made immutable was security. Look at this example: We have a file open method with login check. We pass a String to this method to process authentication which is necessary before the call will be passed to OS. If String was mutable it was possible somehow to modify its content after the authentication check before OS gets request from program then it is possible to request any file. So if you have a right to open text file in user directory but then on the fly when somehow you manage to change the file name you can request to open "passwd" file or any other. Then a file can be modified and it will be possible to login directly to OS.
    JVM internally maintains the "String Pool". To achive the memory efficiency, JVM will refer the String object from pool. It will not create the new String objects. So, whenever you create a new string literal, JVM will check in the pool whether it already exists or not. If already present in the pool, just give the reference to the same object or create the new object in the pool. There will be many references point to the same String objects, if someone changes the value, it will affect all the references. So, sun decided to make it immutable.

  • Unable to create a Driver object from driver with Media type string CTC PHO

    Hi All,
    I am trying to develop a siebel cti adapter for avaya.
    I have loaded a custom dll into siebel server but it is throwing error "SBL-CSR-00500: Unable to create a Driver object from driver C:\Mydriver\cti.dll with Media-Type-String CTC Phone ".
    It has been long time without any progress.
    Please help
    Thanks
    Nishant

    Hi tomhowell,
    According to your description, my understanding is that you got an error when you created a site from a custom site template after migrading SharePoint 2010 to your server.
    Did you have the original solution file of the site template? Please re-deploy the solution to your SharePoint site, then create a site from the new site template, compare the result.
    Also use  SPDisposeCheck to indentify the memory leak:
    http://archive.msdn.microsoft.com/SPDisposeCheck
    http://www.fewlines4biju.com/2012/11/detected-use-of-sprequest-for.html
    Here are some similar posts for your reference:
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/3a25eb86-8415-4053-b319-9dd84a1fd71f/detected-use-of-sprequest-for-previously-closed-spweb-object-please-close-spweb-objects-when-you?forum=sharepointdevelopmentprevious
    http://social.msdn.microsoft.com/Forums/en-US/50ce964f-94a6-4fda-abc0-caa34e7111f1/error-detected-use-of-sprequest-for-previously-closed-spweb-object-occurs-when-new-site-gallery
    I hope this helps.
    Thanks,
    Wendy
    Wendy Li
    TechNet Community Support

  • Why should I wrap String objects in a class for my HtmlDataTable?

    Hi,
    Let me describe a basic scenario in which my problem occurs. I have a backing bean and a JSP. The JSP gets a List<String> which is displayed inside a column in an editable HtmlDataTable. Each row in the data table has a UICommandLink that can perform an update to the value in the first column. Hence, the table only has two columns: one input field and one command link.
    My problem is this: When I try to execute HtmlDataTable#getRowData() when the command link is pressed, the updated values are not retrieved, but instead the values that have been in the input field before any changes were made. However, if I instead wrap my List objects inside a StringWrapper class (with a String property and appropriate getters and setters) such that I have a List<StringWrapper>, the problem does not occur. Why is this and is there any way to avoid it?
    I typed out some code to illustrate my scenario. Example 1 is where the table displays a list of String objects and Example 2 is where the table displays a list of StringWrapper objects.
    Example 1: [http://pastebin.com/m2ec5d122|http://pastebin.com/m2ec5d122]
    Example 2: [http://pastebin.com/d4e8c3fa3|http://pastebin.com/d4e8c3fa3]
    I'll appreciate any feedback, many thanks!

    Hi,
    Let me describe a basic scenario in which my problem occurs. I have a backing bean and a JSP. The JSP gets a List<String> which is displayed inside a column in an editable HtmlDataTable. Each row in the data table has a UICommandLink that can perform an update to the value in the first column. Hence, the table only has two columns: one input field and one command link.
    My problem is this: When I try to execute HtmlDataTable#getRowData() when the command link is pressed, the updated values are not retrieved, but instead the values that have been in the input field before any changes were made. However, if I instead wrap my List objects inside a StringWrapper class (with a String property and appropriate getters and setters) such that I have a List<StringWrapper>, the problem does not occur. Why is this and is there any way to avoid it?
    I typed out some code to illustrate my scenario. Example 1 is where the table displays a list of String objects and Example 2 is where the table displays a list of StringWrapper objects.
    Example 1: [http://pastebin.com/m2ec5d122|http://pastebin.com/m2ec5d122]
    Example 2: [http://pastebin.com/d4e8c3fa3|http://pastebin.com/d4e8c3fa3]
    I'll appreciate any feedback, many thanks!

Maybe you are looking for

  • Trading Partner field in GL entry

    We are in ECC6. We want to enter manually the 'Trading Partner' field in certain GL postings. But when we enter the GL document using F-02, this field is not appearing for input. We looked in additional data fields also. But not available. We are usi

  • Security create-keychain does not add the keychain to search list

    Hello guys, It seems that since OS X Mavericks the security create-keychain does not add the keychain in the search list. I tried calling the SecKeychainCreate directly to verify that this is not a bug in the SecurityTool (the result is the same). Co

  • Photoshop Elemenst 12 and Windows 8.1

    Hello, I'm using windows  8.1 with a FULL HD resolution (1920 x 1080) but the menue, the menuelist and the icon's at the left side didn't be upscaled. What can I do, to resice the menue,...

  • Suggestions b4 installing 11g on Servr 2003 with 10g already

    Hi, Are there any pitfalls I need to be aware of before installing 11gR2 onto Windows Server 2003 with 10g (10.2.0.5.0) already installed? I've searched the forum and found threads on multiple installations in Linux, Solaris and AIX, but not on on Wi

  • PKCS#11 with Smart card

    Hi I'm new to smart card technologies. I need some help regarding this. I have to write a application which will store the keys in a smart card. I'm suppose to use pkcs# 11. I don't know from where to start. Can anyone tell me the what to do. I'm usi