Friday 30 December 2016

Way To Create String




Way To Create String:

  There are two ways to create String object:

  1. By String literal. For Example. String str=”Hello”;
  2. By new keyword. For Example. String str=new String(“Hello”);

By String literal:

  Double quotes are used to create String literals. This is an easier way to create string.

    String s=”Hello”;

  String literals are stored in a special memory area called String constant pool. Each time we create a String literal, the JVM checks the string literal pool first. If the string literal exists in the pool, a reference of the pool instance is returned. If String doesn’t exist in the pool, a new string instance is created and placed in the pool.
  For Example:

String str=”Hello”;
String str2=”Hello”;// new instance cannot be created

Propose of String literal is to make java more memory efficient. Because , no new instance will be created for a string literal if it is already exist in string constant pool.

Strings are unchangeable means that the contents of the String instance cannot be changed after it has been created. However, a variable declared as a String reference can be changed to point at some other String object at any time.

By  New Keyword:

  Object of String can be created by new keyword also. Consider the following:

  String str=new String(“Hello Java”);

  In this case two objects and one reference variable is created. One object is created in heap memory area and other is placed in string constant pool.

String Example:

// Construct one String from another.
class MakeString
{
  public static void main(String args[])
  {
    String str1 = “String Literal”;// By String literal
    String str2 = new String(“String Object”);// By String Objects
    System.out.println(str1);
    System.out.println(str2);
  }
}

  The output from this program is as follows:

  String Literal
  String Object






0 comments:

Post a Comment

Powered by Blogger.

Stats