String in Java with Explanation

String in Java with Explanation

String is a collection of characters or we can say sequence of characters. We can also say that String is a array of character because its internal implementation looks something like that.

There are two ways to declare the String in java.

1). Using double quotes ” “ or  string literal

String s="tutorialworld";  

2). Using new Keywords

char[] ch={'t','u','t','o','r','i','a','l'};  
String str=new String(ch);  

or

String str=new String("tutorialworld"); 

A String is a class in Java, but this class is special. By one hand I think that it is the class which you will use more times in your life and, in the other hand, it is a special class because we can use it in different ways.

But, what is a String in Java? As its name says, is a text and it is stored and managed by an object. This object is an instance of a class called String.

String str = new String();

But you also can use the constructor to initialize (give the first value) it:

String str = new String("tutorialworld");

Note: String is special, String is different, and String is possible to initialize in this way too:

String str = "tutorialworld";

This way calls directly the constructor with the text “tutorialworld” as parameter.

Java String class provides various string methods to perform operations on strings. Some methods are concat(), equals(), compare(), split(), length(), substring(), replace(), compareTo(), intern(), toUpperCase(), toLowerCase() etc.

The java.lang.String class implements SerializableComparable and CharSequence.

Java String program to demonstrate charAt()

public class CharAtExample {
  public static void main(String args[]) {
    String name = "tutorialworld";
    char ch = name.charAt(3);
    System.out.println(ch);
  }
}

Output

o