Java Reference
In-Depth Information
These incrementation instructions are so frequent that they can be ei-
ther written compactly as
++x
or
x++
(for pre-incrementation and post-
incrementation). Let us explain the difference between
pre-incrementation
and
post-incrementation
:
Consider the following code:
i=2;
j=i++;
This gives the value 3 to
i
and 2 to
j
as we do a
post-incrementation
. That
is, we increment after having evaluated the expression
i++
. The above code is
equivalent to:
i=2;
j=i;
i=i+1; // or equivalently i+=1;
Alternatively, consider the pre-incrementation code:
i=2;
j=++i;
This code is equivalent to...
i=2;
i=i+1;
j=i;
... and thus both the values of
i
and
j
are equal to 3 in this case. The same
explanations hold for pre-decremention
.
Note that technically speaking the
++
syntax can be seen as a
unary operator
.
i
and post-decrementation
i
−−
−−
1.7.3 A calculator for solving quadratic equations
Let us put altogether the use of mathematical functions with variable init
ializa-
tions and assignments in a simple program that computes the roots
b
√
b
2
−
4
ac
2
a
±
of a quadratic equation
ax
2
+
bx
+
c
=0:
Program 1.12
A quadratic equation solver
class
QuadraticEquationSolver
{
public static void
main( String [ ]
arg )
double
a,b,c;
a=Math. sqrt (3.0) ;
b=2.0;
c=
−
3.0;
double
delta=b
∗
b
−
4.0
∗
a
∗
c;
double
root1 , root2 ;
Search WWH ::
Custom Search