String constructors

I have often seen in java examples and tutorials code like:
void method(String[] message) {
    String s = new String("Msg: " + message);
    ...and I am wondering if the following is equivalent:
void method(String[] message) {
    String s = "Msg: " + message;
    ...Because I have the suspicion that the first syntax first creates a string (to pass as a parameter) and then the String constructor creates and returns another one. Is that true or the compiler/JVM makes sure this double work is not propagated into actual bytecode?
Also, I am confused: what is the use of a constructor for String that takes a String as a parameter? For all the imagination that I can muster I cannot find a trickier way to waste memory, since either the parameter for the constructor is a literal string or a reference to one (and then I think that the constructor is creating an unnecessary duplicate) or the parameter is a result of some operation, like concatenation in the example above, and concatenation I suppose implicitly calls the String constructor, unless it creates strings out of thin air...
I'm learning Java as a Foreign Language (JFL) so please you language purists pardon my clumsiness. Maybe this question was posted, answered and flamed before...

The String constructor that takes a String parameter will always create a new String object. The compiler will never optimize that away. There are very, very few times when this will be useful, so generally it should be avoided.
So, you might wonder why it is even around. Well, one good reason is that a String can have a reference to a character array that is much larger than the content of the String itself. The new String(String) constructor will create a String with a backing array that is only as large as it needs to be. This isn't normally a problem, but if you notice that a lot of application memory is being eaten up by unnecessarily large character arrays, then using this constructor in a few appropriate spots may fix it. However, you should never optimize code until you have profiled your application and determined that the 'problem' you are trying to fix is what is actually causing problems.

Similar Messages

  • Problem with string constructor when using byte array as parameter

    I am creating a string using constructor and passing byte array as parameter.This byte array i am getting from MessageDigest's digest() method,i.e. a hash value.
    The problem is when i iterate through byte array i can able to print all the values in byte array.But when i construct a string from that byte array and printing that string ,that is printing some unknown characters.
    I don't know whether i need to pass charsequence to the constructor and the type of charsequence.Can anybody help me?
    Thanks in advance

    Is there some problem today? I'm getting this sort of thing all over.
    I already told you and so did Kayaman. Don't. String is not a holder for binary data. You have to Base-64 encode it. If you don't you cannot reconstruct the original binary digest value, so putting it into a database is completely utterly and entirely pointless.
    Is that clear enough?

  • Question on String constructors

    Hi.
    String is not a primitive type, so, like all not primitive types, new string objects must be instantiated calling a constructor, via the operator 'new0.
    However this "rule" is not valid with class String (and maybe with other classes), as it is possible to create new string objects simply using the form String myStr = "myStr";
    Well, I'd like to know how this is possible and which kind of statements I should use in my classes to support this kind of instantiation.
    Thanks!

    However this "rule" is not valid with class String
    (and maybe with other classes), as it is possible to
    create new string objects simply using the form
    String myStr = "myStr";You're not necessarily creating a new String object.
    String s1 = "hello";
    String s2 = "hello";
    System.out..println(s1 == s2); // test for objct identity will return truehttp://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.5
    Well, I'd like to know how this is possible and which kind of
    statements I should use in my classes to support this kind of
    instantiation.If you mean you want that stuff for your own classes: you can't.

  • Why create a String object no need to use constructor?

    If we create a Java String object, we will do:
    String s = "Hello";
    And we won't do:
    String s = new String("Hello");
    In API doc, String() constructor description says "Initializes a newly created String object so that it represents an empty character sequence. Note that use of this constructor is unnecessary since Strings are immutable."
    I am not sure how immutable is related to this??
    Also, I wonder if the compiler will convert
    String s = "Hello" to
    String s = new String("Hello");
    Thanks!

    String s = new String("Hello");
    This is a valid statement too..... But the compiler will not convert String s = "Hello" to String s = new String("Hello") as you suggested. The reason is that java has a sort of a String Bag. Everytime you do a String s = "Hello" it will check the bag and see if such a string already exists. If it does, it merely creates a pointer to it, because strings are immutable, it doesn't need to worry about others modifying that string. If the string doesn't exist then it creates the necessary memory for the string object and adds the reference to the bag.
    However, once you do a String s = new String("Hello") what you are saying to the compiler is, "Hey, don't check the bag just create the String." This is all fine and dandy, except that it increases the memory size of your program unnecessarily.
    V

  • About Strings and Memory

    Let's look at a couple of examples of how a String might be created, and let's further assume that no other String objects exist in the "String constant pool"l:
    String s = "abc"; //   creates one String object and one
                      //   reference variable In this simple case, "abc" will go in the pool and s will refer to it.
       String s = new String("abc"); // creates two objects,
                                  // and one reference variable In this case, because we used the new keyword, Java will create a new String object
    in normal (nonpool) memory, and s will refer to it. In addition, the literal "abc" will
    be placed in the pool.
    My question is this:
    Then why did the sun developers created the 'public String(String str)' constructor even it uses an additional memory?

    Caarmel wrote:
    Let's look at a couple of examples of how a String might be created, and let's further assume that no other String objects exist in the "String constant pool"l:
    String s = "abc"; //   creates one String object and one
    //   reference variable In this simple case, "abc" will go in the pool and s will refer to it.Nope. Executing that line only assigns a reference to an already existing String into the variable. The constant was put into the pool when the class was loaded. So your initial assumption of no Strings in the constant pool is invalid.
       String s = new String("abc"); // creates two objects,
    // and one reference variable Nope. As above, it creates one object. The other already existed.
    Then why did the sun developers created the 'public String(String str)' constructor even it uses an additional memory?First, note that your question really has nothing at all to do with the constant pool. Your question is really "Why does the String(String) constructor exist, given that String is immutable, and given that we can just do s2 = s1?" That question applies even in complete absence of the constant pool.
    I wasn't there when they made the decision, so I can't tell you what their thinking was. I can tell you one case where it's useful, however.
    String s1 = some_very_long_string;
    String s2 = s1.substring(x, x + a_small_number);
    String s3 = new String(s1.substring(x, x + a_small_number);Both the s2 and s3 lines create new String objects. However, in the case of s2, the new object shares the same char array as the original, whereas in the s3 case, a new backing array of just the right size is created. If s1 is very large, AND if the substring we're extracting is very small, AND if the substring needs to live on significantly longer than the original, then without the explicit new String(), even though we only need a few characters and could get away with a very small char array, we end up stuck with a large char array that can't be GCed even when the original String is.
    So in this rather unlikely scenario, we can avoid wasting a bunch of memory that can't be GCed when we only need a small fraction of it.
    Or maybe the constructor came about in early versions, before other aspects of the language making it mostly useless were solidified, and then it was kept for backward compatibility.
    Or maybe they didn't really have a good reason and just figured it made sense to have a copy constructor.
    Or maybe the reasons that make it mostly redundant are implementation details, and they wanted to provide a copy constructor so that as Java evolved, if the implementation changed, the functionality would still be there.
    Or maybe none of the above.

  • Converting ASCII text (byte array ending in null) to a String

    Hi all,
    I am trying to convert a null terminated ascii string stored in a byte array to a java String. When I pass the byte array to the String constructor it
    does not detect/interpret the null as a terminator for the ascii string. Is this something I have to manually program in? ie Check for where the null is and then
    pass that subarray of everything before the null to the String constructor?
    example of problem
    //               A   B  C   D   null   F   (note F is junk in the array, and should be ignored since it is after null)
    byte[] asciiArray = { 65, 66, 67, 68, 0,  70 };
    System.out.println(new String(asciiArray, "UTF-8"));
    //this prints ABCD"sqare icon"F

    Why do you expect the null character to terminate the string? If you come from a C or C++ background, you need to understand that java.lang.String is not just a mere character array. It's a full-fledged Java object that knows its length without having any need for null terminator. So Ascii 0 is just another character for String object. To achieve what you want to do, you have to manually loop through the byte array and stop when you encounter a null character.

  • Print a line after each constructor

    Would one of you java gods tell me how i can print a line after each constructor that tells me that the constructor has been constructed?
    * Employee.java
    * Created on April 28, 2007, 11:58 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    * @author Pete Berardi
    package edu.ctu.peteberardi.phase3db;
    import java.util.Scanner;
    public abstract class Employee extends Object
        protected String EmpName;
        protected String EmpAddress;
        protected String EmpSsn;
        protected String EmpEmployeeID;
        protected double EmpYearlySalary;
        protected double computePay;
        protected String Constructor;
        /** Creates a new instance of Employee */
        public Employee(String name, String address, String ssn,
                String id, double salary, double pay, String cvariable)
          name = EmpName;
          address = EmpAddress;
          ssn = EmpSsn;
          id = EmpEmployeeID;
          salary = EmpYearlySalary;
          pay = computePay;
        public void setEmpName(String name)
            EmpName = name;
        public String getEmpName()
            return EmpName;
        public void setEmpAdress(String address)
            EmpAddress = address;
        public String getEmpAddress()
            return EmpAddress;
        public void setEmpSsn(String ssn)
             EmpSsn = ssn; 
        public String getEmpSsn()
            return EmpSsn;
        public void setEmpID(String id)
            EmpEmployeeID = id;
        public String getEmployeeID()
            return EmpEmployeeID;
        public void setEmpYearlySalary(double salary)
            EmpYearlySalary = salary;
        public double getEmpYearlySalary()
            return EmpYearlySalary;
        public void setcomputePay(double pay)
            computePay = pay;
        public double computePay()
            return computePay;
          public void setContstructor(String cvariable)
             Constructor = cvariable;
        public String Constructor()
            return Constructor;
       public static void main( String args[])
          System.out.print("Constructor has been constructed");
     

    I do not know why you have declared the class as abstract. Abstract class must contain at least one abstract method.
    In your code, there is no abstract method.
    public Employee(String name, String address, String ssn,
                String id, double salary, double pay, String cvariable)
          name = EmpName;
          address = EmpAddress;
          ssn = EmpSsn;
          id = EmpEmployeeID;
          salary = EmpYearlySalary;
          pay = computePay;
          System.out.println("Constructor created");
         }The above code works only when you instantiate the object for the class. If it is abstract class, it will not work.
    Abstract class cannot be instantiated.

  • Conversion from int to String

    How can i convert an int to a String.
    There is no direct String constructor that take only an integer.
    Thanks

    int num = 1;
    String str = "" + num;
    or
    int num = 1;
    String str = Integer.toString(num);

  • String deprecation

    I have a warning when compiling a jdk1.1 file under j2sdk1.4
    the String(byte[],int)has been deprecated and I didn't understand how to change the instruction using string constructors as it is said in the note in the documentation.
    please tell me how.
    thanks

    If you look at the Documentation for String:
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/String.html#constructor_summary
    It says:
    String(byte[] ascii, int hibyte)
    Deprecated. This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do this is via the String constructors that take a charset name or that use the platform's default charset.
    And here is that constructor
    String(byte[] bytes, String charsetName)
    Constructs a new String by decoding the specified array of bytes using the specified charset.
    You can start with this "ISO-8859-1" as charsetName, then look here is you want something different.
    http://java.sun.com/j2se/1.3/docs/api/java/lang/package-summary.html#charenc

  • GetResourceAsStream(String name)  - how to use it?

    I tryed to read from a "res.txt" file some text data. This is a test app:
    public class ResTest extends MIDlet{
         public void startApp(){
              try{
                   InputStream is=new String().getClass().getResourceAsStream("/res.txt");
                   DataInputStream dis=new DataInputStream(is);
                   System.out.println(dis.readUTF());
              }catch(Exception e){System.out.println(e);}     
         public void destroyApp(boolean bool){}
         public void pauseApp(){}
    All I got was EOFException.
    So I tryed a different way to read data usinf a loop:
                   char ch;
                   while((ch=dis.readChar())!=-1){
                   System.out.print(ch);
    And than I got:
    ??????java.io.EOFException
    The data in "res.txt" file (I put this file to "res" direction of my project, I use KToolbar):
    Jajko
    Banan

    I'm guessing that the res.txt file is a basic ASCII file, right?
    If this is the case then that is your problem. When you used readUTF() the implementation was expecting a string in UTF format and not basic ASCII so it didn't know how to read it.
    And when you used the readChar() method you have to remember that Java is a Unicode language so chars are 2 bytes. If the string has an odd number of characters then the last character won't have the 2 bytes and you will get an EOFException. And even if the number of chars was even, you wouldn't get the exception but the text wouldn't be what you expect since it was reading text encoded in single byte ASCII format.
    You have two choices:
    a) Encode the res.txt file appropiately, either save as as a UTF-8 file and use readUTF(), or a Unicode file and use the readChar() method.
    b) Use readByte() instead of readChar() and save the bytes in an array, then pass that array to a string constructor.
    shmoove

  • Converting bytes to strings

    iam receiving data from other device iam storing hole data in byte buffer as
      byte[]  data= new byte[1024];for every read i get 16 bytes of data ..
    when iam veiwing i am getting some bytes in -ve like -127 and some or +ve 126,115. i want to convert  this data to string then how i can do this .                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Use one of the String constructors that takes a byte or byte array argument.

  • Oracle.jbo.Key Constructor giving Exception

    Getting the following exception when trying to pass a URL parameter called "Leadid" with value=1129 (....?LeadId=1129) in a ADF-Faces/ADF BC scenario :
    oracle.jbo.InvalidParamException: JBO-25006: Invalid parameter value 1129 for String passed to method Constructor:Key. Explanation: {3}
         at oracle.jbo.Key.parseBytes(Key.java:482)
         at oracle.jbo.Key.<init>(Key.java:181)
    This is happening when navigating to a Faces page using the above URL parameter. do I need to do anythign special when passing URL params and later use that with "setCurrentRowWithKey" operation?

    Shailesh,
    You are right! I misunderstood the other thread issue.
    I will modify my source code, using the type factory (oracle.jbo.domain.TypeFactory) as you suggested.
    Thanks
    Gleber
    Shailesh,
    You should use the constructor Key(Object[] values) to create a key when you know the Structure of the key.
    So in your case it'd be
    keyvals = new Key(new Object[] {idClassificacaoTipo});I'm using a generic ViewObject. I do not know it's Primary Key datatype.You can call ViewObject.getKeyAttributeDefs() to get the attribute definitions for each of the attributes that make up the key. AttributeDef.getJavaType() gives you the type of the object you need as part of the key.
    So you could do something like:
    oracle.jbo.domain.TypeFactory.getInstance(AttributeDefInstance.getJavaType(), myKeyPartVariable)
    to get the right java object to pass to the Object[] in the Key (Object[]) constructor.
    The undocumented constructor you're using accepts string values that represent serialized Key string obtained from Key.toStringFormat() method and is used in web-app scenarios. I'm using the undocumented as suggested in this thread:
    Re: resize rollback
    I'm using the constructor Key(String, AttributeDef[]) in many parts of my source code with no problems, and it's behavior is the same as using Key(Object[]).
    What is happening?The String constructor usage is limited to key strings obtained from toStringFormat method. Any other usage will lead to potential problem like you're seeing. And that's the assumption in other thread as well.

  • How do I convert byte[] to String?

    I've got a class that pulls information from a GPS receiver on a COM port. That works fine, but the information I'm getting from the port is in the following format:
    Reading serial port...
    44,44,52,46,50,44,77,44,45,51,52,46,50,44,77,44,44,48,48,48,48,42,120,30,-104,-128,96,120,96,0,-26,126,-98,-104,-98,0,30,-122,6,30,-122,6,120,-122,-32,-122,-32,-122,-32,-122,-32,-122,-32,-122,-32,-122,-32,-122,-32,-122,-32,-122,-32,120,-122,-32,-122,-32,-122,-32,-122,-104,-122,6,120,6,-98,30,-104,-128,96,120,96,0,-26,24,-26,-26,-104,30,30,-122,24,120,-32,120,30,102,120,-26,120,-26,-4,48,50,52,44,86,44,52,48,53,54,46,49,50,50,49,44,78,44,48,55,51,53,52,38,54,70,70,-58,118,-115,25,25,89,70,6,102,6,-122,-58,-58,-58,-26,83,102,-122,
    -61,-31,
    36,71,80,71,71,65,44,50,49,52,53,53,54,46,48,50,52,44,52,48,53,54,46,49,50,50,49,44,78,44,48,55,51,53,52,46,50,51,52,52,44,87,44,48,44,48,48,44,44,52,46,50,44,77,44,45,51,52,46,50,44,77,44,44,48,48,48,48,42,52,66,13,10,36,71,80,71,83,
    65,So it's pretty obvious that it's spitting out ASCII values, so I changed the code a bit to print out the corresponding letters instead:
    Reading serial port...
    $GPGGA,214724.031,4056.1221,N,07354.2344,W,0,00,,4.2,M,-34.2,M,,0000*48
    $GPGSA,A,1,,,,,,,,,,,,,,,*1E
    $GPGSV,3,1,11,31,70,286,,14,57,089,,32,51,293,,30,44,061,*7D
    $GPGSV,3,2,11,05,24,046,,22,23,167,,20,20,315,,16,15,194,*70
    $GPGSV,3,3,11,12,12,039,,29,09,103,,11,00,279,*4F
    $GPRMC,214724.031,V,4056.1221,N,07354.2344,W,,,140608,,,N*68
    $GPGGA,214725.031,4056.1221,N,07354.2344,W,0,00,,4.2,M,-34.2,M,,0000*49
    $GPGSA,A,1,,,,,,,,,,,,,,,*1ENow those are the NMEA sentences that the GPS receiver spits out, that's exactly what I need. Only problem is I'm printing them out using the following code:
          byte[] buffer = new byte[4096];
          InputStream theInput = thePort.getInputStream();
          System.out.println("Reading serial port...");
          while (canRead()) // Loop
            int bytesRead = theInput.read(buffer);
            if (bytesRead == -1)
              break;
            for (int z = 0; z < bytesRead; z++)
                 System.out.print(Character.toString((char)buffer[z]));
            }So as you can see, it's simply taking the byte, converting it from ASCII to a symbol or letter, and putting it on the screen. Then it moves onto the next byte. So what I've tried to do is change it again so that it adds each converted letter to a string value, starting a completely new string every time it hits a $ sign, which always starts a NMEA sentence:
          byte[] buffer = new byte[4096];
          InputStream theInput = thePort.getInputStream();
          System.out.println("Reading serial port...");
          while (canRead()) // Loop
            int bytesRead = theInput.read(buffer);
            if (bytesRead == -1)
              break;
            String s = "";
            for (int z = 0; z < bytesRead; z++)
                 if (Character.toString((char)buffer[z]).equalsIgnoreCase("$") && s.length() > 1)
                      System.out.println(s);
                      s = Character.toString((char)buffer[z]);
                 else
                      s = s + Character.toString((char)buffer[z]);
    //             System.out.print(Character.toString((char)buffer[z]));
    s = "";
    }The problem with this is for some reason the sentences aren't whole, there's line breaks inserted into them. So when I'm passing them to the parser, I'm passing incomplete sentences. Here's the output I'm getting now:
    Reading serial port...
    $GPGSA,A,1,,,,,,,,,,,,,,,*1E
    .2,M,-34.2,M,,0000*4D
    $GPGSA,A,1,,,,,,,,,,,,,,,*1E
    ,32,51,293,,30,44,061,*7D
    $GPGSV,3,3,11,12,12,039,,29,09,103,,11,00,279,*4FHow do I get each NMEA sentence into a string so I can send it to a parser? Any ideas?
    Edited by: DeX on Jun 14, 2008 6:02 PM

    Your problem is that you're assuming a newline actually indicates the end of a line.
    Assuming you can't fix the sender (or yell at the maintainer and get him to fix it), take
    advantage of the fact that you know what a valid line starts with and just ignore the newline
    characters.
    Thanks but that gives me the same result. I think my issue is with the multithreading,
    another thread is rolling through and assigning values to the String before the previous
    thread is finished copying the bytes to it. I suggest you take advantage of the StringBuilder class. Also, if you insist on using the
    String(byte[ ]) constructor, you should note that you're assuming a charset, a rather
    dangerous thing to do. Use the String(byte[ ], String) constructor instead and explicitly use US-ASCII.

  • Verify if string is valid ASCII

    I have a string and I want to verify if it contains only valid ASCII, for example, if the string contains characters like the right allow, then it be should reject ! can anyone help? thanks!

    What's the in the db? A series of bytes from a different character set? (One which, when displayed on a terminal (which may or may not understand the character set), displays a right arrow?)
    Perhaps the ultimately correct solution is to use java.io.InputStreamReader, constructing it denoting the correct character set.
    Or, to put data into the database using OutputStreamWriter, again specifying the correct character set.
    Then you catch CharConversionExceptions. That's how you detect bad input.
    Or, do the same kind of thing using String.getBytes and String constructors.

  • Detecting an arbitrary string of bytes at a known offset?

    I need to use the content scanning feature to identify an arbitrary string of bytes. In particular, I need to identify a certain string of 768 bytes (binary stuff, not text), at a known offset within an attachment file of a specific type. I'm sorry I can't provide details such as exactly what attachment type and where within the file the 768 bytes are found, but that information is confidential and I am not at liberty to reveal it here. Expressed in pseudo-code, I need something like this:
    if the attachment type is "xxxxxx/xxxx"
    and bytes N:N+767 of the attachment match the binary string "..."
    then act on this message
    The attachment type is one that requires base64 encoding, and that is frustrating me. I could live with matching on the base64-encoded data by looking for a certain 13 consecutive lines, even though that's not quite as accurate because it does not take the offset into account (the signature is unique enough that this is acceptable). However, it appears that AsyncOS decodes base64 before doing content scanning.
    Given my reading of the AsyncOS documentation, I don't think this is possible, but I'd like to be wrong.
    Thanks,

    No, I understand how to access the bytes one at a time, but I want to access the array of bytes from address 1948 onwards. I actually managed this with a string constructor (since it is a string i'm trying to get at), but there are probably other ways.

Maybe you are looking for

  • How to upgrade adobe catptivate 6.0.1.240 to 6.1 or latest version

    Greetings All, How to upgrade adobe catptivate 6.0.1.240 to 6.1 or latest version. Please advice. Because HTML5 not published properly my videos...Thanks Best Regards, Kumaran Paranthaman.

  • How to fetch indivdual rows from a dynamic query.

    Hi, I wish to fetch the individual rows returned from a dynamic query. if my dynamic query is: dyn_stmt := select col1, col2, col3 from tab1; The query returns multiple rows. Then how to fetch individual rows of this query ? Please explain.

  • I uninstalled Foxrire because it is loading mulitble copies but NOT showing an icon.

    Foxfire is loading multiable copies. If I open Foxfire it will show an icon. When I close Foxfire the icon is not shown. But if I try to un install Foxfire I get a dialog box telling me to close Foxfire. There is nothing to close. When I shut off my

  • Why does it say 'Mshome' in the Network finder?

    Hi I'm running a MacBook and a 12" PowerBook. The MacBook is working fine with regard to networking, but the PowerBook comes up with folders 'Mshome' and 'My Network'. What are they for and how do I get rid of them? Also, I can easily see the Powerbo

  • LSMW -  Standard Batch/Direct Input Method.

    Hi all, I was trying to create the LSMW for MM01 using standard Batch/Direct Input Method. While I selected object as "0020- Material Master"  I am not able to get the Method for Batch Input. Is there any we can create method for batch input or we ha