Java Imp Questions
Java Imp Questions
2) Write a Java Program to Reverse a Number. Accept number using command line arguments.
Ans.
class ReverseNumber {
public static void main(String[] args) {
int num = [Link](args[0]);
int rev = 0;
while (num > 0) {
rev = rev * 10 + num % 10; //0*10+5%10
num /= 10; //
}
[Link]("Reversed Number = " + rev);
}
}
3)Write a Java program to print the sum of elements of the array. Also display array elements in
ascending order.
Ans.
import [Link].*;
class ArraySumSort {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter size of array: ");
int n = [Link]();
int arr[] = new int[n];
int sum = 0;
[Link]("Enter " + n + " elements:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
sum += arr[i];
}
[Link](arr);
[Link]("Sum = " + sum);
[Link]("Sorted Array = " + [Link](arr));
}
}
4) Write a Java program to print the factors of a given number. (Use Scanner class).
Ans.
import [Link].*;
class Factors {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
[Link]("Factors of " + num + ":");
for (int i = 1; i <= num; i++) {
if (num % i == 0)
[Link](i + " ");
}
}
}
5) Write a Java program to accept a number from user and print all prime numbers up to that number
(Use Buffered Reader class).
Ans.
import [Link].*;
class PrimeNumbers {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter limit: ");
int n = [Link]([Link]());
[Link]("Prime numbers up to " + n + ":");
for (int i = 2; i <= n; i++) {
boolean prime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
prime = false;
break;
}
}
if (prime) [Link](i + " ");
}
}
}
6)Write a Java Program to Display Armstrong Numbers Between range. Accept range from user.
Ans.
import [Link].*;
class ArmstrongRange {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter range (start end): ");
int start = [Link](), end = [Link]();
[Link]("Armstrong numbers between " + start + " and " + end + ":"); for (int i = start; i <=
end; i++) {
int num = i, sum = 0, temp = num;
int digits = [Link](num).length();
while (temp > 0) {
int d = temp % 10;
sum += [Link](d, digits);
temp /= 10;
}
if (sum == num) [Link](num + " ");
}
}
}
7) Write java program to check whether number is Perfect or not.
Ans.
import [Link].*;
class PerfectNumber {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
int sum = 0;
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) sum += i;
}
if (sum == num) [Link](num + " is a Perfect Number."); else [Link](num + " is
NOT a Perfect Number.");
}
}
8) Define a class student having rollno, name and percentage. Define Default and parameterized
constructor. Accept the 5 student details and display it. (Use this keyword).
Ans.
class Student {
int rollno;
String name;
double percentage;
Student() {
[Link] = 0;
[Link] = "Unknown";
[Link] = 0.0;
}
void display() {
[Link](rollno + " " + name + " " + percentage);
}
[Link]();
}
}
10) Write a program that reads on file name from the user, then displays information about whether
the file exists, whether the file is readable, whether the file is writable and the type of file.
Ans.
import [Link];
import [Link];
if ([Link]())
[Link]("Type : Regular file");
else if ([Link]())
[Link]("Type : Directory");
else
[Link]("Type : Unknown");
} else {
[Link]("File does not exist!");
}
[Link]();
}
}
11) Write a java program to accept a number from the user, if number is zero then throw user defined
exception ―Number is 0, otherwise check whether no is prime or not.
Ans.
import [Link].*;
if (num == 0)
throw new NumberIsZeroException("Number is 0");
if (isPrime(num))
[Link](num + " is Prime");
else
[Link](num + " is NOT Prime");
} catch (NumberIsZeroException e) {
[Link]("Exception: " + [Link]());
}
[Link]();
}
}
12)Write a java program to count number of digits, spaces and characters from a file.
Ans.
import [Link].*;
try {
// Open file (make sure the file exists in the same folder or give full path)
br = new BufferedReader(new FileReader("[Link]"));
13)Create a Hash table containing Employee name and Salary. Display the details of the hash table.
Ans.
import [Link].*;
[Link]("Raj", 45000.0);
[Link]("Anita", 55000.0);
[Link]("Vikram", 60000.0);
[Link]("Employee Details:");
for ([Link]<String, Double> entry : [Link]()) {
[Link]("Name: " + [Link]() + ", Salary: " + [Link]());
}
}
}
14)Write a program to accept ‘n’ integers from the user & store them in an Array List collection.
Display the elements of Array List.
Ans.
public class ArrayListIntegers {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
ArrayList<Integer> list = new ArrayList<>();
15)Write a java program to accept a number from user, if it zero then throw user defined Exception
“Number Is Zero”, otherwise calculate the sum of first and last digit of that number.(Use static
keyword)
Ans.
import [Link];
// User-defined exception
class NumberIsZeroException extends Exception {
public NumberIsZeroException(String message) {
super(message);
}
}
if (number == 0) {
throw new NumberIsZeroException("Number Is Zero");
}
16)Write a class Driver with attributes license_no, name, address and age. Initialize values through the
parameterized constructor. If age of Driver is less than 18 then user-defined exception should be
generated ―Age is below 18 years―
Ans.
import [Link].*;
class Driver {
String licenseNo, name, address;
int age;
Driver(String licenseNo, String name, String address, int age) throws AgeException {
if (age < 18) throw new AgeException("Age is below 18 years");
[Link] = licenseNo;
[Link] = name;
[Link] = address;
[Link] = age;
}
void display() {
[Link]("License: " + licenseNo + ", Name: " + name + ", Address: " + address + ", Age: "
+ age);
}
}
public class DriverAgeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try {
[Link]("Enter License No: ");
String lic = [Link]();
[Link]("Enter Name: ");
String name = [Link]();
[Link]("Enter Address: ");
String addr = [Link]();
[Link]("Enter Age: ");
int age = [Link]();
} catch (AgeException e) {
[Link]("Exception: " + [Link]());
}
[Link]();
}
}
17) Write a java program that displays the number of characters, lines and words of a file.
Ans.
import [Link].*;
MyNumber() {
num = 0;
}
MyNumber(int n) {
[Link] = n;
}
2)Write a java program to design a following GUI. Use appropriate Layout and Components
Ans.
import [Link].*;
import [Link].*;
public RegistrationForm() {
// Frame title
super("Registration Form");
// Set layout
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
[Link] = new Insets(8, 8, 8, 8);
[Link] = [Link];
// Create components
JLabel lblTitle = new JLabel("Registration Form");
[Link](new Font("Arial", [Link], 16));
[Link] = 1;
[Link] = 0; [Link] = 1;
add(lblName, gbc);
[Link] = 1;
add(txtName, gbc);
[Link] = 0; [Link] = 2;
add(lblMobile, gbc);
[Link] = 1;
add(txtMobile, gbc);
[Link] = 0; [Link] = 3;
add(lblClass, gbc);
[Link] = 1;
JPanel classPanel = new JPanel();
[Link](rbFY);
[Link](rbSY);
[Link](rbTY);
add(classPanel, gbc);
[Link] = 0; [Link] = 4;
add(lblGender, gbc);
[Link] = 1;
JPanel genderPanel = new JPanel();
[Link](rbFemale);
[Link](rbMale);
add(genderPanel, gbc);
// Frame settings
setSize(400, 350);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
class Account {
int accno;
String accname;
double balance;
Account(int accno, String accname, double balance) {
[Link] = accno;
[Link] = accname;
[Link] = balance;
}
void display() {
[Link](accno + " " + accname + " " + balance);
}
sortAccount(arr);
4) Write a class Student with attributes roll no, name, age and
course. Initialize values through parameterized constructor. If age
of student is not in between 15 and 21 then generate userdefined
exception ―Age Not Within The Range. If name contains numbers or
special symbols raise exception ―Name not valid
Ans.
import [Link].*;
class Student {
int rollno, age;
String name, course;
[Link] = rollno;
[Link] = name;
[Link] = age;
[Link] = course;
}
void display() {
[Link]("Roll: " + rollno + ", Name: " + name + ",
Age: " + age + ", Course: " + course);
}
}
5) Write a program which define class Product with data member as
id, name and price. Store the information of 5 products and display
the name of product having minimum price (Use array of object).
Ans.
class Product {
int id;
String name;
double price;
6) Define an Interface Shape with abstract method area (). Write a
java program to calculate an area of Circle and Sphere. (Use final
keyword).
Ans.
interface Shape {
double area();
}
Circle(double r) {
radius = r;
}
public double area() {
return PI * radius * radius;
}
}
Sphere(double r) {
radius = r;
}
[Link](2, moreColors);
8) Write a program which define class Employee with data member as
id, name and salary Store the information of 'n' employees and
display the name of employee having maximum salary (Use array of
object).
Ans.
import [Link].*;
class Employee {
int id;
String name;
double salary;
class Customer {
int id;
String name, address, mobile;
[Link](id);
[Link](name);
[Link](addr);
[Link](mob);
}
[Link]();
10)Create an abstract class Shape with methods area & volume. Derive
a class Cylinder (radius, height). Calculate area and volume
Ans.
interface Operation {
double PI = 3.142;
double area();
double volume();
}
Circle(double r) {
radius = r;
}
Cylinder(double r, double h) {
radius = r;
height = h;
}
void display() {
[Link](dd + "-" + mm + "-" + yy);
}
void display() {
[Link]("Name: " + name + ", Salary: " + salary +
", Project: " + projectName + ", Language: " +
progLanguage);
}
}
13) Define a class Student with attributes rollno and name. Define
default and parameterized constructor. Keep the count of Objects
created. Create objects using parameterized constructor and display
the object count after each object is created.
Ans.
class Student {
int rollno;
String name;
static int count = 0;
Student() {
count++;
}
class Customer {
int id;
String name, address, mobile;
[Link](id);
[Link](name);
[Link](addr);
[Link](mob);
}
[Link]();
Ans.
import [Link].*;
import [Link].*;
add(name); add(txtName);
add(lblDose); add(c1); add(c2);
add(lblVaccine); add(r1); add(r2); add(r3);
add(lblDate); add(txtDate);
add(new JLabel("")); add(btnSave);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
double area() {
return 2 * [Link] * radius * (radius + height);
}
double volume() {
return [Link] * radius * radius * height;
}
void display() {
[Link]("Area: " + area() + " Volume: " +
volume());
}
}
17) Write a package game which will have 2 classes Indoor &
Outdoor. Use a function display () to generate the list of players
for the specific game. Use default ¶meterized constructor.
Ans.
File 1: game/[Link]
package game;
public class Indoor {
String name;
public Indoor() {
name = "Chess";
}
public Indoor(String n) {
name = n;
}
public void display() {
[Link]("Indoor Game: " + name);
}
}
File 2: game/[Link]
package game;
public class Outdoor {
String name;
public Outdoor() {
name = "Cricket";
}
public Outdoor(String n) {
name = n;
}
public void display() {
[Link]("Outdoor Game: " + name);
}
}
Main Program
import game.*;
[Link]();
[Link]();
[Link]();
[Link]();
}
}
class Vehicle {
String company;
double price;
void display() {
[Link]("Company: " + company + ", Price: " +
price);
}
}
void display() {
[Link]();
[Link]("Mileage: " + mileage + " km/l");
}
}
void display() {
[Link]();
[Link]("Capacity: " + capacity + " tons");
}
}
if (type == 1) {
[Link]("Enter mileage: ");
double mileage = [Link]();
vehicles[i] = new LightMotorVehicle(company, price,
mileage);
} else {
[Link]("Enter capacity in tons: ");
double capacity = [Link]();
vehicles[i] = new HeavyMotorVehicle(company, price,
capacity);
}
}
19) Create a java application to store city names and their STD
codes using an appropriate collection. i. Add a new city and its code
(No duplicates) ii. Remove a city from the collection iii. Search for
a cityname and display the code.
Ans.
import [Link].*;
while (true) {
[Link]("\n1. Add City\n2. Remove City\n3.
Search City\n4. Display All\n5. Exit");
[Link]("Enter choice: ");
int choice = [Link]();
[Link]();
switch (choice) {
case 1:
[Link]("Enter city: ");
String city = [Link]();
[Link]("Enter STD code: ");
int code = [Link]();
[Link](city, code);
break;
case 2:
[Link]("Enter city to remove: ");
city = [Link]();
[Link](city);
break;
case 3:
[Link]("Enter city to search: ");
city = [Link]();
if ([Link](city))
[Link]("STD Code: " +
[Link](city));
else
[Link]("City not found!");
break;
case 4:
[Link]("City Details: " + map);
break;
case 5:
[Link]();
return;
}
}
}
}
package Series;
public class Fibonacci {
public void print(int n) {
int a = 0, b = 1;
[Link]("Fibonacci: ");
for (int i = 1; i <= n; i++) {
[Link](a + " ");
int c = a + b;
a = b;
b = c;
}
[Link]();
}
}
File 2: Series/[Link]
package Series;
public class Cube {
public void print(int n) {
[Link]("Cubes: ");
for (int i = 1; i <= n; i++) {
[Link]((i * i * i) + " ");
}
[Link]();
}
}
File 3: Series/[Link]
package Series;
public class Square {
public void print(int n) {
[Link]("Squares: ");
for (int i = 1; i <= n; i++) {
[Link]((i * i) + " ");
}
[Link]();
}
}
Main Program
import Series.*;
import [Link].*;
new Fibonacci().print(n);
new Cube().print(n);
new Square().print(n);
}
}
21) Write a Java program to calculate area of Circle, Triangle &
Rectangle. (Use Method Overloading).
Ans.
import [Link];
switch (choice) {
case 1:
[Link]("Enter radius of circle: ");
double r = [Link]();
[Link]("Area of Circle = " + area(r));
break;
case 2:
[Link]("Enter length of rectangle: ");
double l = [Link]();
[Link]("Enter breadth of rectangle: ");
double b = [Link]();
[Link]("Area of Rectangle = " + area(l,
b));
break;
case 3:
[Link]("Enter base of triangle: ");
double base = [Link]();
[Link]("Enter height of triangle: ");
double h = [Link]();
[Link]("Area of Triangle = " + area(base,
h, true));
break;
default:
[Link]("Invalid choice!");
}
[Link]();
}
}
class Employee {
int id;
String name;
double salary;
Employee() {}
void display() {
[Link]("ID: " + id + ", Name: " + name + ",
Salary: " + salary);
}
}
double totalSalary() {
return salary + bonus;
}
void display() {
[Link]();
[Link]("Bonus: " + bonus + ", Total Salary: " +
totalSalary());
}
}
Ans.
import [Link].*;
import [Link].*;
import [Link].*;
LoginGUI() {
setTitle("Login");
setSize(300, 200);
setLayout(new GridLayout(3, 2, 10, 10));
add(lblUser);
add(txtUser);
add(lblPass);
add(txtPass);
add(btnLogin);
add(btnReset);
[Link](this);
[Link](this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
// User-defined Exception
class CovidPositiveException extends Exception {
public CovidPositiveException(String message) {
super(message);
}
}
// Patient class
class Patient {
String patient_name;
int patient_age;
double patient_oxy_level;
double patient_HRCT_report;
// Main class
public class PatientDetails {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Exception Handling
try {
[Link]();
} catch (CovidPositiveException e) {
[Link]("\nException: " + [Link]());
} finally {
[Link]();
}
}
}
25) Construct a Linked List containing name: CPP, Java, Python and
PHP. Then extend your java program to do the following: i. ii.
Display the contents of the List using an Iterator. Display the
contents of the List in reverse order using a List Iterator.
Ans.
import [Link].*;
while ([Link]()) {
[Link]([Link]());
}
}
}
26) Write a java program to accept Doctor Name from the user and
check whether it is valid or not. (It should not contain digits and
special symbol) If it is not valid then throw user defined Exception
– Name is Invalid – otherwise display it
Ans.
import [Link].*;
if ()
throw new InvalidNameException("Name is Invalid");
} catch (InvalidNameException e) {
[Link]("Exception: " + [Link]());
}
[Link]();
}
}
27) Define a class MyNumber having one private integer data member.
Write a default constructor initialize it to 0 and another
constructor to initialize it to a value. Write methods isNegative,
isPositive, isOdd, isEven. Use command line argument to pass a value
to the object and perform the above operations.
Ans.
class MyNumber {
private int num;
MyNumber() {
num = 0;
}
MyNumber(int n) {
[Link] = n;
}
Ans.
import [Link].*;
import [Link].*;
import [Link].*;
LanguageSelector() {
setTitle("Programming Language Selector");
setSize(300, 200);
setLayout(new FlowLayout());
add(combo);
add(btnShow);
add(lblResult);
[Link](this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
// Abstract methods
abstract double area();
abstract double volume();
}
Cone(double r, double h) {
super(r, h); // using super to call parent constructor
}
double area() {
double slantHeight = [Link]((radius * radius) + (height *
height));
return [Link] * radius * (radius + slantHeight);
}
double volume() {
return ([Link] * radius * radius * height) / 3;
}
}
Cylinder(double r, double h) {
super(r, h); // using super to call parent constructor
}
double area() {
return 2 * [Link] * radius * (height + radius);
}
double volume() {
return [Link] * radius * radius * height;
}
}
// Main class
public class ShapeDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
switch (choice) {
case 1:
s = new Cone(r, h);
[Link]("\n--- Cone ---");
[Link]("Area : " + [Link]());
[Link]("Volume : " + [Link]());
break;
case 2:
s = new Cylinder(r, h);
[Link]("\n--- Cylinder ---");
[Link]("Area : " + [Link]());
[Link]("Volume : " + [Link]());
break;
default:
[Link]("Invalid choice!");
}
[Link]();
}
}