Java Reference
In-Depth Information
for
(i = 0; i <= (len - 1)/2; i++)
{
a.
if
(str.charAt(i) is not equal to str.charAt(j))
return false
;
b. j--;
}
4. Return
true
.
The following method implements this algorithm:
public static boolean
isPalindrome(String str)
{
int
len = str.length();
//Step 1
int
i, j;
j = len - 1;
//Step 2
for
(i = 0; i <= (len - 1)/2; i++)
//Step 3
{
if
(str.charAt(i) !=
str.charAt(j))
//Step 3.a
return false
;
j--;
//Step 3.b
}
return true
;
//Step 4
}
We leave it as an exercise for you to write a program to test the method
isPalindrome
. (See Programming Exercise 8 at the end of this chapter.)
As you know, a Java application program is a collection of classes, and a class is a
collection of methods and data members. In a Java program, methods can appear in
any order. However, when a (class containing the main) program executes, the first
statement in the method
main
(of that class) always executes first, regardless of where
in the program the method
main
is placed. Other methods execute only when they
are called.
A method call statement transfers control to the first statement in the body of the
method. In general, after the last statement of the called method executes, control is
passed back to the point immediately following the method call. A value-returning
method returns a value. Therefore, for value-returning methods, after executing the method
control goes back to the caller, and the value that the method returns replaces the method
call statement. The execution then continues at the point immediately following the
method call.
Search WWH ::
Custom Search