1

I understand that String is immutable. However, for this reason, I don't understand why the following code works (a code sample from Oracle). I refer to the line "path = path.replace(sep, '/');" Can someone please help explain?

import oracle.xml.parser.v2.*;

import java.net.*;
import java.io.*;
import org.w3c.dom.*;
import java.util.*;

public class XSDSample 
{
   public static void main(String[] args) throws Exception 
   {
      if (args.length != 1)
      {
         System.out.println("Usage: java XSDSample <filename>");
         return;
      }
      process (args[0]);
   }

   public static void process (String xmlURI) throws Exception 
   {

      DOMParser dp  = new DOMParser();
      URL       url = createURL (xmlURI);

      // Set Schema Validation to true
      dp.setValidationMode(XMLParser.SCHEMA_VALIDATION);
      dp.setPreserveWhitespace (true);

      dp.setErrorStream (System.out);

      try 
      {
         System.out.println("Parsing "+xmlURI);
         dp.parse (url);
         System.out.println("The input file <"+xmlURI+"> parsed without 
errors");
      } 
      catch (XMLParseException pe) 
      {
         System.out.println("Parser Exception: " + pe.getMessage());
      }
      catch (Exception e) 
      { 
         System.out.println("NonParserException: " + e.getMessage()); 
      }

  }

   // Helper method to create a URL from a file name
   static URL createURL(String fileName)
   {
      URL url = null;
      try
      {
         url = new URL(fileName);
      }
      catch (MalformedURLException ex)
      {
         File f = new File(fileName);
         try
         {
            String path = f.getAbsolutePath();
            // This is a bunch of weird code that is required to
            // make a valid URL on the Windows platform, due
            // to inconsistencies in what getAbsolutePath returns.
            String fs = System.getProperty("file.separator");
            if (fs.length() == 1)
            {
               char sep = fs.charAt(0);
               if (sep != '/')
                  path = path.replace(sep, '/');
               if (path.charAt(0) != '/')
                  path = '/' + path;
            }
            path = "file://" + path;
            url = new URL(path);
         }
         catch (MalformedURLException e)
         {
            System.out.println("Cannot create url for: " + fileName);
            System.exit(0);
         }
      }
      return url;
   }

}

3 Answers 3

4

path = path.replace(sep, '/'); creates a new String instance and assigns it to the path variable. The original String that was referred by path is unchanged, since, as you know, Strings are immutable.

If you would call path.replace(sep, '/') without assigning the result to path, path would continue to refer to the original String.

Sign up to request clarification or add additional context in comments.

Comments

0

The String itself is not modified. The handler path however then points to a new String which is the previous value of path with some replacement done.

Comments

0

String instances are always immutable.

Simple example :

public static void main(String[] args) throws IOException {
    String s = "abc";
    String replacedString = s.replace("a", "x"); // returns a "new" string after replacing.
    System.out.println(s == replacedString); // false
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.