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.

Similar Messages

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

  • 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 about string manipulation

    Hello, I am practicing with Java and trying to learn it, and have a quick question. I am trying to get the count on a string of numbers for after a decimal point. the numbers are generated as the result of a math, so I can't use index, since the location of the decimal changes based on the number imputed. I want to figure this out on my own, but have hit a wall here, i've spent the past few hours trying every string command I can think of, and haven't figured it out yet, anyone mind pointing me in the right direction for which string to use? Thanks in advance for any help you can provide!

    Is this what you want?
    public class Fallen{
      public static void main(String[] args){
        String number = "123.45678";
        String frac = number.substring(number.indexOf('.') + 1);
        System.out.println(frac + " length=" + frac.length());
        frac = number.replaceFirst("^.+\\.", "");
        System.out.println(frac + " length=" + frac.length());
    }

  • Newbie question about default Constructors

    I have this simple class with a constructor:
    ============================================================
    public class ScopeTest {
    public static void main(String[] args) { ScopeTest tst = new ScopeTest(); }
    public ScopeTest(String a) { System.out.println("ScopeTest(String a) : " + a); }
    ============================================================
    This class generates these errors when compiling:
    ScopeTest.java:3: cannot find symbol
    symbol : constructor ScopeTest()
    location: class ScopeTest
    public static void main(String[] args) {ScopeTest tst = new ScopeTest();}
    ^
    All the books and tutorials I read say that the compiler invokes the constructor of the super class (Object in this case)
    if it can't find one with the right signature in the class. Yet if I comment out this class's constructor it compiles and works.
    Can anyone explain???

    so u hv to put a default constructor...
    public class ScopeTest {
    public static void main(String[] args) { ScopeTest tst = new ScopeTest(); }
    public ScopeTest(String a) { System.out.println("ScopeTest(String a) : " + a); }
    public ScopeTest() { System.out.println("Default Constructor"); }
    }

  • Question abotu String.format() functionality

    Hello all,
    I am curious as to whether this functionality exists in the String.format method, or if there is any other class in the current version of Java that would allow for this.
    I want to construct a format string, where if one of the args contains a newline character in it, the same format for that arg will be used on the newline.
    Example:
    String s = String.format("%20s%20s","this line contains\na newline character","so does\nthis one");
    System.out.println(s);
    Actual Output:
    this line contains
    a newline character    so does
    this one
    Wanted Output:
    this line contains         so does
    a newline character      this oneHopefully there is something that exisits in the language that would allow me to do this. If no one can think of any easy way to do this? I have a few ideas, but it would require a whole lot of string manip. than I want to put into it =(
    Anyways, I look forward to your reply. Thanks!

    You want the method to treat the strings as multi-line blocks of text instead of as strings? And put the blocks next to each other instead of the strings? Maybe padding the blocks with spaces? Forget it, that's way too complicated for a quick and dirty formatting method.
    And yes, a whole lot of string manipulation would be going into that.
    Assuming that I understood your requirements correctly. I just went by the picture, I couldn't make any sense out of the words you used to describe it, so I may well be totally wrong.

  • Question about String constant pool

    Is there is any function available to find how many Sring literal in String Constant pool

    Well, there's stuff like BCEL.
    But it may not do what you want.
    Why do you want to find out what's in the constant pool?

  • Quick Question on String Searches

    I'm about to write a small program to find a target string in any file format, then display the target string and the first 200 characters before and 200 characters after the target string to the console. I want to use OOP, using main() for testing purposes only, but I'm not sure of the best way to approach this. Should I use the store() and load() methods from Properties or just use indexOf()? Any thoughts, folks? Thanks.

    If fyou are going to be searching in any file format (including binary files such as Word docs) then you can't really use the indexOf or the Properties class (I am not sure what your intentions were with the Properties class, but using it requires a particular file format).
    Just off the top of my head, I would suggest using a RandomAccessFile and seeking around, reading data into buffers when you find what you want. To me, this isn't exactly a job for OOP, at least at its guts. You can use OOP to come up with a design - perhaps using specific "Searchers" tuned to particular file formats, and then have a driver class that determines, at runtime, which Searcher class to use for a given file. But again, that's just off the top of my head.
    Good Luck
    Lee

  • Easy question about String

    Hi!
    I have a string in a variable. how can I check if the String is composed just by numbers?
    thank you very much!

    Use the following method from Integer API
    parseInt
    public static int parseInt(String s)
                        throws NumberFormatExceptionParses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002d') to indicate a negative value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.If it throws NumberFormatException its alphanumeric else its numeric. You would however have to remove any spaces or commas etc. since they are not mumeric either

  • A question regarding String

    One String problem confused me.
    String s = "aacc";
    Now, i want to insert "bb" between "aa" and "cc", The result would be that s equals "aabbcc". I had thought to implement it by using insert method. but I was surprised that Class String do not support this method. Could anyone give me a simple way that can do this. thanks a lot.

    Use the StringBuffer class instead. The String class is imutable. It will create a new string when modified.
    StringBuffer b = new StringBuffer("aacc");
    b.insert(2, "bb");

  • Noobish question on strings-plz help

    Whats wrong with this code?
    public String name(){
              String str="hi";
              if(str.equals("hi"))
                   return str;
    Why is it saying "This method should return a result of type string"?
    Regards.

    public String name(){
        String str="hi";
        if(str.equals("hi")) {
            return str;
        // if above if statement is false code gets to here
        // where is the return statement?
    }The compiler doesn't give a shit about evaluating the if statement to see that it can only be true. All the compiler looks at is that when the if statement is false there is no return statement.

  • A question about String.hashCode()

    Why the implementation of hashCode() for String class using 31 as a base?

    Why the implementation of hashCode() for String class
    using 31 as a base?I think it's a magic number. It has been found to produce a reasonably even distribution over the int range.

  • A question about string.trim()

    I got a fragment of code as follows:
    String s = "abcd ";
    boolean a = (s.trim()=="abcd");
    boolean b = (s =="abcd ");
    Why a is false, b is true?

    The reason why the below code has true assigned to be is quite easy to explain:
    String s = "abcd";
    String y = "abcd";
    boolean b = (s == y);
    ...The String class has a "Pool" of strings. When you use String literals; the compiler automatically checks if it is in the String pool already and if it exists; a reference to that String is returned; if not a new entry in the pool is added and then you get a reference to that. This is only true for Stirng literals and String created using the intern() method.
    If you compile this code you will see that the strings are not equal:
    public static void main(String args[])
      String s = "abcd";
      String y = args[0];
      boolean b = (s == y);
      System.out.println(b);
    }This is because the "abcd" is in the String pool when your program starts; but because the value "abcd" passed in (is not created in the pool automaticlaly). Therefor they are two different String objects.
    This code block shows that you can add Strings to the pool. The intern() method checks to see if the String is in the pool already and if it is it will return you a reference to it; if not it will create one and then return it.
    public static void main(String args[])
      String s = "abcd ";
      String y = args[0].intern();
      boolean b = (s == y);
      System.out.println(b);
    }- Chris

  • Question about string constant in Hex display format

    how to get a plus of 2 string constant which is display in Hex display like attahced, for example I have string "28" and "5D" in Labview which has been in Hex format, the plus of this 2 string should be "85" in Hex. pls help on this, thanks
    Attachments:
    1.jpg ‏21 KB

    This'll work, too.  I'm afraid of casting types...
    Jm
    Jim
    You're entirely bonkers. But I'll tell you a secret. All the best people are. ~ Alice
    Attachments:
    hex.png ‏2 KB
    hex.vi ‏7 KB

  • A quick question of String

    how to check whether it starts with digitals or not? i remember there is a quick solution but i forget it.
    i checked the books but found no answer. could anybody tell me? Thanks!

    Maybe this will work:
    String s = "1abc";
    try{
    Integer.parseInt(s.substring(0,1));
    catch (NumberFormatException e){
    System.out.println("1st char is not a integer");

Maybe you are looking for

  • Asking for apple ID password constantly & Crashing apps

    iOS 8.2, 6 Plus 64g Since the 8.2 update, I have had issues with apps crashing pretty consistently, including Safari.  Also, I am being prompted to enter my apple ID password about 30 times a day.  It happens at random times, unlocking the phone, sur

  • Printing to windows printer via mac - am i being stupid?

    I really don't get this. I've just bought my 1st mac, a macbook pro, to replace my old windows laptop. I also have a windows pc, with an Epson USB printer attached to it, as well as the windows desktop being connect via ethernet to a netgear wireless

  • Can't drag videos into itunes

    i have movies in mp4 format which is compatible with my ipod but i can't seem to be able to drag those files into my itunes. how can i upload my videos onto my ipod if i can't get them into my itunes?? ): can somebody help me pls?

  • What is the use of OP and CA operator in PDF creation and on which factor transparency is determined?

    What is the use of OP operator in PDF creation and on which factor transparency is determined? q 0 g 0 G 1 w 10 M /GS4 gs /Fm3 Do Q PostScript code for Fm3 q 65.136 431.142 491.727 -307.179 re W n q /GS0 gs 493.7399902 0 0 308.3157654 64.0563507 123.

  • Smooth line drawing in as3

    I am looking for a smoothe line drawing effect as in the pencil tool in Flash. I need to implement the same using as3. Any idea how I can achieve that?