Pages

Strings in java

Strings in java?
  • Strings plays a vital role in programming language
  • Group of characters enclosed in double quotes ("")
  • String is a class belongs to java.lang package.This is the default package in a java program which consists of basic classes and interfaces (ex: I/O console,utility,keyboard functions)
  • String is a class in which once the values stored in it, can't be modified.Therefore string is called as Immutable class.
  • String objects are always stored in string constant pool memory
    A string can be declared in 2 ways

   1) By using String literal
   2) By using new operator
    
      String s1="welcome";
      
      String s2=new String("welcome");

public class StringDemo {
public static void main(String[] args) {
String s1 = "first string";
System.out.println("using string literal: " + s1);

String s2 = new String("second string");
System.out.println("using new operator: " + s2);
}
}

Output:
using string literal: first string
using new operator: second string
Here difference is, string literal s1 is stored in string constant pool whereas s2 is stored in Heap (non-pool) memory



Strings memory
Strings


See below program we can understand the difference:

public class StringDemo {
public static void main(String[] args) {
String a = "one";
String b = "one";
System.out.println(a == b);

String c = new String("two");
String d = new String("two");
System.out.println(c == d);
}
}

Output:
true
false
intern() method in string:

intern() method is used to put the object in String constant pool area.when a string is declared using String literal it will automatically call intern() method and put the object in SCP area. So, intern() method is used to move objects to SCP area.

Just see below program:

public class StringDemo {
public static void main(String[] args) {
String a = "one";
String b = "one";
System.out.println(a == b);

String c = new String("two");
String d = new String("two");
System.out.println(c.intern() == d.intern());
}
}

Output:
true
true

Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.