Strings
Strings
Strings
Java String
• String is a sequence of characters.
• In java, objects of String are immutable which
means a constant and cannot be changed
once created.
• There are two ways to create string in Java:
String s = “GLA University”; //String literal
String s = new String (“GLA University”);
// Using new keyword
String Literal
• Java String literal is created by using double quotes.
• String objects are stored in a special memory area
known as string constant pool.
• 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.
String Constant Pool
String s1="Welcome";
String s2="Welcome";
String s=new String("Welcome");
• The above code creates two objects and one
reference variable.
• In such 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).
Methods defined in String class
No. Method Description
Points to Remember
public class RecursionExample3 {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args) {
System.out.println("Factorial of 5 is: "+factorial(5));
}
}