Why String class is defined as immutable?

Why String class is defined as immutable? what can be the reason behind it?

Do try this at home. :)
public class Main {
    public static void main(String... args) {
        System.out.println("Greetings.");
        System.out.println("Goodbye.");
    static {
        // translates into Japanese. NOT a good idea!
        try {
            final Field field = String.class.getDeclaredField("value");
            field.setAccessible(true);
            char[] chars = new char[8];
            "Sayonara".getChars(0,8,chars,0);
            field.set("Goodbye.", chars);
            chars = new char[10];
            "Konichi-wa".getChars(0,10,chars,0);
            field.set("Greetings.", chars);
        } catch (Exception e) {
            throw new AssertionError(e);
}

Similar Messages

  • Why String class was declared as final.

    Why String class was declared as final.
    Thanks
    Mohan

    http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=d92720bd3ed4dffffffff95e59403ecf4db1:YfiG?bug_id=4095367

  • Doubt with String class

    Please tell me why String class objects are immutable. Why it was designed like that?

    Read Java tutorials.Thanks for your reply. But tutorial says thatString
    objects are immutable but they dont say why
    they
    made
    as immutable.Welcome swathi.reply #4 is the best answer Ithink.
    But please look at my reply #8Please look at reply#2 in the other thread.But reply #2 was mine. I dont understand what you say? Please help me.

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

  • Did the Java Writers Get a Little Happy with Memory Use in String class?

    I mean that question half jokingly.
    Taking a look at the String class code, I saw the following (below).
    Why is there an int for offset and an int for count?
    String is immutable, why not just return value.length for the count?
    And what is the offset for?
    Thanks!
    public final class String
        implements java.io.Serializable, Comparable<String>, CharSequence
        /** The value is used for character storage. */
        private final char value[];
        /** The offset is the first index of the storage that is used. */
        private final int offset;
        /** The count is the number of characters in the String. */
        private final int count;
        /** Cache the hash code for the string */
        private int hash; // Default to 0PS: a second look kinda verifies it too.
    in the constructor ,count is even defined as value.length.
        public String(char value[]) {
         int size = value.length;
         this.offset = 0;
         this.count = size;
         this.value = Arrays.copyOf(value, size);
        }

    You don't get the choice. The arrays are shared
    whenever you do substring.Yea, thats my point. I think most Strings are unique.
    Id be very surprised if even 2% of all String use was
    a result of a substring.The wrapper classes use it for parsing.
    File uses it for getName and getParent.
    String uses it for trim.
    Class uses it for resolving names.
    Regex uses it.
    etc. ...
    Now, I don't know what percentage of usage all that amounts to, but it IS heavily used.
    So your desire to gain the 2 bytes back would cost enough byte every time substring is used that it might end up costing far more than the 8 bytes you save.

  • Problems with String[] Class Object

    Hi guys,
    I'm writing a web server who should invoke a method of a class when asked by a client.
    My problem is that if the method that should be invoked has a String[] parameter the web server is unable to invoke it and throws a java.lang.IllegalArgumentException: argument type mismatch.
    Useful pieces of code to understand are the following:
    //create the Class[] to pass as parameter to the getMethod method
    Class[] paramType = {String[].class};
    //find the class "className" and create a new instance
    Class c = Class.forName(className);
    Object obj = c.newInstance();
    //the getMethod should find in the class c the method called nameMeth
    // having paramType (i.e. String[]) as parameter type...
    Method theMethod = c.getMethod(nameMeth, paramType);
    //here's the problematic call!!
    theMethod.invoke(obj, params);I've noted that System.out.println(theMethod); prints the signature of the method with the parameter type java.lang.String[].
    System.out.println(paramType[0]); instead prints [Ljava.lang.String;
    I know that [L means that it is an array, so why do you think that I'm having an argument type mismatch?
    Thank you                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    I had no problems making that work.import java.lang.reflect.Method;
    public final class StringArray {
        public static final String CLASSNAME = "StringArray";
        public static final String METHODNAME = "myMethod";
        public static final String[] sa = { "a", "b"};
        // automatic no-args constructor
        public final void myMethod(String[] sa) {
            for(int i=0;i<sa.length;++i) {
                System.out.println(sa);
    public static final void main(String[] arg) throws Exception {
    //create the Class[] to pass as parameter to the getMethod method
    Object[] params = { sa };
    Class[] paramType = {sa.getClass()};
    //find the class "className" and create a new instance
    Class c = Class.forName(CLASSNAME);
    Object obj = c.newInstance();
    //the getMethod should find in the class c the method called nameMeth
    // having paramType (i.e. String[]) as parameter type...
    Method theMethod = c.getMethod(METHODNAME, paramType);
    //here's the problematic call!!
    theMethod.invoke(obj, params);

  • Is the instance fields have private accessibility in String class?

    Is the instance fields have private accessibility in an immutable class, such as the String class?
    also Could any one answer the following question,
    (This is the question I got in written exam for job recruitment)
    "Invoking a method can represent a significant amount of overhead in a program; as such, some compilers will perform an optimization called "method inlining." This optimization will remove a method call by copying the code inside the method into the calling method."
    Referring to the text above, which one of these statements is true?
    Choice 1 The performance benefits should be balanced against the increased chance of a RuntimeException.
    Choice 2 It allows the use of getter and setter methods to execute nearly as fast as direct access to member variables.
    Choice 3 This optimization will only occur if the relevant methods are declared volatile.
    Choice 4 The developer of inlined methods must copy and paste the code that is to be inlined into another method.
    Choice 5 It prevents code from executing in a way that follows object-oriented encapsulation.

    Sarwan_Gres wrote:
    Is the instance fields have private accessibility in an immutable class, such as the String class?Usually, but not always.
    "Invoking a method can represent a significant amount of overhead in a program; as such, some compilers will perform an optimization called "method inlining." This optimization will remove a method call by copying the code inside the method into the calling method."The java compiler does not inline methods so this is not relevant to Java. (The JVM does inline methods) The java compiler does inline constants known at compile time but it is a feature causes more trouble than good IMHO.

  • What does the trim() method of the String class do in special cases?

    Looking here ( String (Java Platform SE 7 ) ), I understand that the trim() method of the String class "returns a copy of the string, with leading and trailing whitespace omitted", but I don't understand what the last special case involving Unicode characters is exactly.
    Looking here ( List of Unicode characters - Wikipedia, the free encyclopedia ), I see that U+0020 is a space character, and I also see the characters that follow the space character (such as the exclamation mark character).
    So, I decided to write a small code sample to try and replicate the behaviour that I quoted (from the API documentation of the trim method) in the multi-line comment of this same code sample. Here is the code sample.:
    public class TrimTester {
        public static void main(String[] args) {
             * "Otherwise, let k be the index of the first character in the string whose code
             * is greater than '\u0020', and let m be the index of the last character in the
             * string whose code is greater than '\u0020'. A new String object is created,
             * representing the substring of this string that begins with the character at
             * index k and ends with the character at index m-that is, the result of
             * this.substring(k, m+1)."
            String str = "aa!Hello$bb";
            System.out.println(str.trim());
    However, what is printed is "aa!Hello$bb" (without the quotes) instead of "!Hello$" (without the quotes).
    Any input to help me better understand what is going on would be greatly appreciated!

    That's not what I was thinking; I was thinking about the special case where the are characters in the String whose Unicode codes are greater than \u0020.
    In other words, I was trying to trigger what the following quote talks about.:
    Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index of the last character in the string whose code is greater than '\u0020'. A new String object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m+1).
    Basically, shouldn't the String returned be the String that is returned by the String class' substring(3,9+1) method (because the '!' and '$' characters have a Unicode code greater than \u0020)?
    It seems to not be the case, but why?

  • Why arrays length is defined to be a field not a method in Java?

    Why arrays length is defined to be a field not a method in Java?

    TRANSLATE result USING R.
    This statement replaces all characters in field result according to the substitution rule stored in field string R .  R contains pairs of letters, where the first letter of each pair is replaced by the second letter.
    in your case TRANSLATE result USING '#'.
    menas '#' and  ' ' space are 2 pair of characters.. and # is replaced by ' ' (space).
    for better understanding..
    Example:
    DATA: T(10) VALUE 'AbCdEfGhIj',
    STRING LIKE T,
    RULE(20) VALUE 'AxbXCydYEzfZ'.
    STRING = T.
    TRANSLATE STRING USING RULE.
    WRITE / STRING.
    Output:
    xXyYzZGhIj
    Hope this helps..

  • Statements like 'List String .class' cause error.

    Consider the following simple code:
        Class<List<String>> cl;
        cl=List<String>.class;The first line is valid but the second one causes the "illegal start of expression" error.
    That's rather strange: the type
    Class<List<String>>is valid itself, but variables of that type cannot be assigned via the ".class" expression.
    Is this a bug or I am missing something?
    Thanks.

    Java generics aren't C++ templates; they don't cause new classes to be created based on parameter type.
    What this means is that for types...
    List<String> stringList = new ArrayList<String>();
    List<Number> numberList = new ArrayList<Number>();...the class of those lists is, in both cases, java.util.ArrayList...
    string.getClass().equals(ArrayList.class);
    numberList.getClass().equals(ArrayList.class);Neither class ArrayList<String> nor class ArrayList<Number> exist, because such generics information is wiped out at runtime. That's why an expression like...
    ArrayList<Number>.class...is illegal.

  • Stop escaped characters from resolving within String class.

    Hello,
    Is it possible to stop escaped characters from resolving within the String class?
    For example, I define a character array,
    char[] c = {'0','\\','n'}
    and I want to create a String based on this exact sequence (0\n). However, when I call the String constructor String(char[]), it resolves the \n sequence into the newline character, creating a String of length 2 not 3.
    I'm not very familiar with the innards of the Java compiler (does "xyz" translate to char[]{'x','y','z'}?), so maybe this is something very basic.
    Does anyone know if there is a flag that can be set somehow before I create a String instance (it appears that no String constructor supports this kind flag)?
    Or perhaps is there a method in the standard Java release that escapes all escape characters in a character array...? I'm curious if there is a simpler way (like a flag), because the method approach seems superfluous.
    Thanks,
    Brien

    What do you mean?char[] c = {'0', '\\', 'n'};
    String s = new String(c);
    System.out.println(s);does give the string 0\n...
    And by the way, it's not the String class that transforms \n to the linefeed character, it is the compiler..

  • How to use string class?

    Hi, experts:
    Have you run HelloStrings sample in "Thinking in C++" book? The source code is following. But when I compile, it throws error:"string in not defined". How to write correct makefile? Thanks! /Denise
    //: C02:HelloStrings.cpp
    // The basics of the Standard C++ string class
    #include <string>
    #include <iostream>
    using namespace std;
    int main() {
    string s1, s2; // Empty strings
    string s3 = "Hello, World."; // Initialized
    string s4("I am"); // Also initialized
    s2 = "Today"; // Assigning to a string
    s1 = s3 + " " + s4; // Combining strings
    s1 += " 8 "; // Appending to a string
    cout << s1 + s2 + "!" << endl;
    } ///:~

    The most likely cause is that the "using namespace std;" line is missing from the file you are compiling, or commented out.
    Using C++ 5.6 and the exact file I listed earlier, I get this result:
    % CC -V hello.cc
    CC: Sun C++ 5.6 2004/06/02
    /set/mercury/dist/fcs.2/sparc-S2/opt/SUNWspro/prod/bin/c++filt: Sun C++ 5.6 2004/06/02
    ccfe: Sun C++ 5.6 2004/06/02
    ld: Software Generation Utilities - Solaris Link Editors: 5.9-1.377
    Copy/paste the hello.cc file I listed above and try compiling it.
    If you still get errors, your compiler was not installed correctly, or the installation has become corrupted.
    If you want to poke around a bit more before re-installing, try this:
    CC -H -c HelloStrings.cc |& grep string
    The -H option lists all the header files that were read. You should see this, assuming your compiler is installed in /opt:
    /opt/SUNWspro/prod/include/CC/Cstd/./string <------- string header
         /opt/SUNWspro/prod/include/CC/std/string.h
              /usr/include/string.h
                   /usr/include/iso/string_iso.h
         /opt/SUNWspro/prod/include/CC/Cstd/rw/string_ref
    If in particular you do not see /opt/SUNWspro/prod/include/CC/Cstd/./string, or if the "string" header marked above comes from some other location, something is definitely wrong with the compiler installation.
    If you see the correct string header, run "wc" on that header. You should see this:
    1858 6099 68105 string
    If not, the string header is corrupted.
    To re-install, refer to the Installation Guide that comes with Sun Studio 9. Follow the instructions for uninstalling Sun Studio 9. Then run the product installer, paying close attention to any warnings or error messages. I strongly recommend using the product installer, and not trying to install the product yourself directly from the packages.

  • JDev 10.1.3 / Ant / element classes not defined in parent war

    I tried to build a WAR file with Ant in JDeveloper 10.1.3 (Preview). The source of the build.xml:
    <?xml version="1.0" encoding="windows-1252" ?>
    <project name="MyApp" default="war" basedir=".">
    <target name="init">
    <tstamp/>
    </target>
    <!-- ... -->
    <target name="war" depends="init">
    <war destfile="../deploy/myApp.war" encoding="Cp1252" webxml="../public_html/WEB-INF/web.xml">
    <classes dir="../classes"/>
    <lib dir="../public_html/WEB-INF/lib"/>
    <webinf dir="../public_html/WEB-INF"/>
    <metainf dir="public_html/META-INF"/>
    </war>
    </target>
    </project>
    I got 3 error messages, which do not correspond to the Ant documentation:
    - element classes not defined in parent war
    - element lib not defined in parent war
    - element webinf not defined in parent war
    That's why I'm not able to build a war file for deployment.
    Is there any chance to bypass/correct the errors?

    This bug has been fixed for the Production Release. There is no workaround in the Preview Release. However, these errors should only appear while editing the Ant buildfile. They should not prevent you from running the buildfile.
    -Matt Hawkins
    Oracle JDeveloper

  • Why String  Dont have reverse method

    hi guys am new to java i have small doubt could u pls clear that one.
    In java StringBuffer class have the reverse method but String class dont have a reverse method.
    Why?
    Whats the reason?

    It's not really worth it. You can't have methods for everything or you get language bloat.

  • Why String need to be final?

    Why String need to be final?

    Final or immutable? Final so that you are not tempted to extend String. You are supposed to use String. Immutable for the salient reasons previously posted.
    - Saish

Maybe you are looking for

  • Different Batch Classification at storage location level

    Dear guru , I have tested that i can insert different values of batch classification for the same material and the same batch number but in different plants. In MSC1N/MSC2N transaction the system allow a insertion at storage location level. Itu2019s

  • Creation of Purchase group, purchase area & purchase area determination

    How do i creat the Purchase Area & its determination for a 3rd party sales ?? Pls let me know the menu path for the same...

  • Why does it take so long?

    Exporting Files from Final Cut Pro takes Forever. I imported a file that was a quicktime movie, .avi, and after just adding chapter marks, exporting it takes a real long time. I never fully wait it out because it takes too long. Is it because the fil

  • Payment advice form for each payment method

    Hi, We have Check, RTGS and Bank Transfer payment methods in single company code, I have assigned different payment programs in OBVCU for payment methods C,R & T and seperate payment advice form to each payment methods in OBVU, and also I have mainta

  • DMS  object links

    hello ,    about object links ,there is no sap object about QM inspection lot ,i want to create it .    how to create sap object about QM inspection lot ? thanks!