Strings in Java

String

String is a sequence of characters. In Java string is an object that is created by String class. The string is an immutable object which means that it cannot be modified once it has been created.

For example:
char[] chr = {'T', 'u', 't', 'o', 'r', 'i',  'a', 'l', 'R', 'i', 'd', 'e'};  
String s = new String (chr);
or
String str = "TutorialRide";

In the above example, both the char array and string are the same.

Creating String

There are two ways to create string in Java.
1. By using string literal
2. By using new keyword.

1. By using String Literals
It is simply created by assigning the string value within double quotes ("").

For example:
String s1 = "welcome";
String s2 = "Hello";

When we create string literals, JVM first checks if the string object already exists in string pool. If string already exits, then JVM does not create reference in pool.

2. By using new keyword
String object are also created by use of new keyword.

For example:
String s1 = new String ("Hello");
String s2 = new String ("welcome");

Example : Sample program to create and print string

public class StringDemo
{
       public static void main(String args[])
       {
              char[] ch = {'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 'R', 'i', 'd', 'e'} ;
              String str1 = new String(ch);
              String str2 = "TutorialRide";
              String str3 = new String ("TutorialRide");
              System.out.println(str1);
              System.out.println(str2);
              System.out.println(str3);
       }
}


Output:
TutorialRide
TutorialRide
TutorialRide

Concatenating Strings

  • String class has a method to concatenate the two strings into the single string.
  • Syntax: string1.cancat (string2);
  • Strings are also concatenate by using + operator.
  • Syntax: string3 = string1 + string2

Example : A program demonstrating concatenation of strings

public class StringTest
{
      public static void main(String args[])
      {
            String str1 = "Java ";
            String str2 = "Tutorials";
            System.out.println(str1.concat(str2)); //using concat() method
            System.out.println(str1 + str2); //using + operator
      }
}


Output:
Java Tutorials
Java Tutorials

Immutable String

Once the objects of a String class are created, they cannot be changed or modified. So string objects are called immutable.

Example

public class ImmutableTest
{
       public static void main(String args[])
       {
             String str1 = "Java ";
             str1.concat("Tutorial");
             System.out.println(str1); // it will only print Java
       }
}


Output:
Java