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

Similar Messages

  • String Object info not getting displayed in outgoing referrences .

    Hi,
    Iam new to MAT and is in learning stage.
    Iam having a sample java program , whch has got String objects printed contunously . In order to take the heap dump while running itself , I am running this application for 2 minutes and in between Im taking the heap dump , but when analysed my java class , found that there is no entry for String objects under outgoing referrences of the java class from histogram.
    Please help me to find out why String object details are not present in outgoiing referrences for the java class.
    My Java Program,
    public class B{
    public static void main(String[] args) {
              //create Calendar instance
             Calendar now = Calendar.getInstance();
             System.out.println("Current time : "+ now.get(Calendar.HOUR_OF_DAY)+ ":" + now.get(Calendar.MINUTE)+ ":"+ now.get(Calendar.SECOND));
             int m = now.get(Calendar.MINUTE);
             B b = new B();
             b.print();
    public void print( int m2, Calendar now2){
               while ( (m2+2) >= now2.get(Calendar.MINUTE)){
                       String x = "xxxxxx";
                        System.out.println("String"+x);

    Hi,
    Do you mean this String object?
       String x = "xxxxxx";
    If so, then here the explanation. The String above is declared as a loca variable in the print method. I can't see any field pointing to it (neider an object insance is pointing to it, nor a static reference from the class).
    This local object will be in the heap as long as the method is running, and in the heap dump you will see such objects marked as GC roots. The type of this GC root will be <Java local> .
    Depending on the heap dump format, there may be also stack traces inside. If there are stack traces, you shold be able to see your object as referenced from the corresponding frame (the print method) in the Thread Stacks query.
    I hope this helps.
    Krum

  • How to execute a method from String object?

    I have some methods in String objects, example:
    String methodOne = "someMethod1";
    String methodTwo = "someMethod2";
    public void someMethod1() {
    public void someMethod2() {
    How can i execute that methods, when the method names i have only in String objects?

    You can get the method directly from the name and parameter types if you want to avoid using the loop:public class Foo27 {
      public static void main (String[] args) throws Exception{
        String methodOne = "someMethod1";
        String methodTwo = "someMethod2";
        Object foo = new Foo27();
        Method method1 = foo.getClass().getMethod(methodOne, new Class[]{});
        method1.invoke(foo, null);
        Method method2 = foo.getClass().getMethod(methodTwo, null);
        method2.invoke(foo, null);
      public void someMethod1() {
        System.out.println("someMethod1");
      public void someMethod2() {
        System.out.println("someMethod2");
    }The parameter types are required as there could be more than one method with the same name.
    For somereason when I tried to create a new Method object and invoke it, an exception was thrownThere isn't a public constructor for Method, so how did you create a new one?
    Pete

  • Converting Base64 encoded String to String object

    Hi,
    Description:
    I have a Base64 encoded string and I am using this API for it,
    [ http://ws.apache.org/axis/java/apiDocs/org/apache/axis/encoding/Base64.html]
    I am simply trying to convert it to a String object.
    Problem:
    When I try and write the String, ( which is xml ) as a XMLType to a oracle 9i database I am getting a "Cannot map Unicode to Oracle character." The root problem is because of the conversion of the base64 encoded string to a String object. I noticed that some weird square characters show up at the start of the string after i convert it. It seems like I am not properly converting to a String object. If i change the value of the variable on the fly and delete these little characters at the start, I don't get the uni code error. Just looking for a second thought on this.
    Code: Converting Base64 Encoded String to String object
    public String decodeToString( String base64String )
        byte[] decodedByteArray = Base64.decode( base64String );
        String decodedString = new String( decodedByteArray, "UTF-8");
    }Any suggestions?

    To answer bigdaddy's question and clairfy a bit more:
    Constraints:
    1. Using a integrated 3rd party software that expects a Base64 encoded String and sends back a encoded base64 String.
    2. Using JSF
    3. Oracle 10g database and storing in a XMLType column.
    Steps in process.
    1. I submit my base64 encoded String to this 3rd party software.
    2. The tool takes the encoded string and renders a output that works correctly. The XML can be modified dynamically using this tool.
    3. I have a button that is binded to my jsf backing bean. When that button is clicked, the 3rd party tool sets a backing bean string value with the Base64 String representing the updated XML.
    4. On the backend in my jsf backing bean, i attempt to decode it to string value to store in the oracle database as a XML type. Upon converting the byte[] array to a String, i get this conversion issue.
    Possibly what is happen is that the tool is sending me a different encoding that is not UTF-8. I thought maybe there was a better way of doing the decoding that i wasn't looking at. I will proceed down that path and look at the possibility that the tool is sending back a different encoding then what it should. I was just looking for input on doing the byte[] decoding.
    Thanks for the input though.
    Edited by: haju on Apr 9, 2009 8:41 AM

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

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

  • Diffrence between assign a String object  by literal and through new

    Plz tell me
    What is the diffrence between
    String x = "surya";
    or
    String y = new String("Surya");

    Plz tell me
    What is the diffrence between
    String x = "surya";
    or
    String y = new String("Surya");When String x = "surya"; is compiled it is placed in the class's pool of strings. If the same string literal is found elsewhere in the class the same string litteral in the pool is reused ( this is possible since String is immutable ).
    When you use the constructor in String to create the string, a whole new String instance is created. However, this causes extra memory allocation for no apparent advantage

  • 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

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

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

  • String object equivalency

    Maybe someone could explain this to me.
    String a="abc";
    String b="abc";
    a == b // true
    I thought == compared the object reference, not the value. Is == overloaded in the String object or are Strings created differently than other objects so the two different variables really are pointing at the same object?

    jamesss wrote:
    Maybe someone could explain this to me.
    String a="abc";
    String b="abc";
    a == b // true
    I thought == compared the object reference, not the value.Yep.
    Is == overloaded in the String objectNo
    or are Strings created differently than other objects so the two different variables really are pointing at the same object?They're not created differently than other objects other than that here you didn't need to use the "new" keyword. They are referencing the same literal constant in the string pool.

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

  • Can we change data in string object.

    Can we change data in string object.

    Saw this hack to access the char[]'s in a String in another thread. Beware that the effects of doing this is possible errors, like incorrect hashCode etc.
    import java.lang.reflect.*;
    public class SharedString {
            public static Constructor stringWrap = null;
            public static String wrap(char[] value, int offset, int length) {
                    try {
                            if (stringWrap == null) {
                                    stringWrap = String.class.getDeclaredConstructor(new Class[] { Integer.TYPE, Integer.TYPE, char[].class });
                                    stringWrap.setAccessible(true);
                            return (String)stringWrap.newInstance(new Object[] { new Integer(offset), new Integer(length), value });
                    catch (java.lang.NoSuchMethodException e) {
                            System.err.println ("NoMethod exception caught: " + e);
                    catch (java.lang.IllegalAccessException e) {
                            System.err.println ("Access exception caught: " + e);
                    catch (java.lang.InstantiationException e) {
                            System.err.println ("Instantiation exception caught: " + e);
                    catch (java.lang.reflect.InvocationTargetException e) {
                            System.err.println ("Invocation exception caught: " + e);
                    return null;
            public static void main(String[] args) {
                    char[] chars = new char[] { 'l', 'e', 'v', 'i', '_', 'h' };
                    String test = SharedString.wrap(chars, 0, chars.length);
                    System.out.println("String test = " + test);
                    chars[0] = 'k';
                    chars[1] = 'a';
                    chars[2] = 'l';
                    chars[3] = 'l';
                    chars[4] = 'a';
                    chars[5] = 'n';
                    System.out.println("String test = " + test);
    } Gil

  • How to create a xml file from String object in CS4

    Hi All,
    I want to convert a string object into an XML file using Javascript in Indesign CS4.
    I have done the following script. But it does not convert the namespaces for the xml elements with no value in it.
    var xml = new XML(string);
    The value present in string is "<level_1 xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>"
    When it is converted to xml, the value becomes "<level_1 xsi:nil="true"/>"
    On processing the above xml object, am getting an error like this "Uncaught JavaScript exception: Unbound namespace prefix."
    Kindly help.
    Thanks,
    Anitha

    Can you post more of the script?
    Are you getting the XML file from disk, or a string?

Maybe you are looking for