"String str=new String("My String")" v.s. "String str="My String";

-- what's the difference bet String str="My String"; to this
String str=new String("My String");

Its a subtle one. Its also been asked a hundred times before :-)
When a java class is compiled it "interns" all the Strings it can find.
Anywhere that you use that string, gets replaced with a reference to that string.
So the first gets a reference to the interned String.
The second creates a new String, using the interned String as an argument - results in reserving new memory.
Take this code:
String str1 = "My String";
String str2 = "My String";
String str3=  new String("My String");In effect the compiler turns it into something like this:
String internedString = "My String"
String str1 = internedString;
String str2 = internedString;
String str3 = new String(internedString);So initially, it only stores "MyString" once, and all your String variables point at that same memory space. As Strings are immutable in java (the contents never change) this is safe to do. str3 creates a NEW String, which reserves new memory, and copies the contents of internedString into it.
So
str1 == str2 (they point to the same bit of memory)
str1 != str3 (str3 created a new String, so is in new memory)
str1.equals(str3) (the contents of the strings are the same)
Hope this helps,
evnafets

Similar Messages

  • Difference between str="Hai"; and str = new String("Hai");

    HI,
    String szFirst = "Hello World":
    String szSecond = new String("Hello World");What is the difference between the two types of string initialization?

    RajivGuna wrote:
    HI,
    String szFirst = "Hello World":
    String szSecond = new String("Hello World");What is the difference between the two types of string initialization?What do you think the difference is?

  • Creating String frm new String(charBuffer.array()) Vs charBuffer.toString()

    Whats the difference in creating String from CharBuffer by using array and by using toString() ?
    When ever i have some UTF-8 chars in my file (""someFile"), String created from new String( charBuffer.array()) appends some extra null/junk charaters at the very end of the file.
    How ever when i try charBuffer.toString() its working fine.
    For simple ASCII i.e ISO-*** charset both methods are working fine.
    Please see below code for reproducing. Here "someFile" is any text file with some UTF-8 characters.
    public char[] getCharArray()
    throws IOException
    Charset charset = Charset.forName("UTF-8");
    CharsetDecoder decoder = charset.newDecoder();
    FileInputStream fis = new FileInputStream("someFile");
    FileChannel channel = fis.getChannel();
    int size = (int) channel.size();
    MappedByteBuffer mbb = channel.map(FileChannel.MapMode.READ_ONLY, 0 , size);
    CharBuffer cb = decoder.decode(mbb);
    channel.close();
    fis.close();
    return cb.array();
    public String getAsString()
    throws IOException
    Charset charset = Charset.forName("UTF-8");
    CharsetDecoder decoder = charset.newDecoder();
    FileInputStream fis = new FileInputStream("someFile");
    FileChannel channel = fis.getChannel();
    int size = (int) channel.size();
    MappedByteBuffer mbb = channel.map(FileChannel.MapMode.READ_ONLY, 0 , size);
    CharBuffer cb = decoder.decode(mbb);
    channel.close();
    fis.close();
    return cb.toString();
    String fromToString = getAsString();
    String fromCharArray = new String(getCharArray());

    Whats the difference in creating String from CharBuffer by using array and by using toString() ?array() returns the entire backing array regardless of offset and position. toString() takes those into account.
    When ever i have some UTF-8 chars in my file (""someFile"), String created from new String( charBuffer.array()) appends some extra null/junk charaters at the very end of the file.More probably you haven't filled the array.
    How ever when i try charBuffer.toString() its working fine.So there you go.

  • Import CSV Is Incorrect - Misinterprets RETURN within Strings as New Row

    When importing a CSV file into Numbers 3.0.1, it produces bad results, because it interprets RETURNs within strings as new rows, when it should ignore them.
    How can this be worked around?

    If the CSV is properly formatted and the strings that have the carriage return(s) are enclosed in quotes, it works fine  (at least it does for me). If the strings do not have quotes around them, the returns should be interpreted as a new row.
    The workaround would be to somehow get quotes around those strings before importing into Numbers. I'm not sure how to do that except manually in a text editor or for the app that created the CSV to format it correctly.

  • Splitting a string on new lines...

    If I want to split string on whitespaces, I do:
    StringTokenizer st = new StringTokenizer(a, " ");If I want to split a string on new lines, (I think the ascii values are "13", "10") how can I do it?
    Thanks a lot!

    does "\n" represents both chr(13) and chr(10) ?No, it does not.
    KajI solved with "\r\n"Did you read the other replies? They are correct when they say that you shouldn't use StringTokenizer.
    Kaj

  • String name = new String {...} what is this?

    Hi,
    Java beginner, moving from C++:
    protected String[] name = new String[] {
              Integer.toString(1),
    Integer.toString(2)
         };what does a bracket mean after new String[] ?
    Thanks,

    Thanks, I didn't know what to search for in
    google...
    Is it generalizable to any object?Why don't you try it with various objects and primitives? Then you'll find out for yourself.
    You can also read the JLS
    http://java.sun.com/docs/books/jls/second_edition/html/j.title.doc.html
    or
    http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html
    Or any of a number of books or tutorials. This is basic stuff. It should be covered.
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java.

  • Another Tutorial Error? List String [] lsa = new List ? [10];

    Quote from Gilad Bracha's tutorial:List<String>[] lsa = new List<?>[10]; // unchecked warning - this is unsafeAt least with jdk 1.5.0_01 it does not compile at all, but gives compile error "incompatioble types. found java.,util.List<?>[]. reuired java.util.List<java.lang.String>".
    This one however gives an unchecked warning:List<String>[] lsb = (List<String>[]) new List<?>[10];

    An error in the tutorial. Thanks for noticing. I've told Gilad.

  • Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string co

    Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs. at Error$/throwError() at flash.net::URLVariables/decode() at flash.net::URLVariables() at flash.net::URLLoader/onComplete() _________________________________________________________________________________________ _____________________ stop(); var DepartVars:URLVariables = new URLVariables(); var DepartURL:URLRequest = new URLRequest("scripts/www.mywebsite.com/depart.php"); DepartURL.method = URLRequestMethod.POST; DepartURL.data = DepartVars; var DepartLoader:URLLoader = new URLLoader; DepartLoader.dataFormat = URLLoaderDataFormat.VARIABLES; DepartLoader.addEventListener(Event.COMPLETE, completeDepart); depart_btn.addEventListener(MouseEvent.CLICK, DepartUser); // Function to run when the Depart button is pressed function DepartUser (event:MouseEvent):void{             // Ready the variables here for sending to PHP           DepartVars.post_code = "Depart";         // Send the data to the php file           DepartLoader.load(DepartURL);         welcome_txt.text = "Processing request...Bon Voyage"; } // Close DepartUser function /////////////////////////////////////// // Function for when the PHP file talks back to flash function completedepart(event:Event):void{     if (event.target.data.replyMsg == "success") {             var refreshPage:URLRequest = new URLRequest("javascript:NewWindow=window.location.reload(); NewWindow.focus(); void(0);");             navigateToURL(refreshPage, "_self");         } // Close completeDepart function ////////////////////////////// // Code for the View res Button var viewRes:URLRequest = new URLRequest("view_res.php"); viewRES_btn.addEventListener(MouseEvent.CLICK, viewResClick); function viewResClick(event:MouseEvent):void {     navigateToURL(viewRes, "_self"); } ///////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// // Code for the Edit Res profile Button var editRes:URLRequest = new URLRequest("edit_res.php"); editRES_btn.addEventListener(MouseEvent.CLICK, editResClick); function editResClick(event:MouseEvent):void {     navigateToURL(editRes, "_self"); } }

    this should be in the as3 forum.  but you need to return name/value pairs from your php file.

  • Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containin

    Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs. at Error$/throwError() at flash.net::URLVariables/decode() at flash.net::URLVariables() at flash.net::URLLoader/onComplete() _________________________________________________________________________________________ ____________ stop(); var DepartVars:URLVariables = new URLVariables(); var DepartURL:URLRequest = new URLRequest("scripts/www.mywebsite.com/depart.php"); DepartURL.method = URLRequestMethod.POST; DepartURL.data = DepartVars; var DepartLoader:URLLoader = new URLLoader; DepartLoader.dataFormat = URLLoaderDataFormat.VARIABLES; DepartLoader.addEventListener(Event.COMPLETE, completeDepart); depart_btn.addEventListener(MouseEvent.CLICK, DepartUser); // Function to run when the Depart button is pressed function DepartUser (event:MouseEvent):void{             // Ready the variables here for sending to PHP           DepartVars.post_code = "Depart";         // Send the data to the php file           DepartLoader.load(DepartURL);         welcome_txt.text = "Processing request...Bon Voyage"; } // Close DepartUser function /////////////////////////////////////// // Function for when the PHP file talks back to flash function completedepart(event:Event):void{     if (event.target.data.replyMsg == "success") {             var refreshPage:URLRequest = new URLRequest("javascript:NewWindow=window.location.reload(); NewWindow.focus(); void(0);");             navigateToURL(refreshPage, "_self");         } // Close completeDepart function ////////////////////////////// // Code for the View res Button var viewRes:URLRequest = new URLRequest("view_res.php"); viewRES_btn.addEventListener(MouseEvent.CLICK, viewResClick); function viewResClick(event:MouseEvent):void {     navigateToURL(viewRes, "_self"); } ///////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// // Code for the Edit Res profile Button var editRes:URLRequest = new URLRequest("edit_res.php"); editRES_btn.addEventListener(MouseEvent.CLICK, editResClick); function editResClick(event:MouseEvent):void {     navigateToURL(editRes, "_self"); } }

    I have a similar problem
    whey I use .txt my code works, but when I change to .dat external file, it get error 1067
    my code:
    import flash.display.Sprite;
    import flash.events.*;
    import flash.net.URLLoader;
    import flash.net.URLLoaderDataFormat;
    import flash.net.URLRequest;
    var loader: URLLoader = new URLLoader();
    loader.dataFormat = URLLoaderDataFormat.VARIABLES;
    loader.addEventListener(Event.COMPLETE, loading);
    loader.load(new URLRequest("rssnews.dat"));
    function loading(e: Event): void {
              news_1.text = trace(e.target.data.titulo);
              news_2.text = trace(e.target.data.texto);

  • Need to send text string to new row in expandable table

    I have a table that is a summary of other choices made throughout the document.  For specific check boxes in the form, there is a defined phrase that needs to be sent to a new row in the summary table.
    The general idea is that for checkbox:
    form1.sfMain.sfContent.tableC2.Row1.cbC2b6
    if (this.rawValue == "1") {
    this.resolveNode('form1.sfApp6.tableApp6A._Row1').addInstance(1);
    this.resolveNode("form1.sfApp6.tableApp6A.Row1[*].ddApp6A1c").rawValue = "Blue bottle";
    This needs to be something I can specify for each applicable checkbox (each will have a different text string), but I don't know what the final count is going to be (depends on choices made by the user) so I can't delete rows in the table and start over every time.  It needs to be additive.
    Any suggestions?
    Message was edited by: cyndilynnrose

    For anyone needing the same thing, I found exactly what I needed:
    http://www.truetechtroubleshooting.com/2012/02/advanced-expanding-tables-and-script.html
    The hardest part of getting it working was figuring out how many parent levels I needed to add since I have a heavily layered form.

  • Host string and new users

    Hi, I've just installed DevSuiteHome1, OraDb10g_home1, and Oracle Developer Suite - DevSuiteHome1 and will be creating forms for an assignment. I've managed to log in to SQL*Plus with: "/ as sysdba" and successfully created a new user with a password and created a table "student", what privileges should I give this user (currently DBA) to allow them to access simple forms?.
    When I log in to SQL*Plus I get in without entering a "Host String", do I need this? What is a Host String?
    Also, though I don't need the database name just yet, I'd like to know how to find it!
    Thanks for reading, I'm grateful for any help.
    Will.

    The more formal way of reading that is
    sqlplus user/password@service-information
    where service-information is somehow translated into a combination of 3 pieces of information
    1) how to find the host or computer where the database resides
    2) which port the listener is monitoring
    3) which service (commonly mistaken as database) to which the listener should provide a connection
    (A database, when 'running', has a default service that matches the database name.)
    If you are logged on the the same machine as the database, you can bypass the network and the listener by setting the ORACLE_SID and implying the 3 pieces of information.
    If you are remote, there are several ways of getting the 3 pieces. The most common is to use the TNSNAMES.ORA to translate the service-information alias into the needed information. The translation could also be stored in an LDAP database Using InstantClient you have added variations, such as 'supply the host name and assume the listener is monitoring port 1521 for one and only one database', or supplying the whole translation manually.

  • Long string in new tab url

    Firefox always used to open a new tab with a simple url, which if I clicked in it would automatically become selected, so it was easy to overtype an different url.
    Lately each new tab is opening with along string like this: http://www.google.com.au/firefox?gfe_rd=ctrl&ei=jlGcUpi5JquN8Qfz5YGYDQ&gws_rd=cr
    And when I click in it the cursor is placed at the end of the string, so I have to select the whole string with Ctrl and A or backspace to get rid of it. What changed and how do I get my short url with auto click / select back
    Also, I have opened in safe mode without any addons, didn't make any difference.
    Thanks

    Choose the ''final'' URL you want and paste that in as your newtab URL. If the site redirects your newtab URL in any way (whether to a secure connection, for example, or otherwise), then Firefox's selection code will be defeated and the cursor will appear at the end of the URL.

  • MM Change Value String from new Movement Type. (URGENT)

    Dear friends ,
    We have copied moviment type 501 and we need to change the value string to this movement.
    So after copy to 933 and creates value string ZA01 copied from WA01 , which tables should I change to value string of movment type use it ?
    We are using ECC 5.0.
    Best regards,
    Alessandro

    Could you please tell us what you want to achive with this setting though iam 99% sure that what you told in this thread cannot be done. WE always try to create the new movement types using exisiting movement types. So , transaction key/ Value string are copied over . So, i highly doubt if you can even change those fields as they are defined by SAP and used as part of their code and highly recommends not to attempt to play with them.
    If you want, you can check in OMWN and OMJJ to see that they are uneditable..
    please let us know what you want to achive with this so that we can try to help you.
    Please revert back to us if you have achived in creating a copy of WA01 and also let us know how you did it . Iam just curios.
    AH

  • Split string into new column

    Hi All,
    Hoping you are able to help.
    I have a table of approx 16 items that I need to split,
    EG:
    CUSTOMER ACCEPTANCE - HAS BEEN DECLINED - DO NOT APPLY TO ACCOUNT
    CUSTOMER ACCEPTANCE -  HAS BEEN ACCEPTED - APPLY TO ACCOUNT
    CUSTOMER ACCEPTANCE - PENDING DECLINE - ESCALATION REQUIRED - RAISED IN PORTAL
    ESCALATION - RAISED - PENDING
    ESCALATION - NOT RAISED - STILL TO BE PROCESSED
    I need to Keep the first two sections, eg CUSTOMER ACCEPTANCE - HAS BEEN DECLINED in one column, and split off the remaining, eg DO NOT APPLY TO ACCOUNT into a new TEMP table to insert as a column into an existing table.
    With little SQL experience, I am having difficulties as they are all of different lengths / criteria etc. Some have 3 hyphens whilst others have 4+
    Is anyone able to help point me in the right direction with this request? I will be greatly appreciated.
    Kind Regards,
    BTMMP

    If you're trying to do this all in a SQL query or stored procedure, then you'll probably get better results on the SQL Server forums. However, if you're working with a PowerShell or VBScript that's doing the work, you're in the right place.
    Here's one example of how you could do what you're describing.  By the way, what do you want to do with the string "CUSTOMER ACCEPTANCE - PENDING DECLINE - ESCALATION REQUIRED - RAISED IN PORTAL"?  Should that be split into "CUSTOMER ACCEPTANCE
    - PENDING DECLINE" and "ESCALATION REQUIRED - RAISED IN PORTAL", or "CUSTOMER ACCEPTANCE - PENDING DECLINE - ESCALATION REQUIRED" and "RAISED IN PORTAL"?
    (In other words, should the script only split off whatever's after the final hyphen, or should it grab the first two pieces of text and split off everything else?)
    Here's an example in PowerShell which assumes that you want to separate out all text after the final hyphen in a string.  It uses a regular expression, though you could accomplish the same thing with Split, Join and Trim operations, if you prefer.
    $string = 'CUSTOMER ACCEPTANCE - HAS BEEN ACCEPTED - APPLY TO ACCOUNT'
    if ($string -match '(.*?)\s*-\s*([^-]*)$')
    $split = $matches[1], $matches[2]
    else
    $split = $string, ''
    Write-Host "Original String: $string"
    Write-Host "First Text : $($split[0])"
    Write-Host "Second Text : $($split[1])"

  • Regular expression- insert into a string phrase "new" into correct position

    I have sample data in table T below, and i have sample output how i want the query to output over that data.
    with T as
    select 'CREATE OR REPLACE PACKAGE BODY "YYY"."PACKAGEONE" IS' s from dual union all
    select 'Create or REPLACE PACKAGE BODY "ZZZ"."PACKAGETWO" IS' s from dual
    select REGEXP_REPLACE(T.s, '^.PACKAGE BODY$','(\1)_new',1,1,'i') as s from T;
    Expected output:
    CREATE OR REPLACE PACKAGE BODY "YYY"."PACKAGEONE_new" IS
    Create OR REPLACE PACKAGE BODY "ZZZ"."PACKAGETWO_new" IS
    */All data has following pattern:
    CREATE OR REPLACE PACKAGE BODY "[owner]"."[name]" ISWhere [owner] can be any string. In sample data we have for example values XXX and YYY there.
    And [name] can be any string. In sample data we have for example values PACKAGEONE and PACKAGETWO there.
    Other parts of the string is fixed and stays as you see.
    As shown in expected output query should replace substring "[owner]"."[name]" to "[owner]"."[name]_new"
    How can i write such query?
    I think i somehow should in regular expression count the positions of double quotes to achieve the expected result, but i don't know how.

    Thx, but your solution doesn't work, it doesn't put phrase "new" into string. I use Oracle 10g.
    with T as
    select 'CREATE OR REPLACE PACKAGE BODY "YYY"."PACKAGEONE" IS...' s from dual union all
    select '...Create or REPLACE PACKAGE BODY "ZZZ"."PACKAGETWO" ..."a"."b" procedure a IS..' s from dual
    select
    RegExp_Replace(s,'(" IS$)','_new\1') as new
    from t;
    CREATE OR REPLACE PACKAGE BODY "YYY"."PACKAGEONE" IS...
    ...Create or REPLACE PACKAGE BODY "ZZZ"."PACKAGETWO" ..."a"."b" procedure a IS..
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for

  • Role of a ABAPer in workflow

    I am very new to workflow concept. Please can anyone explain me ABAPer role in creating or customizing workflow. My doubt is ..whether ABAPer will create jobs, positions, task or Basis people? At what stages there will be interaction with the functio

  • Display xls file in iView

    Friends, I want to display the xls file in iView. Tell me whether its possible or not? If yes, than how? If someone has done this than pls. tell me the procedure to do that. Thanks. Hitesh

  • Serial number no longer valid after new HD installed

    I have a macbook that originally came with version 10.5 and I had Final Cut Studio 2 running fine on it. About a month ago it shut down and I was told it was a hard drive failure and the hard drive needed to be replaced. I had it sent in and replaced

  • Idvd 16:9 issue

    Hi All: Okay, I've been shooting in HD 16:9 and using the Sony's HDV DV down conversion to import into FCP HD in SD 16:9. I've exported as Quicktime movie in both NTSC 48 format and NTSC 48 anamorphic. Once in idvd, I choose the 16:9 format and when

  • CS5 Code & Design View Problems?

    In earlier versins of Dreamweaver whenever I as in the deisgn view and I clicked around different pieces of text the cursor would jump to that text section in code view....Now it doesn't seem to work at all? Not sure why it is stuck in code view??