Java Reference
In-Depth Information
strings lexicographically, similar to how words or phrases would be sorted alphabetically. If
the first string comes first alphabetically, the method will return a negative integer, indicat-
ing the first is less than the second. If the first operand comes last alphabetically, the method
will return a positive integer, indicating the first is greater than the second. If the two strings
are equal, the method will return 0 . If myString .equals(anotherString) evaluates to true ,
then myString .compareTo(anotherString) will return 0 . An example using the compareTo()
method follows:
String employee1 = "Addams";
String employee2 = "Brown";
String employee3 = "O'Connor";
String manager = "Brown";
employee1.compareTo(employee2); //evaluates to -1 (negative)
employee3.compareTo(employee2); //evaluates to 13 (positive)
employee2.compareTo(manager); //evaluates to 0
There is not a similarly straightforward approach to comparing arrays relationally, partially because
there is not one single way to rank one set of elements against another. Also, the elements of an
array can be any type of object. You can think of many criteria that might determine which int
array is greater than another: the greatest length, the greatest sum of all elements, the greatest single
element, and so on, and that is only for int arrays. Arrays of more complex objects require even
more unique criteria. Relational comparisons of arrays, like many other objects, must be defined
according to the needs of the program.
understanding language control
This section explores how comparison operators and methods can be used in Java control struc-
tures. These structures include for and while loops, if-then statements, and switches. While each
situation may be better suited to one type of structure, in fact, they are usually interchangeable as
they function much the same way using different constructs. The following sections explain each of
these structures independently and also compare and contrast them.
creating if-then statements
The most fundamental control structure is an if-then statement. Simply put, if a condition is met,
then execute a piece of code. It may also be called branching, since different branches of code are
executed according to the conditional statements. Often a control operator will be used as the condi-
tion in an if-then statement. The most basic syntax is as follows:
if (/*condition*/) {
/*then execute these statements*/
}
In this case, if the conditions inside the parentheses are evaluated as true , then the statements
between curly brackets will be executed. Otherwise, the program will not execute the statements
and continue just after the last curly bracket, indicating the end of the block.
 
Search WWH ::




Custom Search