[java] Java, How to specify absolute value and square roots

How do you specify in java how to make a square root and absolute value?

Here is what I have:

if(variable < 0){
    variable = variable + variable2;
}

But is there an easier way to get the absolute value in Java?

variable = |variable|

This question is related to java math

The answer is


import java.util.Scanner;
class my{
public static void main(String args[])
{
    Scanner x=new Scanner(System.in);
    double a,b,c=0,d;
    d=1;
    d=d/10;
    int e,z=0;
    System.out.print("Enter no:");
    a=x.nextInt();

    for(b=1;b<=a/2;b++)
    {
        if(b*b==a)
        {
            c=b;
            break;
        }
        else
        {
            if(b*b>a)
            break;
        }
    } 
    b--;
    if(c==0)
    {
       for(e=1;e<=15;e++)
        {
            while(b*b<=a && z==0)
            {
                if(b*b==a){c=b;z=1;}
                else
                {
                    b=b+d;          //*d==0.1 first time*//
                    if(b*b>=a){z=1;b=b-d;}
                }
            }
            d=d/10;
            z=0;
        }
        c=b;
    }

        System.out.println("Squre root="+c);





}    
}    

Try using Math.abs:

variableAbs = Math.abs(variable);

For square root use:

variableSqRt = Math.sqrt(variable);

int currentNum = 5;
double sqrRoot = 0.0;
int sqrRootInt = 0;



sqrRoot=Math.sqrt(currentNum);
sqrRootInt= (int)sqrRoot;

Math.sqrt(Math.abs(variable))

Couldn't be more simple can it ?


Use the java.lang.Math class, and specifically for absolute value and square root:, the abs() and sqrt() methods.