Wednesday, 13 August 2014

Java Program to Calculate the Square Root of a nmuber

As in our previous program we have just printed the message using System.out.println() method now we are going to use more features of Java .We will use some packages(like header files of C++).It would be coming in your mind that what is package. Actually package is a set of java code that is already written by Java developers and we are going to use them in our program(we will see packages in details in upcoming blog post).
import java.lang.Math;           //import package statement
class SquareRoot
{
   public static void main(String arg[])
   {
       double num=5;                //declaration and initialization of variable
       double sqResult;
       sqResult=Math.sqrt(num);     //This statement will calculate the Square-root 
       System.out.println("Square root of num 5 is="+sqResult);
   }
}
In this program the structure is same as in the previous post program.But the new code that is there in the example is as following:-

  • variable declaration statement

double num=5;
this statement is a variable declaration statement that has variable name
num
,this name is used in further code as a reference of value 5.we will see full explanation that shows how to declare variables and what rules are followed in the upcoming post.
double sqResult;
This statement also a variable declaration statement but we are not providing the initial(default) value.

  • Method call of a class

sqResult=Math.sqrt(num); 
In this statement we are saving the result value to the variable sqResult. On the right hand side of equal operator(=) we are calling a method(function) of class 'Math' that accept the variable 'num' as argument and do some calculation for us(the code is already written in package) and return the result back . = equal operator set the result into variable 'sqResult'.

  • Printing the result on the command line
  • System.out.println("Square root of num 5 is="+sqResult); 
    This statement will print the message that is written in the double quotes and the value of the variable 'sqResult'.You can see that the 'println' is also a method(function' that is accepting the message given by us and it will do some work for us to print it on the command prompt.
Execution:-

  • Open notepad and write the code:-




  • Save the code in file with name' SquareRoot.java':-

  • Compile and Run the program in command prompt:-