Why String need to be final?

Why String need to be final?

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

Similar Messages

  • Why String class was declared as final.

    Why String class was declared as final.
    Thanks
    Mohan

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

  • Why to need close the result set and statement

    why to need close the result set and statement

    It's best to explicitly close every ResultSet, Statement, and Connection in the narrowest scope possible.
    These should be closed in a finally block.
    Since each close() method throws SQLException, each one should be in an individual try/catch block to ensure that a failure to close one won't ruin the chances for all the others.
    You can capture this in one nice utility class, like this:
    package db;
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.Map;
    import java.util.LinkedHashMap;
    import java.util.List;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    * Created by IntelliJ IDEA.
    * User: MD87020
    * Date: Feb 16, 2005
    * Time: 8:42:19 PM
    * To change this template use File | Settings | File Templates.
    public class DatabaseUtils
         * Logger for DatabaseUtils
        private static final Log logger = LogFactory.getLog(DatabaseUtils.class);
        /** Private default ctor to prevent subclassing and instantiation */
        private DatabaseUtils() {}
         * Close a connection
         * @param connection to close
        public static void close(Connection connection)
            try
                if ((connection != null) && !connection.isClosed())
                    connection.close();
            catch (SQLException e)
                logger.error("Could not close connection", e);
         * Close a statement
         * @param statement to close
        public static void close(Statement statement)
            try
                if (statement != null)
                    statement.close();
            catch (SQLException e)
                logger.error("Could not close statement", e);
         * Close a result set
         * @param rs to close
        public static void close(ResultSet rs)
            try
                if (rs != null)
                    rs.close();
            catch (SQLException e)
                logger.error("Could not close result set", e);
         * Close both a connection and statement
         * @param connection to close
         * @param statement to close
        public static void close(Connection connection, Statement statement)
            close(statement);
            close(connection);
         * Close a connection, statement, and result set
         * @param connection to close
         * @param statement to close
         * @param rs to close
        public static void close(Connection connection,
                                 Statement statement,
                                 ResultSet rs)
            close(rs);
            close(statement);
            close(connection);
         * Helper method that maps a ResultSet into a map of columns
         * @param rs ResultSet
         * @return map of lists, one per column, with column name as the key
         * @throws SQLException if the connection fails
        public static final Map toMap(ResultSet rs) throws SQLException
            List wantedColumnNames = getColumnNames(rs);
            return toMap(rs, wantedColumnNames);
         * Helper method that maps a ResultSet into a map of column lists
         * @param rs ResultSet
         * @param wantedColumnNames of columns names to include in the result map
         * @return map of lists, one per column, with column name as the key
         * @throws SQLException if the connection fails
        public static final Map toMap(ResultSet rs, List wantedColumnNames)
            throws SQLException
            // Set up the map of columns
            int numWantedColumns    = wantedColumnNames.size();
            Map columns             = new LinkedHashMap(numWantedColumns);
            for (int i = 0; i < numWantedColumns; ++i)
                List columnValues   = new ArrayList();
                columns.put(wantedColumnNames.get(i), columnValues);
            while (rs.next())
                for (int i = 0; i < numWantedColumns; ++i)
                    String columnName   = (String)wantedColumnNames.get(i);
                    Object value        = rs.getObject(columnName);
                    List columnValues   = (List)columns.get(columnName);
                    columnValues.add(value);
                    columns.put(columnName, columnValues);
            return columns;
         * Helper method that converts a ResultSet into a list of maps, one per row
         * @param rs ResultSet
         * @return list of maps, one per row, with column name as the key
         * @throws SQLException if the connection fails
        public static final List toList(ResultSet rs) throws SQLException
            List wantedColumnNames  = getColumnNames(rs);
            return toList(rs, wantedColumnNames);
         * Helper method that maps a ResultSet into a list of maps, one per row
         * @param rs ResultSet
         * @param wantedColumnNames of columns names to include in the result map
         * @return list of maps, one per column row, with column names as keys
         * @throws SQLException if the connection fails
        public static final List toList(ResultSet rs, List wantedColumnNames)
            throws SQLException
            List rows = new ArrayList();
            int numWantedColumns = wantedColumnNames.size();
            while (rs.next())
                Map row = new LinkedHashMap();
                for (int i = 0; i < numWantedColumns; ++i)
                    String columnName   = (String)wantedColumnNames.get(i);
                    Object value = rs.getObject(columnName);
                    row.put(columnName, value);
                rows.add(row);
            return rows;
          * Return all column names as a list of strings
          * @param rs query result set
          * @return list of column name strings
          * @throws SQLException if the query fails
        public static final List getColumnNames(ResultSet rs) throws SQLException
            ResultSetMetaData meta  = rs.getMetaData();
            int numColumns = meta.getColumnCount();
            List columnNames = new ArrayList(numColumns);
            for (int i = 1; i <= numColumns; ++i)
                columnNames.add(meta.getColumnName(i));
            return columnNames;
    }Anybody who lets the GC or timeouts or sheer luck handle their resource recovery for them is a hack and gets what they deserve.
    Do a search on problems with Oracle cursors being exhausted and learn what the root cause is. That should convince you.
    scsi-boy is 100% correct.
    %

  • Why local class merely be final/abstract/package access?

    The scenario is that while declaring a local class as final/abstract/package access only and why this access specifier is using?
    could anyone plz express the reason for that?
    With Regards,
    Stalin.G

    final String efg = "efg";
    testCallback(new Callback()
    public void execute(String str)
    try
    Thread.sleep(3000);
    } catch (InterruptedException e)
    System.err.println(str+efg);
    System.err.println("finished " + System.currentTimeMillis());
    //...Look at the local variable efg, it must be final, or the code does not compile,, Can anybody explain why efg has to be final?*explained by dcminter and Jardium in [an older thread|http://forums.sun.com/thread.jspa?messageID=10694240#10694240]:*
    >
    ...Final variables are copied into inner classes - that's why they have to be declared final; to avoid the developer making an incorrect assumption that the local variable can be modified and have the change reflected in the copy.
    When a local class uses a local variable, it doesn't actually use the variable. Instead, it takes a copy of the value which is contained in the variable at the moment the class is instantiated. It's like passing the variable to a constructor of the class, except that you do not actually declare any such constructor in your code.
    To avoid messy execution flows to be present in a Java method, the Java language authors thought it was better to allow a single value to be present in such a variable throughout all its life. Thus, the variable has to be declared final.

  • Why we need XML?

    hi,
    Why we need XML.?(we have ascii file format is a gentral format, to access all plateform,why not we didn't follow.?)
    like XML:
    <contact>
    <name> java</name>
    <age>25</age>
    </contact>
    flat files:
    contact name:java age:25
    i feel flat file is small and easy .....why we didn't use it.........?

    PS - Jos, how's the weather in your garden today?
    (Rainy and cool here.) Well picture this: both of my parrots are trying to
    sleep in their own hollow
    coconut, slightly disturbed by some silly squeaky
    bird at the other side
    of the barn. The fish in the pond are sort of
    sunbathing between the
    floating leafs, my wife seems to be in a catatonic
    state sleeping all the
    time and then there's me in front of my little laptop
    (protected by a silly
    little green umbrella like thingy, the laptop that is
    ;-)A nice image indeed.
    It's been one wet spring here. It's very cool and overcast, threatening more rain. I'm sitting in my office working away on getting my head around Spring. I've been going through Rob Harrop's "Pro Spring" slowly and carefully, making all the code work and taking little side trips to set it into my head. Rod Johnson's team is doing a great job, in my opinion.
    I still feel that the Spring framework, the web part
    of it, is as some sort
    of a corset, a hindrance. I feel like I'm all
    dressed up but nowere to go
    because Spring or something else I don't know about
    forbids me ... I
    know that I have it wrong alltogether but I can't get
    a grip on it. Not sure what the impediment is, but then I don't understand all the nuances of Spring yet. Maybe their newer web flow stuff might help. It models a UI as a state machine, so you can do more complex flows from page to page. The finite automata underneath will appeal to your inner mathematician. 8)
    btw. it's in
    the lower thirties here (celcius); that makes it in
    the lower nineties (fahrenheit).
    btw, YoGee helped me a lot yesterday.No surprise there. YoGee sure is smart. While I was reading the thread I wished that I had seen it first. You've been so helpful to me so often that I would have enjoyed reducing the trade deficit I have with you. I know that particular problem with Tomcat and JSTL well.
    Yep, I'm working on a large ('Dutch-wise' speaking
    that is) optic fibre
    network. Technically this network works great.
    Managerially speaking
    ahem there's nothing yet: no services, no control
    of services, no
    network checking stuff, no customer (crm) stuff, no
    nothing. Those folks
    want me to do it all. Sounds like a great problem. Could be an engagement to carry you through the summer.
    Yes, that particular part gave me blood behind my
    eyes: I did everyhing
    according to the book and that crap simply refused to
    work. It turned out
    that I was trying to develop something against wrong
    versions of several
    components. In a certain way I'm a believer, i.e.
    when I finally do understand
    what it's all about I "walk this way" when the
    documentation tells me to
    "walk this way". When that turns out not to work at
    all I want my pink
    inflatable axe again (or worse ;-)I like Tomcat, but I think the docs are sketchy. This seems to be a common problem.
    No, I feel reluctant to introduce yet another
    technology while I'm still
    struggling with the ones I found necessary to use.Me, too. I'm overwhelmed by all that I don't know. That's why I'm taking the time to get all the way through Spring once. I've been reading and dabbling, but I haven't given it enough concentrated attention to have it under my fingers. I've got three personal projects lined up once I get through "Pro Spring" that should set it into my head nicely.
    <advertisement>
    By the way, I decided to buy a copy of IntelliJ. I've never paid for an IDE, but since I've gotten used to it at work I don't want to be without it. I've never championed an environment as much as I do this one. I used Eclipse for several years and was glad to have it, but I'd still find myself slipping out and using a text editor to do quick things. IntelliJ doesn't get in my way. It's completely eliminated any temptation to use a text editor. A terrific product that's only getting better with time.
    </advertisement>
    <disclaimer>I'm not related to anyone who works for or affiliated with JetBrains in any way. Just a happy customer.
    </disclaimer>
    I'm not a GUI guy myself, far from that and I'd like
    to stay away from it as
    far as possible. As I wrote above I feel "all dressed
    up but nowhere to go".
    I've got my beans all ready, my DataSources are all
    solid and sound; I
    can see that everything works (from the logs), but
    that darn web stuff
    keeps on pestering me ...I think the UI is always the hardest part. Everything from the service layer back can almost be generated from the beans and tables: Hibernate mappings, DAOs, service layer, JUnit tests for the whole thing. A few nice annotations and you've got the whole thing. Just the UI beast left to tame...
    >
    I think I'll take another Grolsch and chase that
    silly squeaky bird away.
    Enjoy your weekend!
    kind regards,
    JosYou too! Go enjoy some World Cup football!
    %

  • Why String class is defined as immutable?

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

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

  • HT4910 i save my photos to camera roll. then back up but can't see it on icloud. why? we just lost 300 photos on my other iphone because we do not get proper help. that's why i need to learn now.

    i save my photos to camera roll. then back up but can't see it on icloud. why? we just lost 300 photos on my other iphone because we do not get proper help. that's why i need to learn now.

    You can't view your back up files at icloud.com.
    You can't view your camera roll and you can't view your Photo Stream files at icloud.com.
    The icloud back up plan allows you to "restore" your iOS device from the files you backed up at icloud.com.

  • I am not able to register my Apple ID for iCloud and the error is "the maximum no of free accounts have been activated on this phone" can any one help me why I need to do

    I am not able to register my Apple ID for iCloud and the error is "the maximum no of free accounts have been activated on this phone" can any one help me why I need to do

    Sir, your Apple ID can be used as an iCloud account as well. They are both the same thing.
    You can learn more from --> Set up your Apple ID for iCloud and iTunes - Apple Support

  • Can you give me some reasons about why I need to buy an iPod touch 5.Although I have the iPhone ,iPod nano, iPad ,MacBook pro,I think the iPod touch 5 is so attractive that I can't help buying it at once.If I have it,what I can do with it,can you tell me?

    can you give me some reasons about why I need to buy an iPod touch 5.Although I have the iPhone ,iPod nano, iPad ,MacBook pro,I think the iPod touch 5 is so attractive that I can't help buying it at once.If I have it,what I can do with it,can you tell me?

    All I can say is that I REALLY like my Touch 4th gen because I have all sorts of capabilities in a small form: e-mail, web browsing, news, weather, books, magazines, etc. etc.  Plus lots and lots of apps out there, including so many free ones.  I use the Cloud a lot so it's great to have everything sync'd to my MacBookPro (e-mail, Evernote, Pocket, etc.)
    It would be easier, though, to do some of this, especially magazines, on the iPad mini, but, again, I love the small size of the Touch. 
    As for the 5th gen instead of the 4th, the fifth has Siri and the 3D feature in maps, which are great.  And I'm sure it's a lot faster in iOS 6 than the 4th gen.  And cool colors! 
    Don't know if this helps . . .

  • IF Auto Update Statistics ENABLED in Database Design, Why we need to Update Statistics as a maintenance plan

    Hi Experts,
    IF Auto Update Statistics ENABLED in Database Design, Why we need to Update Statistics as a maintenance plan for Daily/weekly??
    Vinai Kumar Gandla

    Hi Vikki,
    Many systems rely solely on SQL Server to update statistics automatically(AUTO UPDATE STATISTICS enabled), however, based on my research, large tables, tables with uneven data distributions, tables with ever-increasing keys and tables that have significant
    changes in distribution often require manual statistics updates as the following explanation.
    1.If a table is very big, then waiting for 20% of rows to change before SQL Server automatically updates the statistics could mean that millions of rows are modified, added or removed before it happens. Depending on the workload patterns and the data,
    this could mean the optimizer is choosing a substandard execution plans long before SQL Server reaches the threshold where it invalidates statistics for a table and starts to update them automatically. In such cases, you might consider updating statistics
    manually for those tables on a defined schedule (while leaving AUTO UPDATE STATISTICS enabled so that SQL Server continues to maintain statistics for other tables).
    2.In cases where you know data distribution in a column is "skewed", it may be necessary to update statistics manually with a full sample, or create a set of filtered statistics in order to generate query plans of good quality. Remember,
    however, that sampling with FULLSCAN can be costly for larger tables, and must be done so as not to affect production performance.
    3.It is quite common to see an ascending key, such as an IDENTITY or date/time data types, used as the leading column in an index. In such cases, the statistic for the key rarely matches the actual data, unless we update the Statistic manually after
    every insert.
    So in the case above, we could perform manual statistics updates by
    creating a maintenance plan that will run the UPDATE STATISTICS command, and update statistics on a regular schedule. For more information about the process, please refer to the article:
    https://www.simple-talk.com/sql/performance/managing-sql-server-statistics/
    Regards,
    Michelle Li

  • Why we need ABAP if we can connect With Crystal Reports to SAP R/3

    Hi,
        I am new to Crystal reports.I came to know that we can connect SAP R/3 by using SAP InfoSet,SAP Table Cluster and Function connectivity in Crystal Reports.So we can generate reports for SAP R/3 database with out need of ABAP.So why we need to go ABAP module.Is there any disadvantages if we dont use ABAP to generate reports or we can use always Crystal Reports to generate Reports for R/3 database?

    Hi,
    it is correct that you can built a Crystal Report without the need to use ABAP, but we have lots of customers that have invested over the years into ABAP Routines and Crystal REports is able to leverage those as well. So with Crystal Reports you have the choice to leverage existing ABAP Functions as a source for reporting - which might help to leverage complex processing on the backend - or to use InfoSets and tables.
    regards
    Ingo

  • Does CC 2014 eliminate the need to have Final Cut Pro and/or Compressor installed to access Apple ProRes 422?

    Hello:
    Just today, I was working on a Mac system that does not have any of the applications that I would have expected to need to have installed in order to do more than just decompress movie files compressed with Apple ProRes 422.
    I was expecting to have to install Final Cut Studio 3, Final Cut Pro X, Compressor 4, and/or QuickTime 7 with the QuickTime Pro key; however, none of those applications are installed and I am able to create custom QuickTime Apple Pro Res422 Sequences in Premiere Pro as well as export using Apple ProRes 422.  After Effects and Adobe Media Encoder also show all the Apple ProRes variations.
    Does CC 2014 eliminate the need to have Final Cut Pro and/or Compressor installed to access Apple ProRes 422?  Is it something happening on the OS or QuickTime level that would affect CC or CS6 in the same way?
    I've done a web search, but haven't really come up with anything other than older articles about needing to have FCP installed (and I typically work on systems with Final Cut Studio 3 installed as well as CS6, CC, or CC 2014).  If more detailed information is available, it would be great to be able to read up on it.
    The system is a 21.5-inch iMac running Mac OS X 10.8.5, QuickTime Player 10.2, and Adobe Premiere Pro CC 2014 (8.0.0 - I know an update is available for PrPro, but it's not my system to make that change).
    Thanks in advance,
    Warren Heaton

    Hi Emil:
    I use ProRes all the time as well, but I have Final Cut Studio on my workstations.
    I had not come across MindPower009's YouTube video.  That explains how ProRes could be showing up without FCP or Compressor.
    So, the answer to my question would be, "No, CC 2014 does not eliminate the need to have Final Cut Pro and/or Compressor installed to access Apple ProRes 422; however, if you are willing to be in violation Apple's terms of use, you can install the ProRes codecs anyway."
    Even though MindPower009's YouTube video comments claim "FREE and LEGAL", it's clear from both the Apple download page and the ProRes codecs installer that Apple expects you to own at least one of their applications.
    Thanks again for the link!
    -Warren

  • Do I need to have Final Cut to run Motion?

    Hello guys,
    I understand that I can purchase Motion 5 (and Compressor 4) as stand alone applications, but I was wondering:
    Do I need to have Final Cut installed in order to run it?
    Just use it to create animated graphics, then export it as a self contained file and use it in any editing program.
    And I was also wondering if Motion 5 would run OK on a new iMac (27 inch one with NVIDIA GE FORCE GTX 775 card).
    Thank you so much for your feedback,
    Paul

    You do not need to have Final Cut installed to run Motion or Compressor.  Each app can run as a stand-alone. Some functionality is enhanced when running them in combination. Motion will run just fine on any current hardware.  You can always check the system requirments to know if the applications will run on a particular computer.
    http://www.apple.com/lae/finalcutpro/specs/
    http://www.apple.com/lae/finalcutpro/motion/specs/
    http://www.apple.com/lae/finalcutpro/compressor/specs/

  • Why I need a code for rent a film and where ist the code? (I dont have a card)

    Why I need a code for rent a film and where ist the code? (I dont have a card)

    it's unclear what you mean
    you say you dont have a card which I guess is you don't have a creditcard
    in which case the other option is to pay by a giftcard which include a code which you put in
    because to rent you have to pay otherwise it's not really renting

  • Why we need Java Class in c++ pof Serialization

    Hi,
    I'm really confused why we need java class which implements PortableObject to support complex objects of c++. If we are not using any queries or entry processors in the application can't we keep the object as serialized byte format and can't we retrieve in from the c++ deserialization.
    Please share your thoughts if there's a way if we can skip any Java implementation.
    regards,
    Sura

    feel both are doing same work. Also can anyone tell me what is teh difference between Serilization and Exgternalization.If you need someone to tell you the difference, (a) how can you possibly 'feel both are doing the same work'? and (b) why don't you look it up in the Javadoc?
    It's not a secret.

Maybe you are looking for

  • Need to publish my iweb site

    Purchased the domain with godaddy, but no longer have mobile me. HELP! can I use software like Rage or Host Excellence. Can I have multiple websites hosted? Not sure what to do need my sites back up on the internet ASAP!

  • How to cleaning old files hidding?

    My files not need and hidding on my OS Mac 10.6.7 . My friend told me about Mackeeper. I say no way. I just want to learn about utilities for cleaning old files on my programs that I not need. Does Macbook Air have automatic unused files and ask me t

  • Compressor 4.1 Crashes When Changing Location

    Every time I click on a job to change the Location from Source to a specific folder, Compressor 4.1 crashes.  I've trashed preferences using Preference Manager but to no avail.  Suggestions?

  • Designing with Kuler | Understanding Adobe Photoshop CS6 | Adobe TV

    This video shows how the Kuler utility can be used when working with color to import themes, adjust palettes and save swatches, using other people's inspiration and adding your own to the online community. http://adobe.ly/Wc2Tu4

  • ICloud Connectivity Issues

    I'm hoping others may be able to assist me with diagnosing the cause of one of the issues with my Mac right now (without suggesting that I perform a re-install of my OS). I have been noting issues within my Console log that I discovered when I was tr