What is String? Ways to create String? Complete Concept !!

In java, string is basically an object that represents sequence of char values.

char[] ch={'j','a','v','a','b','o','x'};  
String s=new String(ch);  

is same as

String s="javabox"

Two ways to create String object:

  1. By string literal
  2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:
String s="javabox";

Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled 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 s="javabox";
String s="javabox";//will not create new instance 

Note: String objects are stored in a special memory area known as string constant pool.

Why java uses concept of string literal?
To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).


2) By new keyword

String s=new String("javabox");//creates two objects and one reference variable 
In this case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool).

Program-

public class A {
public static void main(String args[]) {
String s1 = "javabox"; // creating string by java string literal
char ch[] = { 'p', 'u', 'l', 'k', 'i', 't'};
String s2 = new String(ch);  // converting char array to string
String s3 = new String("rajput"); // creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}

Output-
javabox
pulkit
rajput


Program to print box pattern in java

Pattern to be printed - 

 *****
*****
*****



Program -

public class BoxPattern {

public static void main(String[] args) {

for (int i = 1; i <= 3; i++) {

for (int j = 1; j <= 5; j++) {

System.out.print("*");

}
System.out.println();
}
}


}


Basic structure and printing elements of Linked list in java

class Node {      int data ;      Node next ;           Node ( int data ){            this . data = data ;            ...