String class in Java
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.
Creating Strings
The most direct way to create a string is to write
String company = "Oracle Corporation";
As with any other object, you can create String objects by using the new keyword and a constructor.
String company = new String("Oracle Corporation");
char[] companyArray = { 'O', 'r', 'a', 'c', 'l', 'e' };
String companyName = new String(companyArray);
Note: The String class is immutable, so that once it is created a String object cannot be changed.
String Length
public int length()
Returns the length of this string. The length is equal to the number of Unicode code units in the string.
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.
You can also use the concat() method with string literals, as in:
"Company name is ".concat("Oracle Corporation");
Strings are more commonly concatenated with the + operator, as in
"Hello," + " Java" + "!"
which results in
"Hello, Java!"
The + operator is widely used in print statements. For example:
String string1 = " Oracle ";
System.out.println("Compnay name is " + string1 + " Corporation");
which prints
Company name is Oralce Corporation
Such a concatenation can be a mixture of any objects. For each object that is not a String, its toString() method is called to convert it to a String.
Creating Format Strings
Manipulating Characters
Example:
import java.io.*;
import java.lang.*;
public class StringDemo
{
public static void main(String args[])
{
String str="welcome to Sun";
char ch=str.charAt(0);
System.out.println("Chareter at 0 is.."+ch);
String con_str=str.concat(" software");
System.out.println("Concatted String is.."+con_str);
System.out.println("Index of 'e' is...."+str.indexOf('e'));
System.out.println("Index of 'e' from 3 is.."+str.indexOf('e',3));
System.out.println("last Index of 'e' is...."+str.lastIndexOf('e'));
System.out.println("String length is.."+str.length());
System.out.println("replaced String as.."+str.replace('e','k'));
System.out.println("SubString is.."+str.substring(11));
System.out.println("Substring is.."+str.substring(3,7));
String ustr=str.toUpperCase();
System.out.println("upper Case is.."+ustr);
System.out.println("Lower case is..."+ustr.toLowerCase());
String tstr=" Java ";
System.out.println("String after trim is.."+tstr.trim());
}
}