Java Strings

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings

The most direct way to create a string is to write:

String greeting = "Hello world!";

Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'.

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters.

public class strDemo{

   public static void main(String args[]){
      char[] hello_array = { 'h', 'e', 'l', 'l', 'o', '.'};
      String hello_string = new String(hello_array);  
      System.out.println( hello_string );

String Length

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.

public class StringDemo {

   public static void main(String args[]) {
      String palindrome = "Welcome to Java Tutorial";
      int len = palindrome.length();
      System.out.println( "String Length is : " + len );
String Length is : 24

Concatenating Strings

The String class includes a method for concatenating two strings:


This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in:

"My name is ".concat("Sachin yadav");

Strings are more commonly concatenated with the + operator, as in:

 "Hello" + " world" + "!"

which results in:

 Hello world !


public class StringDemo {

   public static void main(String args[]) {
      String string1 = "to Java ";
      System.out.println("Welcome" + string1 + "Tutorial");
Welcome to Java Tutorial

Share this article on