Computer Applications
Write a program by using a class with the following specifications:
Class name — Prime
Data members — private int n
Member functions:
- void input() — to input a number
- void checkprime() — to check and display whether the number is prime or not
Use a main function to create an object and call member methods of the class.
Java
Encapsulation & Inheritance in Java
34 Likes
Answer
import java.util.Scanner;
public class Prime
{
private int n;
public void input() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number: ");
n = in.nextInt();
}
public void checkprime() {
boolean isPrime = true;
if (n == 0 || n == 1)
isPrime = false;
else {
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime)
System.out.println("Prime Number");
else
System.out.println("Not a Prime Number");
}
public static void main(String args[]) {
Prime obj = new Prime();
obj.input();
obj.checkprime();
}
}
Variable Description Table
Program Explanation
Output

Answered By
17 Likes
Related Questions
Can a private member be accessed by
(a) a member of the same class?
(b) a member of other class?
(c) a function which is not a member function?
Show with the help of an example how the following base classes can be derived in class bill to fulfill the given requirement:
class elect { String n; float units; public void setvalue() { n = "SOURABH"; units = 6879; } }
Class bill uses data members charge and a member function to calculate the bill at the rate of 3.25 per unit and displays the charge. Class elect is inherited by class bill by using private visibility.
Write a program by using a class with the following specifications:
Class name — Factorial
Data members — private int n
Member functions:
- void input() — to input a number
- void fact() — to find and print the factorial of the number
Use a main function to create an object and call member methods of the class.
Write a program by using a class with the following specifications:
Class name — Salary
Data members — private int basic
Member functions:
- void input() — to input basic pay
- void display() — to find and print the following:
da = 30% of basic
hra = 10% of basic
gross = basic + da + hra
Use a main function to create an object and call member methods of the class.