Description
Learn Java with simple programming examples.
This snippet evaluates the polynomial
1 2 
y = 2x<sup><span style="fontsize: medium;">3</span></sup> + 3x<sup><span style="fontsize: medium;">2</span></sup>  4x + 3 where x = 3 
Raising a number to a power (e.g., x^{3}) is often represented in other programming languages with the caret symbol (^), meaning to the power of.

1x^3
In Java, a number is raised to a powerÂ by successive multiplications

1x * x * x
or with the builtin Math.pow()
method.
We will use variables of type double
throughout the program snippet because the Math.pow()
method requires double
rather than int
. Raising the number three to the second power (i.e., 3^2) is expressed as

1Math.pow(3.0, 2.0);
Source Code
 Type (or copy) the program shown below into your computer, compile it, and then run it.
 Modify the line
double x = 3.0;
todouble x = 5.0;
to evaluate the polynomial with a different value ofx
.  What result do you expect? Use a calculator if you need to.
 Compile and run it to see if you were correct.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 
/* Program EvaluatePolynomial.java This program evaluates the polynomial y = 2x^3 + 3x^2  4x + 3Â Â Â Â Â where x = 3Â Â Â Â */ class EvaluatePolynomial { public static void main(String args[]) { double x = 3.0;Â Â Â Â Â Â Â Â // Change this to evaluate other values of x. double y; y = 2.0 * Math.pow(x, 3.0) + 3.0 * Math.pow(x, 2.0)  4.0 * x + 3.0; System.out.println("Given x = " + x + " then y = " + y); } } 
Compile and Run Screenshot