The following program demonstrates the preceding concepts:
// Demonstrating Strings.
class StringDemo {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " + strOb2;
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
}
}
The output produced by this program is shown here:
First String
Second String
First String and Second String
The String class contains several methods that you can use. Here are a few. You can test
two strings for equality by using equals( ). You can obtain the length of a string by calling
the length( ) method. You can obtain the character at a specified index within a string by
calling charAt( ). The general forms of these three methods are shown here:
boolean equals(String object)
int length( )
char charAt(int index)
Here is a program that demonstrates these methods:
// Demonstrating some String methods.
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " +
strOb1.length());
System.out.println("Char at index 3 in strOb1: " +
strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home