Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
Now Reading
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Any beginner-level coding class includes learning to do the prime number program in Java. Despite its simplicity, students may initially find it confusing with the various programs involved in the process. This comprehensive guide explains with examples how to run the prime number program in Java using a variety of processes.
If you want to download this tutorial in PDF format for further reading: Download Tutorial PDF
Any natural number that is greater than 1 and divisible by 1 and itself only is termed a prime number. The isPrime() function is usually used in Java to determine whether the input number is prime or not.
All natural numbers can be categorized into 2 classes ⎯ prime numbers and composite numbers.
A prime number is defined as a natural number greater than 1 which is divisible by 1 and the number itself only. It has only 2 divisors. Some examples of prime numbers are 2,3,5,7,13,47,53…
On the other hand, composite or non-prime numbers are divisible by more than 2 numbers apart from 1 and itself.
Prime and co-prime numbers are distinctly different.
Prime Numbers | Co-prime Numbers |
Single number | Always come in pairs. |
Only factors are 1 and itself. | Highest common factor is always 1. |
Only primes. | Can be prime or composite. |
Examples - 17,23,67 | Examples- (17,25), (6,13), (8,15) |
We will be using the ‘isPrime’ method for finding out if a number is prime or not in the following program. However, in this method, you must name the .java file where you are writing the code as ‘PrimeCheker.java’ or it will cause an error during compilation.
If the ‘PrimeChecker’ class is not declared in a PrimeChecker.java file, it will cause the following error after execution:
Here is the program:
import java.util.Scanner;
public class PrimeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to check Prime or Not: ");
int number = scanner.nextInt();
if (isPrime(number)) {
System.out.println(number + " is a prime number");
} else {
System.out.println(number + " is not a prime number");
}
}
private static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
The prime number program in javascript begins with importing the Scanner class from java.util package using “import java.util.Scanner;”. Next, an instance of the Scanner class is created using “Scanner scanner = new Scanner(System.in);” which allows users to input a number. This is followed by the program prompt “System.out.print("Enter a number to check Prime or Not: ");”.
The program reads the user’s input using the “scanner.nextInt()” method. The entered number’s value is stored in an integer variable termed “number” using “int number = scanner.nextInt();”. The isPrime() method with the entered value is called an “argument” which checks whether the number is prime or not.
If the java program to print prime numbers in a given range returns true with the statement flashing “System.out.println(number + " is a prime number");” then the entered value is prime. If not, the isPrime() method returns false with the message “System.out.println(number + " is not a prime number");”. This indicates the entered value is not prime.
//Prime Number Program using Method in Java
public class prime{
static void checkPrime(int a){
int i,m=0,flag=0;
m=a/2;
if(a==0||a==1){
System.out.println(a+" is not prime number");
}else{
for(i=2;i<=m;i++){
if(a%i==0){
System.out.println(a+" is not prime number");
flag=1;
break;
}
}
if(flag==0) { System.out.println(a+" is prime number"); }
}//end of else
}
public static void main(String args[]){
checkPrime(10);
checkPrime(45);
checkPrime(67);
checkPrime(15);
}
}
Another way to write a program to check if a given number is prime or not is by using the “checkPrime” method. The checkPrime method takes an integer “a” as input and declares its variables “i,” “m,” and “flag” to 0. The value of “m” is set to “a/2,” and the program prints "a is not a prime number" when the variable is equal to 0 or 1. The program then enters a “for” loop that initializes “i” to 2 and continues until “i” is less than or equal to “m.”
Among the given inputs, only 67 returns as prime.
In the following program, we will be using the Lucas-Lehmer test for Mersenne primes to find out if a number is prime or not.
import java.math.BigInteger;
import java.util.Scanner;
public class PrimeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to check Prime or Not: ");
int number = scanner.nextInt();
BigInteger mersenneNumber = BigInteger.valueOf(2).pow(number).subtract(BigInteger.ONE);
BigInteger s = BigInteger.valueOf(4);
for (int i = 3; i <= number; i++) {
s = s.multiply(s).subtract(BigInteger.valueOf(2));
s = s.mod(mersenneNumber);
}
if (s.equals(BigInteger.ZERO)) {
System.out.println(number + " is a prime number");
} else {
System.out.println(number + " is not a prime number");
}
}
}
//Find prime numbers between two numbers
import java.util.Scanner;
public class prime {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the source number : ");
int source = sc.nextInt();
System.out.print("Enter the destination number : ");
int destination = sc.nextInt();
System.out.println("List of prime numbers between " + source + " and " + destination);
for (int i = source; i <= destination; i++) {
if (isPrime(i)) {
System.out.println(i);
}
}
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
In the following program, we will use the Sieve of Eratosthenes method to determine if a number is prime.
import java.util.Scanner;
public class PrimeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to check Prime or Not: ");
int number = scanner.nextInt();
boolean[] isPrime = new boolean[number + 1];
for (int i = 2; i <= number; i++) {
isPrime[i] = true;
}
for (int i = 2; i * i <= number; i++) {
if (isPrime[i]) {
for (int j = i * i; j <= number; j += i) {
isPrime[j] = false;
}
}
}
if (isPrime[number]) {
System.out.println(number + " is a prime number");
} else {
System.out.println(number + " is not a prime number");
}
}
}
import java.util.Scanner;
public class PrimeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to check Prime or Not: ");
int number = scanner.nextInt();
int count = 0;
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
count++;
break;
}
}
if (count == 0) {
System.out.println(number + " is a prime number");
} else {
System.out.println(number + " is not a prime number");
}
}
}
//Program to Check Prime Number Using a While Loop
import java.util.Scanner;
public class prime {
public static void main(String[] args) {
System.out.println("Enter a number to check Prime or Not");
Scanner obj = new Scanner(System.in);
int p = obj.nextInt();
int i = 2, c = 0;
while (i <= p / 2) {
if (p % i == 0) {
c++;
break;
}
i++;
}
if (c == 0) {
System.out.println(p + " is prime number");
} else {
System.out.println(p + " is not a prime number");
}
}
}
//Program to Check If the Number is Prime or not using a Flag Variable
import java.util.Scanner;
public class prime {
public static void main(String args[]){
int i,a=0,flag=0;
//int n=5;//it is the number to be checked
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter a number");
int n = myObj.nextInt(); // Read user input
System.out.println("the number is: " + n); // Output user input
a=n/2;
if(n==0||n==1){
System.out.println(n+" is not prime number");
}else{
for(i=2;i<=a;i++){
if(n%i==0){
System.out.println(n+" is not prime number");
flag=1;
break;
}
}
if(flag==0) { System.out.println(n+" is prime number"); }
}//end of else
}
}
Let us now further optimize the above code by using a boolean variable ‘isPrime’ rather than a flag variable. The boolean variable will help us determine if the number is a prime number or not, based on the value of ‘isPrime’.
import java.util.Scanner;
public class PrimeChecker {
public static void main(String args[]) {
int i, limit;
boolean isPrime = true;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (number == 0 || number == 1) {
System.out.println(number + " is not a prime number");
return;
}
limit = (int) Math.sqrt(number);
for (i = 2; i <= limit; i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(number + " is a prime number");
} else {
System.out.println(number + " is not a prime number");
}
}
}
//Program to Display the prime Numbers From 1 to 100
import java.util.Scanner;
public class prime {
public static void main(String[] args) {
System.out.println("Enter a number range to generate prime numbers in between");
Scanner obj = new Scanner(System.in);
int n1 = obj.nextInt();
int n2 = obj.nextInt();
if (n1 >= n2) {
System.out.println("Number2 must be greater then number1");
System.exit(0);
}
while (n1 <= n2) {
int i = 2, count = 0;
while (i <= n1 / 2) {
if (n1 % i == 0) {
count++;
break;
}
i++;
}
if (count == 0) {
System.out.println(n1 + " is prime number");
}
n1++;
}
}
}
To print prime numbers from 1 to 100 in Java, the program reads in two integer values from the user 1 and 100. An “if” statement checks if the first number is greater than or equal to the second.
//Find Prime Number Using Recursion
class prime {
static boolean isPrime(int p, int i) {
if (p <= 2) return (p == 2) ? true : false;
if (p % i == 0) return false;
if (i * i > p) return true;
return isPrime(p, i + 1);
}
public static void main(String[] args) {
int a = 11;
if (isPrime(a, 7)) {
System.out.println("The number is prime");
}
else {
System.out.println("The number is not prime");
}
}
}
Learning the prime number logic in Java is as essential as it is easy. To launch your coding career, you must learn the prime number program in Javascript since it serves as the base for future lessons. Enroll in a reliable programming course to build a strong foundation.
1. How do you handle large prime numbers in Java?
To deal with huge prime numbers in Java, we can use the BigInteger class. BigInteger is a java.math package that lets you conduct calculations on integers of arbitrary size.
2. Is 1 a prime number in Java?
Any positive integer greater than 1 divisible by only 1 and itself is termed a prime number. Since 1 does not meet these criteria, it is not a prime number.
3. How can we find a prime number program in Java using an array?
To print prime numbers from 1 to n in java, we can use the ‘Math.sqrt’ method. It helps limit the range of numbers to check their divisibility.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...