Saturday, November 1, 2014

Java Random Pro



Find square root of a number using Math

public class FindSquareRootExample
{
public static void main(String[] args)
{
System.out.println(Math.sqrt(9));
System.out.println(Math.sqrt(25.5));
   }
}

Generate Random Int Within Given Range

public class GenerateRandomIntByRange
 {
public static void main(String args[])
 {
int random = (int)(Math.random()* 10 ) + 5;
System.out.println(random);
   }
}

Generate random numbers using Math

public class GenerateRandomNumbers
{
public static void main(String[] args)
{
System.out.println("Random numbers between 0.0 and 1.0 are,");
for(int i=0; i < 5 ; i++)
System.out.println("Random Number ["+ (i+1) + "] : " + Math.random());
System.out.println("Random numbers between 1 and 100 are,");
for(int i=0; i < 5 ; i++)
System.out.println("Random Number ["+ (i+1) + "] : " + (int)(Math.random()*100));
     }
}

Round Java float and double numbers using Math

public class RounFloatDoubleNumbersExample
 {
public static void main(String[] args)
{

System.out.println(Math.round(10f));
System.out.println(Math.round(20.5f));
 
System.out.println(Math.round(20.5f));
System.out.println(Math.round(-19.4f));

System.out.println(Math.round(-23.5f));
  }
}

Convert Java String to Short

public class StringToShortExample
{
public static void main(String[] args)
{
Short sObj1 = new Short("100");
System.out.println(sObj1);
String str = "100";
Short sObj2 = Short.valueOf(str);
System.out.println(sObj2);
   }
}

Convert Short object to String object

public class ShortToStringExample
{
public static void main(String[] args)
{
short s = 10;
Short sObj = new Short(s);
String str = sObj.toString();
System.out.println("Short converted to String as " + str);
    }
}

No comments:

Post a Comment