String objects

String s1 = "abc";
String s2 = "def";is it correct that s1 and s2 are both references to the same object? and therefore this same object has two different values, being "abc" and "def"?
thanks.

how can they become all of a sudden different objects
just cause one of the values change?Have a look at this "drawing":
// Start JVM
/*               +----------+
                 |          |
   String-pool:  |          |
                 |          |
                 +----------+
String s1 = "qwe";
   "qwe" is not in the pool, so it gets created
                 +----------+
                 |        +-+---[s1]
   String-pool:  |        | |
                 |"qwe"<--+ |
                 +----------+
String s2 = "qwe";
   "qwe" IS in the pool, so it gets 'recycled'
                 +----------+
                 |        +-+---[s1]
   String-pool:  |        | |
                 |"qwe"<--+-+---[s2]
                 +----------+
s1 = "qaz";
   point s1 to a different String (which is not yet present, so it gets created)
                 +----------+
                 |"qaz"<----+---[s1]
   String-pool:  |          |
                 |"qwe"<----+---[s2]
                 +----------+
*/Note that, as already mentioned by the previous poster, that s1 and s2 are merely references* to String objects.
* think of them as pointers, as you will (not too loud though!)
; )

Similar Messages

  • 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

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

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

  • XML validation with DTD stored in String object

    Does anyone know if this is plausible......
    I am trying to validate some XML with a DTD... easy enough, right? The catch is that the dtd is NOT stored in a file somewhere and is also not declared in the XML to be validated. It is stored in a String object (as is the XML file to be validated).
    To clarify - I want to do something like this... but not sure how to incorporate the DTD.
    String dtd = // dtd definition here
    String xml = // xml text here (no URI at the top)
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    DefaultHandler handler = new DefaultHandler();  // DTD handler??
    parser.parse(new InputSource(new StringReader(xml.toString())), handler);any help would be greatly appreciated.
    thanks in advance,
    Terrance

    I guess it makes the most sense to make the dtd local to the xml. Therefore I would only have one string with both the xml contents and dtd contents. That is how I am going to approach this unless I hear something different.

  • How to validate the string object for alphabet input

    Hi,
    I want to check for alphabet (a-z,A-Z), in String object. I need to check the object, whether its contain numerals or special character, in that case, I want to throw an error stating that "value is not valid". It should accept only the a-z or A-Z.
    how to do this.
    Thanks in advance
    Karthi

    > I want to check for alphabet (a-z,A-Z), in String
    object. I need to check the object, whether its
    contain numerals or special character, in that case,
    I want to throw an error stating that "value is not
    valid". It should accept only the a-z or A-Z.
    how to do this.
    As Rene suggested, you can do this using the Pattern class:
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
    You can do it also by looping through your String and check with String's charAt(index) method (which returns a char) to see if every char from the String is >= A AND <= z.
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html
    Good luck.

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

  • Problem in showing value of a string object of jsp to on page

    hello there
    i have a problem that i m fatching a value from a JavaBean in my jsp page now i want to print that value in my jsp page but i is createing problem
    my probelm is that the value which i have been fatching from my javabean contain code like
    #include<stdio.h>
    #include<conio.h>
    void main
    int a=10;
    printf("%d",a);
    getch();
    i m getting this code in a variable in a String object myCode
    and when i m displaying this using
    <%=myCode%>
    it is giving output as follows
    #include<stdio.h> #include<conio.h> void main { int a=10; printf("%d",a);
    getch();}
    can you tell me why it is creating a problem
    plz help me
    thanks in advance
    pawan gupta

    HTML formats in its own special way. It ignores spaces/newlines.
    Try using <pre> tags to tell the browser "this is pre-formatted text. Don't screw around with it"
    ie
    <pre><%= myCode %></pre>
    Cheers,
    evnafets

  • Non-string objects as parameters to an applet

    how can i pass non-string objects as parameters to an applet?
    thanks in advance...

    those are some objects that i wroteThen, you could use Class.forName() method for your string parameters.
    If you get the classes, then you can call newInstance() method on them to get objects.
    Alternative way could be using your string parameter as index or keys for some
    data structures that contains ready-made objects.

  • To add a string object to a list

    hi all,
    i am trying a string object usind add method
    like
    String s="xyz";
    list.add(s)
    when i try to compile the code it says that the code contains an unchecked exception..please tell me how to handle this exception.....like if its not the correct way please do post some code...........
    thanks

    To handle exceptions you need try/catch statements around the code which is potentially bad.
    The code you have shown here should not throw an exception - it must be something else you have - maybe reading from file, parsing an Integer to a string etc etc
    Read the section on [url http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html] exceptions in the tutorial
    try{
    // do some code
      String s = "xyz";
      list.add(s);
    catch(Exception e){
      System.out.println("An error occurred " + e.getMessage());
      e.printStackTrace();
    }Cheers,
    evnafets

  • Convert Map String, Object to Map String,String ?

    How can I convert a map say;
    Map<String, Object> map = new Map<Striing, Object>();
    map.put("value", "hello");
    to a Map<String,String>.
    I want to pass the map to another method which is expecting Map<String,String>.
    Thanks

    JoachimSauer wrote:
    shezam wrote:
    Because im actaully calling an external method to populate map which returns <String, Object>.Now we're getting somewhere.
    Oh wait, no, we're not! We're back to my original reply:
    What do you want and/or expect to happen if one of the values isn't actually a String object but something else?Nothing like a bit of confusion :). They are and always will be String objects.
    So this external method, call it external1 for now returns a Map<String, Object>, I then want to pass this map to another external method external2 which takes Map <String,String> as a parameter.

  • Convert Map String, Object   to    Map Object, Object

    is there any way to convert a map of type Map<String, Object> to a map of type Map<Object, Object>? I tried casting it did not work

    You can also take the long way around:
        Map<Object, Object> map = (Map<Object, Object>)buildMapObject(
          new String[] { "1", "2", "3" },
          new Object[] { new Integer(1), new Integer(100), new Integer(1000) });
      public Object buildMapObject(String[] s, Object[] o) {
        Map<String, Object> map = new HashMap<String, Object>();
    // Populate map from arguments
        return map;
      }Though why you'd want to do that is beyond me.

  • String object to Date object

    Hi,
    I have date as string object "22/04/2008". I want convert this string object to Date object as specified format (dd/MM/yyyy) only.
    Please do the need full.
    Thanks in Advance

    kishoreyakkali wrote:
    Hi,
    I tried as follows
    SimpleDateFormat strOutDt = new SimpleDateFormat("dd/MM/yyyy");
    Date dateObj=strOutDt.parse(strTmp);
    System.out.println("dateObj::::" + dateObj);
    Output : Mon Apr 21 00:00:00 IST 2008 A date object is always a wrapper around a millisecond value. It does not contain any formatting information, so you should never print a Date object. You should always convert it to a String using SimpleDateFormat before you print.
    Kaj

  • 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

Maybe you are looking for

  • Report for Approver's name in Org. Structure

    Dear Experts. Is there any standard way out to get a report where we can find the approver's name with the employee name. I want a report where i can find all the employee name with his approvers name, which is assigned in org.structure( reports line

  • Disappointed with Mountain Lion Please Help?

    Ever since i installed OS X Mountain Lion onto my Macbook White (Late 2011) my macbook has been running extremely slow at times my computer freezes and all apps become unresponsive, and i also have an 8GB ram installed, i have also installed the upda

  • Qosmio F30-117 freezes

    Hi! I bought a Qosmio F30-117 a little while ago and it has now started to freeze. I get to the desktop alright, then it just completely freezes and I have to take the mains lead and battery off to restart it, then it usually loads up fine. Anyone el

  • WHAT ARE SUBEVENTS OF DIFFERENT EVENTS IN REPORTS ?

    WHAT ARE SUBEVENTS OF DIFFERENT EVENTS IN REPORTS ? BEST REGARDS, RYAN

  • List: Budget / Actual / Commitments Report Breakup

    Dear All, Report Writer: Library: 6O2 Report  6OBU-001. Report: 6O2-6OBU-001. In the report List: Budget / Actual / Commitments Report Breakup, We need to breakup the Actual Amount into period wise. I assume the tables COEP, BPJA, COOI have the detai