Site icon TestingDocs.com

String Handling in Java

What is a String?

A String is a sequence of characters and the String class is contained in standard java.lang package. Using the object of this class we can manipulate the series if characters. Strings are constant and immutable in Java. String values cannot be changed after they are created. If we need mutable Strings we need to use the StringBuffer class.

 

Create a String

The simple way to create a String is using the below declaration.

String str= “TestingDocs”;

Another approach for creating a string object is:

String s = new String(“TestPlan”);

Concatenation of Strings

The concatenation of strings is joining them into a single String. We can use the + operator for concatenating strings.

 

package com.testingdocs.tutorial;

public class StringConcatenationDemo {

 public static void main(String[] args) { 
String strOne="Testing"; String strTwo="Docs.com";
 //String concatenation operation String 
newStr=strOne + strTwo; 
System.out.println("String one= "+ strOne);
System.out.println("String two= "+ strTwo);
System.out.println("Concatenated String= "+ newStr);
 } 
}

 

concat()

We can use the concat() String method to concatenate Strings as shown below:

package com.testingdocs.tutorial;

public class StringConcatenationDemo {

  public static void main(String[] args) {
    String strOne="Testing"; 
    String strTwo="Docs.com"; 
    System.out.println("String one= "+ strOne);
    System.out.println("String two= "+ strTwo);
    System.out.println("Concatenated String= "+ strOne.concat(strTwo));
  }

}

 

 

Exit mobile version