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.

Similar Messages

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

  • Doubt in String class

    What is the exact difference between
    String s=new String("xxxxxxx");
    String s="xxxxxxx"; ?
    Please let me know
    rgds
    Mohan S

    Read the Java Language Specs people.
    If I do this:
    String a = "A";
    String b = "A";How many "A"'s are in memory?
    The answer: 1.
    Doing this:
    String a = new String("A");First thing that happens is that "A" will be put in memory. Then a reference to "A" will be created (new String()), then your creating a reference (String a) and assigning your new String to it.
    The new String() creates a new object referencing the same string in memory.
    Hope this clarifies.
    It's explained better in JLS
    3.10.5 String Literals
    4.3.3 The Class String
    And the VM Spec
    2.3 Literals
    String literals and, more generally, strings that are the values of constant expressions are "interned" so as to share unique instances, using the method String.intern.

  • [svn:osmf:] 11239: Updated DRM MediaError codes to work with the the Framework strings class.

    Revision: 11239
    Author:   [email protected]
    Date:     2009-10-28 13:03:06 -0700 (Wed, 28 Oct 2009)
    Log Message:
    Updated DRM MediaError codes to work with the the Framework strings class.  DRM errors spit directly from the VideoElement.
    Modified Paths:
        osmf/trunk/framework/MediaFramework/org/osmf/events/MediaErrorCodes.as
        osmf/trunk/framework/MediaFramework/org/osmf/utils/MediaFrameworkStrings.as
        osmf/trunk/framework/MediaFramework/org/osmf/video/VideoElement.as

    check the server log;
    /app/oracle/product/fwm11g/user_projects/domains/fwm_domain/servers/AdminServer/logs/AdminServer.log
    you can launch the console and see if it is running; http://<server>:<port>/console

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

  • Doubt about string.intern()

    Hello
    I have a doubt about string.intern() method.
    The document says
    When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the String.equals(Object) method, then the string from the pool is returned.
    So what is the point of using this intern() method with == or != operators if it aleady calling to equals method internally?
    eg:
    if (studentObject.getName().intern() == "Student Name") {}cannot be better than
    if (studentObject.getName().equals("Student Name")) {}Can someone please explain?

    Easy dude.
    >
    Why do you need to optimize it?>
    Because i want to.
    I would avoid the whole stupid 100 line if-else by doing a Map of type->object and then just clone() the object. But maybe that might not be suitable or "fast enough" for you.I cannot do above because object have it's own behaviors varying at run time
    eg - class One has setOne method and class hundred has setHundred method
    . Even if i use a map and clone it again i have to use above comparison for setting those behaviours.
    Explain your actual problem you're trying to solve, with actual cases. What are these "one" and "Hundred" classes really? Or is your project so top secret that you can't tell us?It is not secret but big. And I need to make the question understandable. If I post the whole code no one will looking at it.
    Now you asking so please have a look.
    still I have cleaned up many.
    My initial question was how to bit speed up the comparison? And can't i use intern() Because here if I got plenty of rectangles(it is the last) performace sucks.
    for (CObject aObject : objList) {
                if (aObject.getType().equals(SConstant.TEMPLATE)) { /* process Template */
                    Template tObj = (Template) aObject;
                    org.apache.velocity.Template template = VelocityTemplateManager.getInstance().getObjectTemplateFromFile(retemplateProperties.getProperty("PAGE"));
                    VelocityContext context = new VelocityContext();
                    StringWriter writer = new StringWriter();
                    context.put(retemplateProperties.getProperty("BAND_OBJECT"), dtmBand);
                    tObj.setTags(writer.toString());
                } else if (aObject.getType().equals(SConstant.LINE)
                        && !isInBandandBandAutoAdjust(aObject)) {
                    Line object = (Line) aObject;
                    org.apache.velocity.Template template = VelocityTemplateManager.getInstance().getObjectTemplateFromFile(retemplateProperties.getProperty("LINE"));
                    VelocityContext context = new VelocityContext();
                    StringWriter writer = new StringWriter();
                    updateContextWithCheckShifting(context, object);
                    context.put(retemplateProperties.getProperty("LINE_OBJECT"), object);
                    template.merge(context, writer);
                    object.setTags(writer.toString());
                } else if (aObject.getType().equals(SConstant.IMAGE) /* process Image */
                        && !isInBandandBandAutoAdjust(aObject)) {
                    REImage imageObject = (REImage) aObject;
                    org.apache.velocity.Template template = VelocityTemplateManager.getInstance().getObjectTemplateFromFile(retemplateProperties.getProperty("IMAGE"));
                    VelocityContext context = new VelocityContext();
                    updateContextWithCheckShifting(context, imageObject);
                    context.put(retemplateProperties.getProperty("IMAGE_OBJECT"), imageObject);
                    mageObject.setTags(writer.toString());
                   else if (aObject.getType().equals(SConstant.RECTANGLE) /* process Rectangle */
                        && !isInBandandBandAutoAdjust(aObject)) {
                    Rectangle rectangleObject = (Rectangle) aObject;
                    org.apache.velocity.Template template = VelocityTemplateManager.getInstance().getObjectTemplateFromFile(retemplateProperties.getProperty("RECTANGLE"));
                    VelocityContext context = new VelocityContext();
                    StringWriter writer = new StringWriter();
                    updateContextWithCheckShifting(context, rectangleObject);
                    context.put(retemplateProperties.getProperty("RECTANGLE_OBJECT"), rectangleObject);
                    template.merge(context, writer);
                    rectangleObject.setTags(writer.toString());
                }And masijade
    Thank you very much for the better explanation.

  • How to find out what are the functions supported by string class

    Hi,
    Can any one let me know how to find what are all the functions supported by the string class in standard(STL) library on solaris.
    Regards,
    Vignesh

    1. Any C++ textbook that covers the Standard Library will tell you about the standard string class. A good tutorial and reference for the entire Standard Library is "The C++ Standard Library" by Nicolai Josuttis, published by Addison Wesley.
    2. WIth Sun C++, the command
    man -s3C++ basic_string
    provides documentation for the default libCstd version of the Standard Library.
    3. You could look at the <string> header itself. I don't recommend that approach.

  • Memory leak in string class

    We have developed our application in Solaris 10 environment. While running Purify on that it shows leak in the string class. This leak is incremental and so process size keeps in increasing. If we replace string with char array, the leaks disappears and process size also becomes stable.
    Following is the snapshot of the memory leak stack reported by Purify:
    MLK: 4505 bytes leaked in 85 blocks
    * This memory was allocated from:
    malloc [rtlib.o]
    operator new(unsigned) [libCrun.so.1]
    void*operator new(unsigned) [rtlib.o]
    __rwstd::__string_ref<char,std::char_traits<char>,std::allocator<char> >*std::basic_string<char,std::char_traits<char>,std::allocator<char> >::__getRep(unsigned,unsigned) [libCstd.so.1]
    char*std::basic_string<char,std::char_traits<char>,std::allocator<char> >::replace(unsigned,unsigned,const char*,unsigned,unsigned,unsigned) [libCstd.so.1]
    std::basic_string<char,std::char_traits<char>,std::allocator<char> >&std::basic_string<char,std::char_traits<char>,std::allocator<char> >::operator=(const char*) [libCstd.so.1]
    Has anyone faced this problem earlier or is there any patch available for this?

    Over time, we have found and fixed memory leaks in the C++ runtime libraries.
    Get the latest patches for the compiler you are using. (You didn't say which one.) You can find all patches here:
    [http://developers.sun.com/sunstudio/downloads/patches/index.jsp]
    Also get the latest Solaris patch for the C++ runtime libraries, listed on the same web page.
    If that doesn't fix the problem, please file a bug report at
    [http://bugs.sun.com]
    with a test case that can be compiled and run to demonstrate the problem.

  • Problem with loading classes!!!

    I am loading classes using
    // Open File
    InputStream jarFile = new BufferedInputStream(new FileInputStream(
    pluginPath));
    // Get Manifest and properties
    Attributes attrs = new JarInputStream(jarFile).getManifest().
    getMainAttributes();
    jarFile.close();
    // Read Main Class
    String mainClass = attrs.getValue("Protocol-Class");
    // Load all classes from jar file without giving classpath
    URL url = new URL("jar:file:" + pluginPath + "!/");
    JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
    URL[] urls = new URL[] {
    url};
    ClassLoader classLoader = new URLClassLoader(urls);
    // Create new instance of protocol
    Protocol protocol = (Protocol) classLoader.loadClass(mainClass).
    newInstance();
    I am loading classes one by one say a order A, B, C. In my case class c extends class A. So I am loading class A first and later B and finally C. But I am getting exceptions when loading class C that Class A is unknown.The following exception is thrown
    java.lang.NoClassDefFoundError: com/a/A at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:537)
    Please give me a solution to make it run.

    You create a new class loader for each class. The class loaders are independent, and so the class hierarchies they load are independent. Class A loader by classLoaderOne doesn't see class B loader by classLoaderTwo - they are loaded into their own sandboxes.
    Either load everything with one class loader or create the class loaders in a hierarchy. To create a hierarchy use the class loader constructor that takes a parent class loader as a parameter. One class loader may be easier because then you don't need to worry about loading order.

  • Getting problem with DOMImplementation classes method getFeature() method

    hi
    getting problem with DOMImplementation classes method getFeature() method
    Error is cannot find symbol getFeature()
    code snippet is like...
    private void saveXml(Document document, String path) throws IOException {
    DOMImplementation implementation = document.getImplementation();
    DOMImplementationLS implementationLS = (DOMImplementationLS) (implementation.getFeature("LS", "3.0"));
    LSSerializer serializer = implementationLS.createLSSerializer();
    LSOutput output = implementationLS.createLSOutput();
    FileOutputStream stream = new FileOutputStream(path);
    output.setByteStream(stream);
    serializer.write(document, output);
    stream.close();
    problem with getFeature() method

    You are probably using an implementation of DOM which does not implement DOM level-3.

  • EXTENDING the string class

    ok, i know extending the string class is illegal because it's final, but i want to make an advanced string class that basically "extends" the string class and i've seen online this can be done through wrapper classes and/or composition, but i'm lost
    here is my sample code that is coming up with numerous compile time errors due to the fact that when i declare a new AdvString object, it doesn't inherit the basic string features (note: Add is a method that can add a character to a specified location in a string)
    class AdvString
         private String s;
         public AdvString(String s)
              this.s = s;
         public void Add(int pos, char ch)
              int this_len = (this.length()) + 1;
              int i;
              for(i=0;i<(this_len);i++)
                   if(pos == i)
                        this = this + ch;
                   else if(pos < i)
                        this = this + this.charAt(i-1);
                   else
                        this = this + this.charAt(i);
         public static void main(String[] args)
              AdvString s1;
              s1 = new AdvString("hello");
              char c = 'x';
              int i = 3;
              s1.Add(i,c);
              //s2 = Add(s1,i,c);
              //String s2_reversed = Reverse(s2);     
              System.out.println("s1 is: " + s1);
    any tips?

    see REString at,
    http://www.geocities.com/rmlchan/mt.html
    you will have to replicate all the String methods you are interested in, and just forward it to the String instance stored in REString or the like. it is like a conduit class and just passes most processing to the 'real' string. maybe a facade pattern.

  • How to read a xml file with StringReader class

    Hi,
    I need to read a XML document with StringReade class. My aplication receives an absolute path but this doesn't work:
    StringReader oStringReader =
    new StringReader(c:\java\libros.xml);
    However it works with:
    StringReader oStringReader =
    new StringReader("<?xml version="1.0" e......");
    ie, with the whole document as a String, but I need to do it as the frist way.
    Thanks

    Hi,
    I need to read a XML document with StringReade class.
    My aplication receives an absolute path but this
    doesn't work:
    StringReader oStringReader =
    new StringReader(c:\java\libros.xml);
    However it works with:
    StringReader oStringReader =
    new StringReader("<?xml version="1.0" e......");
    ie, with the whole document as a String, but I need
    to do it as the frist way.
    Thankstake a look at this link:
    http://java.sun.com/webservices/jaxp/dist/1.1/docs/tutorial/sax/2a_echo.html

  • Java Switch Statement with Strings

    Apparently you cant make a switch statement with strings in java. What is the most efficient way to rewrite this code to make it function similar to a swtich statement with strings?
    switch (type){
                   case "pounds":
                        type = "weight";
                        break;
                   case "ounces":
                        type = "weight";
                        break;
                   case "grams":
                        type = "weight";
                        break;
                   case "fluid ounces":
                        type = "liquid";
                        break;
                   case "liters":
                        type = "liquid";
                        break;
                   case "gallons":
                        type = "liquid";
                        break;
                   case "cups":
                        type = "liquid";
                        break;
                   case "teaspoons":
                        type = "liquid";
                        break;
                   case "tablespoons":
                        type = "liquid";
                        break;
              }

    I'd create a Map somewhere with entries "liquid", "weight", etc.
    public class Converter {
        private static Map<String, List<String>> unitMap = new HashMap<String, List<String>>();
        private static String[] LIQUID_UNITS = { "pints", "gallons", "quarts", "millilitres" };
        private static String[] WEIGHT_UNITS = { "pounds", "ounces", "grams" };
        static {
            List<String> liquidUnits = new ArrayList<String>();
            for (int i = 0; i < LIQUID_UNITS.length; i++) liquidUnits.add(LIQUID_UNITS));
    unitMap.put("liquid", liquidUnits);
    ... // other unit types here
    public String findUnitType(String unit) {
    for (String unitType : unitMap.keySet()) {
    List<String> unitList = unitMap.get(unitType);
    if (unitList.contains(unit))
    return unitType;
    return null;
    It might not be more "efficient", but it's certainly quite readable, and supports adding new units quite easily. And it's a lot shorter than the series of if/else-ifs that you would have to do otherwise. You'll probably want to include a distinction between imperial/metric units, but maybe you don't need it.
    Brian

  • I think this is a Bug of String class

    I think this is a Bug of String class, do you agree with me ?
    String s = "1234........"; // when "1234........". length() > 65535, there will be wrong, but
    char[] c = new char[88888];...
    String s = new String(c);even if c.length >65535�Cevery thing is ok.
    so I think is a bug. Somebody give me a answer, thanks

    below is the two Constructors Of String
        public String(String original) {
         int size = original.count;
         char[] originalValue = original.value;
         char[] v;
           if (originalValue.length > size) {
             // The array representing the String is bigger than the new
             // String itself.  Perhaps this constructor is being called
             // in order to trim the baggage, so make a copy of the array.
             v = new char[size];
             System.arraycopy(originalValue, original.offset, v, 0, size);
         } else {
             // The array representing the String is the same
             // size as the String, so no point in making a copy.
             v = originalValue;
         this.offset = 0;
         this.count = size;
         this.value = v;
        }=====================
        public String(char value[]) {
         int size = value.length;
         char[] v = new char[size];
         System.arraycopy(value, 0, v, 0, size);
         this.offset = 0;
         this.count = size;
         this.value = v;
        }I don't know where has the problem.

  • How to implement the String class "split()" method (JDK1.4) in JDK 1.3

    is it possible , with some code, to implement the split() method of the String class......which is added in JDK1.4 ..... in JDK1.3
    would be helpful if anyone could suggest some code for this...

    Here it is
    public static String[] split(String source, char separ){
    answer=new Vector();
    int position=-1, newPosition;
    while ((newPosition=source.indexOf(separ,position+1))>=0){
    answer.add(source.subString(position+1,newPosition));
    position=newPosition;
    } //while
    answer.add(source.subString(position+1,source.length-1);
    return (String[])(answer.toArray());
    } //split

Maybe you are looking for