# Java Program to Toss a Coin

We will create a Java program tossing a coin simulation and randomize each result with Math.random. After that, we will test convergence of probebilities of heads and tails

Tossing a coin is a random event and probability is 0.5 for both sides. So lets use Math.random for generating a random number between 0 and 1 and depend on this random value, we will produce a coin value (head or tail).

``````double rand=Math.random();
String coin="";
if(rand < 0.5)
else
coin="Tail";

System.out.println(coin);``````

This code will produce a single head/tail simulation result. Let's increase the number of attempts and calculate probability of each result.

Example: Tossing a coin 10 times

``````for (int i=1; i<=10; i++)
{
double rand=Math.random();
String coin="";
if(rand < 0.5)
else
coin="Tail";

System.out.print(coin+" ");
}``````

Example: Tossing a coin 10 times and Calculating Probabilities

``````int head=0, tail=0;
for (int i=1; i<=10; i++)
{
double rand=Math.random();
String coin="";
if(rand < 0.5)
else
tail++;
}
System.out.println("Tail Probability:"+(tail)/10.0);	``````

My Output for 10 attempts:

Tail Probability:0.3

Example: Tossing a coin 1000 times and Calculating Probabilities

Note: we expect probabilities to converge to 0.5 as the number of attempts increases. For ease of use, let's create a variable ofor number of attempts.

``````double head=0, tail=0;
int numberOfAttempts=1000;
for (int i=1; i<=numberOfAttempts; i++)
{
double rand=Math.random();
String coin="";
if(rand < 0.5)
else
tail++;
}