String class in Java

Java 8Object Oriented ProgrammingProgramming

Strings, which are widely used in Java programming, are a sequence of characters. The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes.

Let us now see how to create strings in Java −

String str = “John”;

The new keyword is used in creating arrays and even strings. Let us see how −

String str = new String(“John”);

String class has a lot of methods in Java to manipulate strings, finding length, format strings, concatenate, etc. Let us see some examples −

Here, we will find the length of strings and concatenate them −

Example

public class Main {
   public static void main(String args[]) {
      String str1 = "This is ";
      String str2 = "it!";
      System.out.println("String1 = "+str1);
      System.out.println("String2 = "+str2);
      int len1 = str1.length();
      System.out.println( "String1 Length = " + len1 );
      int len2 = str2.length();
      System.out.println( "String2 Length = " + len2 );
      System.out.println("Performing Concatenation...");
      System.out.println(str1 + str2);
   }
}

Output

String1 = This is
String2 = it!
String1 Length = 8
String2 Length = 3
Performing Concatenation...
This is it!
raja
Updated on 20-Sep-2019 11:30:41

Advertisements