Java Reference
In-Depth Information
static double
plusone(
int
n)
{
return
n+1.0;
}
static double
plusone(
double
x)
{
return
x+1.0;
}
static double
plusone(String s)
{
return
Double . parseDouble(s) +1.0;
}
public static void
main( String [ ]
args )
{
System . out . println ( plusone (5) ) ;
System.out. println(plusone (6.23)) ;
System . out . println ( plusone (
"123.2"
));
}
}
We get the following output:
6.0
7.23
124.2
However Java does not take into account the type of the result for creating
signatures associated with functions, so that the following code will not properly
compile and generates the following error message:
plusone(int) is already defined in SignatureError static double
plusone(int n)
:
Program 3.10
Function signatures do not take into account the return type
class
SignatureError
{
public static int
plusone(
int
n)
{
return
n+1;
}
public static double
plusone(
int
n)
{
return
n+1.0;
}
public static void
main( String
args [ ] )
{} }
3.5 Recursion
Recursion is a powerful principle for writing functions that call themselves.
Recursion provides a methodology to get compact, simple and yet elegant
algorithms. Since these recursive functions call themselves, we shall take
Search WWH ::
Custom Search