Online visitors

People learning around the world

Online

—

Visitors exploring W3Schools

Online visitors by country Circles show approximate country locations. The country list provides the visitor counts.

Circles represent countries, not exact visitor locations.

Country

Online

Loading country activity…

    Java Program to Toss a Coin

    This Java program is used to toss a coin using Java random class.

    • Java Math.random() returns a random value between 0.0 and 1.0 each time.
    • If value is below 0.5 then it's Heads or otherwise Tails.

    Example:

    public class JavaFlip {
            public static void main(String[] args) { 
                    if (Math.random() < 0.5){
                            System.out.println("Heads");
                    }else{
                            System.out.println("Tails");
                    }
            }
    }
    

    Program Output:

    Java-Flip

    Explanation:

    In this program, you will learn the code of how the tossing of a coin can be implemented in program. First of all, you have to declare a class name 'JavaFlip' and implement the main() method within this class. Now within this main() method declaration you have to use a conditional statement, in this program, the if() statement within which the Math.random () method, which is a predefined method for randomizing any value is used.

    java.lang.Math.random() gives a double value along with the positive sign, greater than or equal to 0.0 and less than 1.0. The resulting values of this predefined method are chosen pseudo-randomly with (approximately) uniform distribution from that range. It does not contains parameter.

    if (Math.random() < 0.5) statement checks whether Math.randon() method gives return value less than 0.5 or not. If t.he condition becomes true, System.out.println() prints the string "Heads" otherwise prints "Tails".



    Found This Page Useful? Share It!
    Get the Latest Tutorials and Updates
    Join us on Telegram

    Notifications

    Updates are enabled for this browser.

    Receive new tutorials, articles and learning resources. You can turn updates off anytime.