Java 中的不可变字符串 - 替换方法有效吗?

Immutable Strings in Java - replace method works?

我知道 String 是不可变的。但是,出于这个原因,我不明白为什么下面的代码有效(来自 Oracle 的代码示例)。我指的是行 "path = path.replace(sep, '/');" 有人可以帮忙解释一下吗?

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;
   }

}

path = path.replace(sep, '/'); 创建一个新的 String 实例并将其分配给 path 变量。 path 引用的原始 String 未更改,因为如您所知,字符串是不可变的。

如果您调用 path.replace(sep, '/') 而不将结果分配给 pathpath 将继续引用原始 String

字符串本身没有被修改。然而,处理程序 path 然后指向一个新的字符串,它是 path 的先前值并完成了一些替换。

String 实例总是不可变

简单示例:

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
}