Java – String Class and its methods explained with examples

Guided by Bipin Ajay
Founder of Tech Jitendra .

String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an immutable object which means it is constant and can cannot be changed once it has been created. In this tutorial we will learn about String class and String methods in detail along with many other Java String tutorials.

Creating a String

There are two ways to create a String in Java

  1. String literal
  2. Using new keyword

String literal

In java, Strings can be created like this: Assigning a String literal to a String instance:String str1 = “Welcome”; String str2 = “Welcome”;

The problem with this approach: As I stated in the beginning that String is an object in Java. However we have not created any string object using new keyword above. The compiler does that task for us it creates a string object having the string literal (that we have provided , in this case it is “Welcome”) and assigns it to the provided string instances.

But if the object already exist in the memory it does not create a new Object rather it assigns the same old object to the new instance, that means even though we have two string instances above(str1 and str2) compiler only created on string object (having the value “Welcome”) and assigned the same to both the instances. For example there are 10 string instances that have same value, it means that in memory there is only one object having the value and all the 10 string instances would be pointing to the same object.

What if we want to have two different object with the same string? For that we would need to create strings using new keyword.

Using New Keyword

As we saw above that when we tried to assign the same string object to two different literals, compiler only created one object and made both of the literals to point the same object. To overcome that approach we can create strings like this:String str1 = new String(“Welcome”); String str2 = new String(“Welcome”);

In this case compiler would create two different object in memory having the same string.

A Simple Java String Example

public class Example{ public static void main(String args[]){ //creating a string by java string literal String str = “Beginnersbook”; char arrch[]={‘h’,’e’,’l’,’l’,’o’}; //converting char array arrch[] to string str2 String str2 = new String(arrch); //creating another java string str3 by using new keyword String str3 = new String(“Java String Example”); //Displaying all the three strings System.out.println(str); System.out.println(str2); System.out.println(str3); } }

Output:Beginnersbook hello Java String Example

Thaking you

Tech Jitendra

Published by Tech Jitendra Direct Investing

Tech Jitendra Direct Investing (TJDI) Empoworing Your Wealth

Join the Conversation

  1. Tech Jitendra Direct Investing's avatar

1 Comment

Leave a comment

Design a site like this with WordPress.com
Get started