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 StringDemo{
public static void main(String args[]){
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println(helloString );
}
}
String Length:
publicclassStringDemo{
publicstaticvoid main(Stringargs[]){
String palindrome ="Dot saw I was Tod";
intlen=palindrome.length();
System.out.println("String Length is : "+len);
}
}
Concatenating Strings:
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end.
Let us look at the following example:
publicclassStringDemo{
publicstaticvoid main(Stringargs[]){
String string1 ="saw I was ";
System.out.println("Dot "+ string1 +"Tod");
}
}