Unit-I - 4 String
Unit-I - 4 String
What is String?
• A string is sequence of characters.
• string is a sequence of characters that exists as an object of the
class java.lang.
• A string class is a user-defined template for creating and
manipulating string objects, which are sequences of characters
• Java strings are created and manipulated through the string
class.
• A String can be constructed by either:
• a string literal
• via the "new" keyword
String str1 = "Java is easiest language";
String str2 = new String("I'm cool");
•In the first statement, str1 is declared as a String reference and initialized with a
string literal "Java is easiest programming language". In the second
statement, str2 is declared as a String reference and initialized via
the new operator and constructor to contain "I'm cool".
•String literals are stored in a common pool. This facilitates sharing of storage for
strings with the same contents to conserve storage. String objects allocated
via new operator are stored in the heap, and there is no sharing of storage for the
same contents.
String Literal vs. String Object
• there are two ways to construct a string: implicit construction by
assigning a string literal or explicitly creating a String object via the
new operator and constructor.
When the next statement s.concat(“world”); will be executed by JVM, it will create two new objects
because we are trying to modify the original content.
1. First, for every string literal “world”, JVM will create one copy of string object in the string constant pool.
2. The second object will be created in the heap with modified content “hello world”. Since string
concatenation is executed at the runtime. Therefore, if a new object is required to create, this new object is
always created in the heap area only, not in the string constant pool.
Since this new object is not assigning with any reference variable, therefore, it is called unreferenced object
and the garbage collector will automatically remove it from the memory.
Thus, the value of string s is not modified and still, ‘s’ is pointing to “hello” only. Therefore, the result is
“hello”. This is the reason, string objects are called immutable in Java.
String Methods
int length() method
• The length() method returns the length of the String that is, the
number of characters in a String.
}
}