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.

Similar Messages

  • Parse  a XML that is inside  a String Object???

    Hi,
    Will I be able to parse a XML that is stored as a String object rather than using a .XML file.Or is there any other way I would be able to access a XML that comes as a parameter to a method call??
    ~~~~~~~~~~~~~~~~~~~~~
    Java Code:
    public void notify(org.oasisOpen.docs.wsn.x2004.x06.wsnWSBaseNotification12Draft01.NotifyDocument notifyDocument){
    //notifyDocument is a XML Response
              System.out.println("I am from notify" );
              System.out.println(notifyDocument.toString() );
              String notifyString = notifyDocument.toString();
              String s2="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
              String s3=s2+' '+notifyString;//Want to parse this XML
              System.out.println("******************notifyString"+notifyString);
              System.out.println("******************s2"+s2);
              System.out.println("******************notifyString+S2"+s3);
              //Parse the String S3 which contains a well formed XML(I Checked it)
    try{
              DocumentBuilderFactory dbf =    DocumentBuilderFactory.newInstance();
              DocumentBuilder db = dbf.newDocumentBuilder();
              Document document = db.parse(s3);
    System.out.println("************** After Parsing **********");
            NodeList count = document.getElementsByTagName("wsrf:NewValue");
              int number= count.getLength();
              System.out.println("**********"+number);
              Element f=(Element)count.item(0);
            //NodeList count1= f.getChildNodes();
            NodeList comment=f.getElementsByTagName("safe:Comment");
            int num=comment.getLength();
            System.out.println("******** Len 2********"+num);
            Element f1=(Element)comment.item(0);
              Node n=f1.getFirstChild();
              if(n != null)
              System.out.println("***********8HEllo**********8");
              String s = n.getNodeValue();
              System.out.println("***********"+ s);
              catch(Exception e){
                   System.out.println("*****Exception**********"+e);
       }~~~~~~~~~~~~~~~~~~~~~~~~~`
    Result::
    *****Exception**********java.net.MalformedURLException: no protocol <?xml versi
    on="1.0" encoding="UTF-8"?> <wsn:Notify xmlns:wsn="http://docs.oasis-open.org/ws
    n/2004/06/wsn-WS-BaseNotification-1.2-draft-01.xsd" xmlns:soapenv="http://schema
    s.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns
    :xsi="http://www.w3.org/2001/XMLSchema-instance">
    <wsn:NotificationMessage>
    <wsn:Topic Dialect="http://docs.oasis-open.org/wsn/2004/06/TopicExpression/S
    imple" xmlns:safe="http://ws.apache.org/resource/serena/safe">safe:Comment</wsn:
    Topic>
    <wsn:ProducerReference>
    <add:Address xmlns:add="http://schemas.xmlsoap.org/ws/2003/03/addressing">
    http://10.236.23.86:8080/pubscribe/services/serenasafe</add:Address>
    <add:ReferenceProperties xmlns:add="http://schemas.xmlsoap.org/ws/2003/03/
    addressing">
    <safe:ResourceIdentifier xmlns:safe="http://ws.apache.org/resource/seren
    a/safe">ALF1</safe:ResourceIdentifier>
    </add:ReferenceProperties>
    <add:PortType xmlns:safe="http://ws.apache.org/resource/serena/safe" xmlns
    :add="http://schemas.xmlsoap.org/ws/2003/03/addressing">safe:MySerenaSafePortTyp
    e</add:PortType>
    <add:ServiceName PortName="serenasafe" xmlns:add="http://schemas.xmlsoap.o
    rg/ws/2003/03/addressing"/>
    </wsn:ProducerReference>
    <wsn:Message>
    <wsrf:ResourcePropertyValueChangeNotification xmlns:wsrf="http://docs.oasi
    s-open.org/wsrf/2004/06/wsrf-WS-ResourceProperties-1.2-draft-01.xsd">
    <wsrf:OldValue>
    <safe:Comment xmlns:safe="http://ws.apache.org/resource/serena/safe">c
    omment</safe:Comment>
    </wsrf:OldValue>
    <wsrf:NewValue>
    <safe:Comment xmlns:safe="http://ws.apache.org/resource/serena/safe">Q
    uick test!</safe:Comment>
    </wsrf:NewValue>
    </wsrf:ResourcePropertyValueChangeNotification>
    </wsn:Message>
    </wsn:NotificationMessage>
    </wsn:Notify>

    Submitting a string is the equivalent of telling the document builder to fetch the XML from a given URI. If you already have the string in memory:
    DocumentBuilder db = null;  // initialize in a spiffy way
    Document document = db.parse(new StreamSource(new ByteArrayInputStream(xml.getBytes()));- Saish

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

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

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

Maybe you are looking for

  • View next received email when I click back into a folder

    Hello Does anyone know how to view the next new email without having to actually click into it? I have rules sent to place emails in folders when I receive a new emails. I used to be able to click that folder and it would highlight the most recent em

  • Reader XI doesn't save changes to any document !!!

    I have a problem with adobe reader XI version 11.0.0.7 which started very lately in which I try changing settings at ctrl+k (Preferences) then just as I close the program and reopen it everything returns as it was and my document returns to page 1 wi

  • Macbook receipt

    Hi there thanks in advance. I used to have a Macbook that I upgraded to 4gb Ram for music purposes - I run pro tools on it. My macbook was stolen in a break in on Friday! Contacted insurance and they are quite rightly asking for a receipt but as it's

  • Consolidation  Unit change from Group A to group B

    When I drag consolidation unit from group A to Group in CX1X and then I run CXCd and error message popped stated  below; Entry cannot be posted :B/s and I/S balance of  1.7million. I think it might be due to moving from one group to another group. pl

  • WRT310N wireless/lan ports

    hi community i bought a wrt310n yesterday and experiencing a strange behaviour. i did set up a dyndns at my parents house listening at port 6666. when i use my notebook with wireless i can access the page without problems. the desktop, which is conne