Java String Manipulation With Example

Java String

What is the String?

  • A string is a sequence of characters.
  • Example: – “Welcome To My World”
  • A string is an immutable object which means that value cannot be changed once it is created. If we try to modify the content, it will create a new object.

What is an immutable object?

  • The class must be declared as final (child classes can’t be created).
  • Data members in the class must be declared as final (After object creation we can’t change the value) .
  • The constructor should be parameterized.
  • All the defined variables should have getter methods.
  • No setters methods(Not have the opportunity to change the value of the instance variable).

Example for immutable :

Output :

User Name-->Sairam
User Id--> 568

Read : Why string is immutable in java?

How many ways we can create string objects in java?

1.Using String Literals :
Example :
String string1=”Java String”;

The above statement creates a String literal with value “Java String” in the String Constant Pool.

2. Using a new Keyword :
Example :
String string2= new String( “ Java String ”);

The above statement creates a String object in the Heap Memory and String Constant Pool (if not exists in SCP).

3. Using a character array :
Example :
char array[] ={‘s’,’c’,’h’,’o’,’o’,’l’};
String string3= new String( array);

The above statement creates a String object in the Heap Memory and String Constant Pool (if not exists in SCP) .

Example : –

Output :

  Output–>false  

How many String objects got created in above snippet?

  • Two objects will be created.
  • String name = “Java String”: – This line will create one object in SCP.
  • String name2 = new String(“Java String”):- This line will create one object in Heap because in SCP already created a reference with “Java String” value, so it will take that reference.

I hope it will help you,please give the comments and suggestions below.

About Manohar

I, Manohar am the founder and chief editor of ClarifyAll.com. I am working in an IT professional.

View all posts by Manohar →

Leave a Reply