1. Introduction:
Strings are often used in programming. A string is a sequence or a sequence of characters. In many languages a string is an array of other characters, whereas in Java a string is a object. This is the main difference between Java and other programming languages regarding the Strings.
Java offers 3 main classes related to strings:
- The class String (string not editable)
- The class StringBuffer (string modified as desired)
- The class StringTokenizer (separating a string into several entities)
In most cases it is necessary to use string to create, store and manage strings. The StringBuffer class provides greater flexibility and is used in the same manner as the String class.
2. The String Class:
This class has 11 manufacturers and over 40 methods to examine the character of a string, compare, search, retrieve, etc.. Among these methods, some are described below. You can find other by experimenting with the language.
2.a. Construction of the String:
A string is usually declared as follows:
Code:
String name = new String("Some Name");
As the strings are a data type widely used, Java allows a more concise statement:
Code:
String name = "Some Name";
2.b. Comparing strings
It is tempting to compare two strings using the == operator as in:
Code:
if (str1 == str2)
However, this comparison, although is correct, does not compare whether two strings are equal, but if str1 and str2 point to the same object.
A string comparison is done as follows:
Code:
if (str1.equals(str2))
There is also the method compareTo :
Code:
str1.compareTo(str2);
This method returns 0 if both strings are equal, a negative value if str1 is smaller than str2 or a positive value if str2 is smaller than str1.
Note: Do not use the operators >,> =, <, <=
No comments:
Post a Comment