BeginnersBook.in

Programming For Geeks

  • Home
  • All Tutorials
    • Learn C
    • Learn Python
  • Programs
    • Java Programs
    • C++ Programs
    • C Programs
  • Algorithms
    • Sorting
  • MCQ’s
    • MySQL
    • Operating System
  • WordPress
    • Genesis Pro Themes
    • Blogs
  • Tools
    • Direct Download Link Generator
    • HTML Compiler
  • How to
    • Web Examples
  • Write For Us

Java Program to Check Whether a Number is Prime or Not

December 7, 2018 By Mr. Robot

In this example, you will learn to check whether an entered number is a prime number or not.

A prime number is a whole number greater than 1 whose only factors are 1 and itself. A factor is a whole number that can be divided evenly into another number. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29. Numbers that have more than two factors are called composite numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Main {
    public static void main(String[] args) {
 
        int num = 29;
        boolean flag = false;
        for(int i = 2; i <= num/2; ++i)
        {
            // condition for nonprime number
            if(num % i == 0)
            {
                flag = true;
                break;
            }
        }
 
        if (!flag)
            System.out.println(num + " is a prime number.");
        else
            System.out.println(num + " is not a prime number.");
    }
}
When you run above program, the output will be following:
1
29 is a prime number.

Filed Under: Java examples

Related Posts

  • Java Program to Convert Decimal to Binary Number
  • Java program to remove duplicate elements in an array
  • Java Program to Print Characters

Recent Posts

  • Download Grand Theft Auto: Vice City Audio File | Highly Compressed
  • Grand Theft Auto: Vice City Game Download For PC | Full Setup
  • SQL SHOW DATABASES Statement
  • Direct view storage Tube (DVST) in Computer Graphics
  • CRT Color Monitor in Computer Graphics

Java Examples

  • More 300+ Java Programs
  • Hello, World
  • Add Two Numbers
  • Area of Triangle
  • Arithmetic Operation
  • Palindrome String
  • Upper or LowerCase
  • Leap Year
  • Toggle String
  • Automorphic Number
  • Neon Number
  • Strong Number
  • Spy Number

Pattern Examples

  • Simple (*) Pattern Programs
  • Tricky (*) Pattern Programs
  • Wave Pattern Programs

More…

  • C++ Programs
  • C Programs

Copyright © 2019 - BeginnersBook.in - All Right Reserved || Sitemap