String in Java

Posted on 2012-09-21
Last Modified: 2012-10-16

What is the difference between the following 2 statements:

      String Str1 = new String("Welcome to");



String Str1="Welcome to";

Question by:JRawabi
    LVL 12

    Accepted Solution

    In the first case , a new object is created irrespective of whether the string is available in the string pool

    Second case , a new string object is created only if the string "Welcome to" is not available in the string pool . If it's already available , then a new object is not allocated
    LVL 12

    Expert Comment

    by:Sharon Seth
    When it comes to Strings , Java has a concept of string internalizing , or in short string interns.
    The JVM maintains a pool of strings . Whenever you assign a string literal(as in the second case) the string gets pooled . Next time someone wants to create another string with the same value , then the String object from the pool is used. It means new memory is not allocated , but the existing reference is used.

    But when you use the new() operator , new memory is allocated to the string , instead of using an already existing reference from the pool

    For this reason , String class has an intern() method , which  will send a string to the pool . All this is for optimizing string memory due to the fact that strings are immutable.

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
    Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
    This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
    This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.

    734 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now