You are on page 1of 31

UNIT-1

STRINGS
1. A String is a non-primitive data type
• One main point about the primitive and non-primitive that is primitive
data type have fixed size of memory and whereas non-primitives does
not have fixed size
• As String references a memory location where data is stored in the
heap memory or String Constant Pool(SCP)i.e, it references to a
memory where an object is actually placed.
• Thus the variable of a non-primitive data type is also called reference
variable. This reference variable lives on the stack memory and the
object which it points always lives on the heap memory.
2. A String is the sequence of characters or say

String is an array of characters


Char c[]={‘J’,’A’,’V’,’A’};

From the above we can also represent array as a string


String s=new String(c);
• To represent sequence of characters, Java provides an
interface CharSequence interface.
3. String is a class it means
class String
{
//methods of a String
}
But this is not the proper syntax then what is the proper syntax
of String
public final class String
{
}
• ‘Object class’ is the super class of all the classes likewise for
Strings Object class is the super class.
• public final class String extends Object implements
CharSequence,Serializable,Comparable
• Coming to ‘Serializable’ interface is used when we need to
store a copy of the object and send them to another process
which runs on the same system or over the network.
• Comparable interface is used to order the obejcts of the class.
It has only one method i.e.,compareTo()
4. String is an object but it is called as an Immutable object.
We can also create an object using String.
Let’s have a look on it.

String s=new String();


Creation of Strings:
• To create a String, there are three classes but in general there
are four ways to create Strings
1. String s=“Java”;
2. String s=new String();
3. StringBuffer sb=new StringBuffer();
4. StringBuilder sb=new StringBuilder();

• From the above when compared to the first two, we use


mostly the first one rather than the second one.
Why ?
What’s the reason of
using the first one?
String Constant Pool:
• String Constant Pool is a special memory location to store String
objects
• SCP is constant memory for Strings located in heap, previously it
is in method area(PERMGEN).
• The reason why it is located in heap because the heap memory
can increase or decrease the memory area. So that’s the reason
SCP is located in heap area.
• String Constant Pool is also called as String Literal Pool where it
stores the values of the String.
• For example:
String s1=new String(“Java”);
String s2=“Programming”;

String s3=new String(“Java”); //doesn’t creates in SCP as


already exists
String s4=“Programming”; //doesn’t creates which directly
relates to SCP

If suppose I need to use object in the future that’s why it is


created in SCP.
String s1=new String(“Java”);//creates 2 objects
String s2=“Programming”;//creates 1 object HEAP
MEMORYAREA
s6
s5
Progra
mming

s1 Java Java
String Constant
Programming
Pool
srinivas

Progra JVM internally


mming creates
s3
reference

s2
s4
• As from the memory areas, we observed that inside heap and
SCP objects are created but 2 objects are created by the new
keyword and also SCP object
• But take a note that whether Garbage collector will come into
picture to free the space as we learnt about it.
• No, it won’t because the JVM internally creates reference to
the String object
• But for SCP it directly creates and Garbage collector is not
applicable
• Coming to the important point that when the String is created
with 2 objects it slows down the project when compared to
directly pointing the String object that is
String s=“Java”;

If suppose if we want to create one more object with same name


as
String s3=new String(“Java”);
It creates object in HEAP memory but in SCP it checks whether
the object is already present or not. So, that’s the reason it
won’t creates object again and again.
WHY STRINGS
ARE
IMMUTABLE OBJECTS
What is immutability?
“Immutable” means unchangeable.
• Immutability concept is used for “String objects” i.e., String
objects are unchangeable, means once String object is
created, its data or state can’t be changed but a new String
object is created.

• Let’s have a look with an example


For example: String s=new String(“Java”);

Suppose if we want to change the value of the String, then let’s


take a look:
s.concat(“python”);
Suppose if we write the statement as
s=s.concat(“srinivas”);
System.out.println(s); //javasrinivas
Heap memory

s Java
Java SCP

Javapython python

Python Python
s programmi programmi
ng ng
• In Strings, if we want to have some changes in our String it
creates separate object but it won’t alters or changes the
previous String.
• The above gives rise to immutable nature. In String Constant
Pool or String Literal Pool it creates the object again because it
looks like String literal.
• “String Immutability” always related to String objects.
What about + symbol
Used in our program?
• If suppose we use (+) symbol which is used for concatenation
in our programs, when we use the symbol instead concat()
method it also returns us the same result as of the method

Why String objects are Immutable??????????


• Strings are immutable in Java because String objects are
cached in String pool.
• Since cached String literals are shared between multiple
persons there is always a risk, where one person’s action
would affect all another’s person .
• For example
• Scp=once the string is it changeable
P1=> String city1=“Hyderabad”;
P2=> String city2=“Hyderabad”;
P3=> String city3=“Delhi”;
Hyderabad ……….
P1000=> String city1000=“Hyderabad”;
Delhi
Suppose String city3=“Delhi” which affects all
other persons for that purpose

SCP
• Strings and especially String literals are widely used in
typical Java code. And they are immutable.
• And being immutable allowed to cache String to save memory
and increase performance (less effort for creation, less
garbage to be collected).
Methods Description

substring() returns the substring of the string

replace() replaces the specified old character with the specified new character

charAt() returns the character present in the specified location

getBytes() converts the string to an array of bytes

indexOf() returns the position of the specified character in the string

compareTo() compares two strings in the dictionary order

trim() removes any leading and trailing whitespaces

format() returns a formatted string


WHAT’S THE CASE
IF WE NEED CHANGES
IN THE STRING
AS IT OCCURS
FREQUENTLY???
• The solution is second way to create a String by using StringBuffer
class.
• We already know the Strings are immutable objects. Suppose for an
example,

String s=“Java”;

s.concat(“programming”);

S.o.p(s);//java

It doesn’t adds programming to java,if we need such change in our


program then we have to make use of StringBuffer class, which is
said to be as Mutable objects.
StringBuffer sb=new StringBuffer(“Java”);

sb.append(“programming”);

S.o.p(sb);//java programming
• There is no separate object to be created for programming, it changes
in a single object.
• If we come to know that the String has frequent changes then we
choose StringBuffer class, whereas if we didn’t want any changes and
make the String object as safer one then we have to choose String
• Public class final StringBuffer implements
serializable,CharSequence,comparable
Class constructors

Sr.No. Constructor & Description

1 StringBuffer()
This constructs a string buffer with no characters in it and an initial
capacity of 16 characters.

2 StringBuffer(int capacity)
This constructs a string buffer with no characters in it and the specified
initial capacity.

3 StringBuffer(String str)
This constructs a string buffer initialized to the contents of the specified
string.
.equals() method and == operator:

• == operator is used for reference comparison (Address


comparison). It means == operator checks if both objects point
to the same memory location or not.
• “.equals() method” is used for content comparison (in String
class). It means .equals() method is used to check object value.

• S1 s2 s3 s4 s5 s6…………..
• String s1=new String(“java”);
• String s2=new String(“java”);
• S.O.P(s1==s2);//false
Heap

SCP

s1
Java
Java s3
program
java

s2 s4
ensureCapacity()
This method is used to ensure minimum capacity
of StringBuffer object.
• If the argument of the ensureCapacity() method is less than the
existing capacity, then there will be no change in existing capacity.
• If the argument of the ensureCapacity() method is greater than the
existing capacity, then there will be change in the current capacity
using following rule: newCapacity = (oldCapacity*2) + 2.

You might also like