0% found this document useful (0 votes)
12 views45 pages

Java Imp Questions

The document contains a series of Java programming tasks, each accompanied by a code solution. The tasks range from generating multiplication tables, reversing numbers, and calculating sums, to more advanced topics like exception handling and GUI design. Each task demonstrates different programming concepts and techniques in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views45 pages

Java Imp Questions

The document contains a series of Java programming tasks, each accompanied by a code solution. The tasks range from generating multiplication tables, reversing numbers, and calculating sums, to more advanced topics like exception handling and GUI design. Each task demonstrates different programming concepts and techniques in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1) Write a Java program to accept a number from user and generate multiplication table of a number.

Accept number using Buffered Reader class.


Ans.
import [Link].*;
class MultiplicationTable {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter a number: ");
int num = [Link]([Link]());
[Link]("Multiplication Table of " + num + ":");
for (int i = 1; i <= 10; i++) {
[Link](num + " x " + i + " = " + (num * i));
}
}
}

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;
}

Student(int rollno, String name, double percentage) {


[Link] = rollno;
[Link] = name;
[Link] = percentage;
}

void display() {
[Link](rollno + " " + name + " " + percentage);
}

public static void main(String[] args) {


Student s[] = new Student[5];
s[0] = new Student(1, "A", 85);
s[1] = new Student(2, "B", 75);
s[2] = new Student(3, "C", 92);
s[3] = new Student(4, "D", 68);
s[4] = new Student(5, "E", 88);

for (Student st : s) [Link]();


}
}

9) Write a Java program to display Fibonacci series using function.


Ans.
import [Link];
public class FibonacciSeries {

// Function to display Fibonacci series


static void displayFibonacci(int n) {
int first = 0, second = 1, next;
[Link]("Fibonacci Series: ");

for (int i = 1; i <= n; i++) {


[Link](first + " ");
next = first + second;
first = second;
second = next;
}
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

[Link]("Enter number of terms: ");


int terms = [Link]();

displayFibonacci(terms); // function call

[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];

public class FileInfo {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter file name (with path if needed): ");


String fileName = [Link]();

File file = new File(fileName);

// Check if file exists


if ([Link]()) {
[Link]("\nFile Information:");
[Link]("-----------------");
[Link]("File exists: Yes");
[Link]("Readable : " + [Link]());
[Link]("Writable : " + [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].*;

class NumberIsZeroException extends Exception {


NumberIsZeroException(String msg) {
super(msg);
}
}

public class PrimeCheckException {


static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) return false;
}
return true;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
try {
[Link]("Enter a number: ");
int num = [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].*;

public class FileCount {


public static void main(String[] args) {
BufferedReader br = null;

try {
// Open file (make sure the file exists in the same folder or give full path)
br = new BufferedReader(new FileReader("[Link]"));

int digits = 0, spaces = 0, chars = 0;


int ch;

while ((ch = [Link]()) != -1) { // read character by character


char c = (char) ch;
if ([Link](c))
digits++;
else if ([Link](c))
spaces++;
else
chars++;
}

[Link]("Number of digits : " + digits);


[Link]("Number of spaces : " + spaces);
[Link]("Number of characters : " + chars);
}
catch (FileNotFoundException e) {
[Link]("File not found!");
}
catch (IOException e) {
[Link]("Error reading file!");
}
finally {
try {
if (br != null)
[Link]();
}
catch (IOException e) {
[Link]("Error closing file!");
}
}
}
}

13)Create a Hash table containing Employee name and Salary. Display the details of the hash table.
Ans.
import [Link].*;

public class EmployeeHashTable {


public static void main(String[] args) {
Hashtable<String, Double> ht = new Hashtable<>();

[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<>();

[Link]("Enter number of integers: ");


int n = [Link]();

for (int i = 0; i < n; i++) {


[Link]("Enter integer " + (i + 1) + ": ");
[Link]([Link]());
}

[Link]("\nArrayList Elements: " + list);


[Link]();
}
}

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);
}
}

public class SumFirstLast {


static int number; // using static keyword

// static method to calculate sum of first and last digit


static int sumOfFirstAndLastDigit(int num) {
int lastDigit = num % 10;
int firstDigit = num;
while (firstDigit >= 10) {
firstDigit /= 10;
}
return firstDigit + lastDigit;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
try {
[Link]("Enter a number: ");
number = [Link]();

if (number == 0) {
throw new NumberIsZeroException("Number Is Zero");
}

int sum = sumOfFirstAndLastDigit([Link](number));


[Link]("Sum of first and last digit = " + sum);
}
catch (NumberIsZeroException e) {
[Link]("Exception caught: " + [Link]());
}
finally {
[Link]();
}
}
}

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 AgeException extends Exception {


AgeException(String msg) {
super(msg);
}
}

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]();

Driver d = new Driver(lic, name, addr, 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].*;

public class FileCount {


public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("[Link]"));
int lines = 0, words = 0, chars = 0;
String line;

while ((line = [Link]()) != null) {


lines++;
chars += [Link]();
words += [Link]("\\s+").length;
}
[Link]();

[Link]("Lines: " + lines);


[Link]("Words: " + words);
[Link]("Characters: " + chars);
} catch (Exception e) {
[Link]("Error: " + e);
}
}
}
1) 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;
}

boolean isNegative() { return num < 0; }


boolean isPositive() { return num > 0; }
boolean isOdd() { return num % 2 != 0; }
boolean isEven() { return num % 2 == 0; }

public static void main(String[] args) {


int val = [Link](args[0]);
MyNumber obj = new MyNumber(val);

[Link]("Number: " + val);


[Link]("Is Negative? " + [Link]());
[Link]("Is Positive? " + [Link]());
[Link]("Is Odd? " + [Link]());
[Link]("Is Even? " + [Link]());
}
}

2)Write a java program to design a following GUI. Use appropriate Layout and Components

Ans.
import [Link].*;
import [Link].*;

public class RegistrationForm extends JFrame {

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));

JLabel lblName = new JLabel("User Name:");


JTextField txtName = new JTextField(15);

JLabel lblMobile = new JLabel("Mobile Number:");


JTextField txtMobile = new JTextField(15);

JLabel lblClass = new JLabel("Class:");


JRadioButton rbFY = new JRadioButton("FY");
JRadioButton rbSY = new JRadioButton("SY");
JRadioButton rbTY = new JRadioButton("TY");

ButtonGroup classGroup = new ButtonGroup();


[Link](rbFY);
[Link](rbSY);
[Link](rbTY);

JLabel lblGender = new JLabel("Gender:");


JRadioButton rbFemale = new JRadioButton("Female");
JRadioButton rbMale = new JRadioButton("Male");

ButtonGroup genderGroup = new ButtonGroup();


[Link](rbFemale);
[Link](rbMale);

JButton btnSave = new JButton("Save");


JButton btnUpdate = new JButton("Update");
JButton btnDelete = new JButton("Delete");

// Add components to frame


[Link] = 0; [Link] = 0; [Link] = 2;
add(lblTitle, gbc);

[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);

[Link] = 0; [Link] = 5; [Link] = 2;


JPanel buttonPanel = new JPanel();
[Link](btnSave);
[Link](btnUpdate);
[Link](btnDelete);
add(buttonPanel, gbc);

// Frame settings
setSize(400, 350);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


new RegistrationForm();
}
}

3)​ Write a program to create class Account (accno, accname,


balance). Create an array of 'n' Account objects. Define static
method “sortAccount” which sorts the array on the basis of balance.
Display account details in sorted order.
Ans.
import [Link].*;

class Account {
int accno;
String accname;
double balance;
Account(int accno, String accname, double balance) {
[Link] = accno;
[Link] = accname;
[Link] = balance;
}

static void sortAccount(Account arr[]) {


[Link](arr, [Link](a -> [Link]));
}

void display() {
[Link](accno + " " + accname + " " + balance);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter number of accounts: ");
int n = [Link]();
Account arr[] = new Account[n];

for (int i = 0; i < n; i++) {


[Link]("Enter accno, name, balance: ");
arr[i] = new Account([Link](), [Link](),
[Link]());
}

sortAccount(arr);

[Link]("\nAccounts sorted by balance:");


for (Account a : arr) [Link]();
}
}

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 StudentException extends Exception {


StudentException(String msg) {
super(msg);
}
}

class Student {
int rollno, age;
String name, course;

Student(int rollno, String name, int age, String course) throws


StudentException {
if (age < 15 || age > 21)
throw new StudentException("Age Not Within The Range");
if (![Link]("[a-zA-Z ]+"))
throw new StudentException("Name not valid");

[Link] = rollno;
[Link] = name;
[Link] = age;
[Link] = course;
}

void display() {
[Link]("Roll: " + rollno + ", Name: " + name + ",
Age: " + age + ", Course: " + course);
}
}

public class StudentCheck {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try {
[Link]("Enter Roll No: ");
int roll = [Link]();
[Link]();
[Link]("Enter Name: ");
String name = [Link]();
[Link]("Enter Age: ");
int age = [Link]();
[Link]();
[Link]("Enter Course: ");
String course = [Link]();

Student s = new Student(roll, name, age, course);


[Link]();
} catch (StudentException e) {
[Link]("Exception: " + [Link]());
}
[Link]();
}
}

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;

Product(int id, String name, double price) {


[Link] = id;
[Link] = name;
[Link] = price;
}

public static void main(String[] args) {


Product p[] = new Product[5];
p[0] = new Product(1, "Pen", 10);
p[1] = new Product(2, "Pencil", 5);
p[2] = new Product(3, "Book", 50);
p[3] = new Product(4, "Bag", 300);
p[4] = new Product(5, "Eraser", 2);

Product min = p[0];


for (int i = 1; i < 5; i++) {
if (p[i].price < [Link]) min = p[i];
}

[Link]("Product with Minimum Price: " + [Link]);


}
}

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();
}

class Circle implements Shape {


final double PI = 3.142;
double radius;

Circle(double r) {
radius = r;
}
public double area() {
return PI * radius * radius;
}
}

class Sphere implements Shape {


final double PI = 3.142;
double radius;

Sphere(double r) {
radius = r;
}

public double area() {


return 4 * PI * radius * radius;
}
}

public class ShapeTest {


public static void main(String[] args) {
Circle c = new Circle(5);
Sphere s = new Sphere(5);
[Link]("Circle Area: " + [Link]());
[Link]("Sphere Area: " + [Link]());
}
}

7)​ Construct a linked List containing names of colours: red, blue,


yellow and orange. Then extend the program to do the following:
i.​ Display the contents of the List using an Iterator
ii.​ Display the contents of the List in reverse order using a
ListIterator
[Link] another list containing pink and green. Insert the
elements of this list between blue and yellow.
Ans.
import [Link].*;

public class LinkedListColors {


public static void main(String[] args) {
LinkedList<String> colors = new LinkedList<>();
[Link]("Red");
[Link]("Blue");
[Link]("Yellow");
[Link]("Orange");
// i) Display using Iterator
[Link]("Colors using Iterator:");
Iterator<String> it = [Link]();
while ([Link]()) {
[Link]([Link]());
}

// ii) Display in reverse using ListIterator


[Link]("\nColors in Reverse:");
ListIterator<String> lit =
[Link]([Link]());
while ([Link]()) {
[Link]([Link]());
}

// iii) Insert pink, green between Blue and Yellow


LinkedList<String> moreColors = new LinkedList<>();
[Link]("Pink");
[Link]("Green");

[Link](2, moreColors);

[Link]("\nAfter inserting Pink and Green:");


for (String c : colors) {
[Link](c);
}
}
}

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;

Employee(int id, String name, double salary) {


[Link] = id;
[Link] = name;
[Link] = salary;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter number of employees: ");
int n = [Link]();
Employee e[] = new Employee[n];

for (int i = 0; i < n; i++) {


[Link]("Enter id, name, salary: ");
e[i] = new Employee([Link](), [Link](), [Link]());
}

Employee max = e[0];


for (int i = 1; i < n; i++) {
if (e[i].salary > [Link]) max = e[i];
}

[Link]("Employee with Max Salary: " + [Link]);


}
}

9)​ Create a package “utility”. Define a class Capital String


under “utility” package which will contain a method to return
String with first letter capital. Create a Person class (members –
name, city) outside the package. Display the person’s name with
first letter as capital by making use of Capital String.
Ans.
import [Link].*;
import [Link].*;

class Customer {
int id;
String name, address, mobile;

Customer(int id, String name, String address, String mobile) {


[Link] = id;
[Link] = name;
[Link] = address;
[Link] = mobile;
}
}

public class CustomerFile {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try {
DataOutputStream dos = new DataOutputStream(new
FileOutputStream("[Link]"));

[Link]("Enter number of customers: ");


int n = [Link]();
[Link]();

for (int i = 0; i < n; i++) {


[Link]("Enter ID: ");
int id = [Link](); [Link]();
[Link]("Enter Name: ");
String name = [Link]();
[Link]("Enter Address: ");
String addr = [Link]();
[Link]("Enter Mobile: ");
String mob = [Link]();

[Link](id);
[Link](name);
[Link](addr);
[Link](mob);
}
[Link]();

DataInputStream dis = new DataInputStream(new


FileInputStream("[Link]"));
[Link]("\nCustomer Details:");
try {
while (true) {
int id = [Link]();
String name = [Link]();
String addr = [Link]();
String mob = [Link]();
[Link](id + " " + name + " " + addr +
" " + mob);
}
} catch (EOFException e) {
[Link]();
}
} catch (Exception e) {
[Link]("Error: " + e);
}
[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();
}

class Circle implements Operation {


double radius;

Circle(double r) {
radius = r;
}

public double area() {


return PI * radius * radius;
}

public double volume() {


return 0; // not applicable
}
}

class Cylinder implements Operation {


double radius, height;

Cylinder(double r, double h) {
radius = r;
height = h;
}

public double area() {


return 2 * PI * radius * (radius + height);
}

public double volume() {


return PI * radius * radius * height;
}
}

public class OperationTest {


public static void main(String[] args) {
Circle c = new Circle(5);
Cylinder cy = new Cylinder(5, 10);
[Link]("Circle Area: " + [Link]());
[Link]("Cylinder Area: " + [Link]() + " Volume:
" + [Link]());
}
}

11)Write a program create class as MyDate with dd,mm,yy as data


members. Write parameterized constructor. Display the date in
dd-mm-yy format. (Use this keyword).
Ans.
class MyDate {
int dd, mm, yy;

MyDate(int dd, int mm, int yy) {


[Link] = dd;
[Link] = mm;
[Link] = yy;
}

void display() {
[Link](dd + "-" + mm + "-" + yy);
}

public static void main(String[] args) {


MyDate d = new MyDate(22, 8, 2025);
[Link]();
}
}

12)​ Write a Java program to create a super class Employee (members


– name, salary). Derive a sub-class as Developer (member –
projectname). Derive a sub-class Programmer (member – proglanguage)
from Developer. Create object of Programmer and display the details
of it. Implement this multilevel inheritance with appropriate
constructor and methods.
Ans.
class Employee {
String name;
double salary;

Employee(String name, double salary) {


[Link] = name;
[Link] = salary;
}
}

class Developer extends Employee {


String projectName;

Developer(String name, double salary, String projectName) {


super(name, salary);
[Link] = projectName;
}
}
class Programmer extends Developer {
String progLanguage;

Programmer(String name, double salary, String projectName, String


progLanguage) {
super(name, salary, projectName);
[Link] = progLanguage;
}

void display() {
[Link]("Name: " + name + ", Salary: " + salary +
", Project: " + projectName + ", Language: " +
progLanguage);
}
}

public class TestProgrammer {


public static void main(String[] args) {
Programmer p = new Programmer("Raj", 60000, "BankApp",
"Java");
[Link]();
}
}

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++;
}

Student(int rollno, String name) {


[Link] = rollno;
[Link] = name;
count++;
[Link]("Object Count: " + count);
}

public static void main(String[] args) {


Student s1 = new Student(1, "A");
Student s2 = new Student(2, "B");
Student s3 = new Student(3, "C");
}
}
14)​ Write a java program to accept details of n customers (c_id,
cname, address, mobile_no) from user and store it in a file (Use
DataOutputStream class). Display the details of customers by reading
it from file. (Use DataInputStream class).
Ans.
import [Link].*;
import [Link].*;

class Customer {
int id;
String name, address, mobile;

Customer(int id, String name, String address, String mobile) {


[Link] = id;
[Link] = name;
[Link] = address;
[Link] = mobile;
}
}

public class CustomerFile {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try {
DataOutputStream dos = new DataOutputStream(new
FileOutputStream("[Link]"));

[Link]("Enter number of customers: ");


int n = [Link]();
[Link]();

for (int i = 0; i < n; i++) {


[Link]("Enter ID: ");
int id = [Link](); [Link]();
[Link]("Enter Name: ");
String name = [Link]();
[Link]("Enter Address: ");
String addr = [Link]();
[Link]("Enter Mobile: ");
String mob = [Link]();

[Link](id);
[Link](name);
[Link](addr);
[Link](mob);
}
[Link]();

DataInputStream dis = new DataInputStream(new


FileInputStream("[Link]"));
[Link]("\nCustomer Details:");
try {
while (true) {
int id = [Link]();
String name = [Link]();
String addr = [Link]();
String mob = [Link]();
[Link](id + " " + name + " " + addr +
" " + mob);
}
} catch (EOFException e) {
[Link]();
}
} catch (Exception e) {
[Link]("Error: " + e);
}
[Link]();
}
}

15)​ Write a java program to design a following GUI. Use appropriate


Layout and Components.

Ans.
import [Link].*;
import [Link].*;

class VaccinationForm extends JFrame {


VaccinationForm() {
setTitle("Vaccination Details");
setSize(400, 300);
setLayout(new GridLayout(6, 2, 5, 5));

JLabel name = new JLabel("Name:");


JTextField txtName = new JTextField();

JLabel lblDose = new JLabel("Dose:");


JCheckBox c1 = new JCheckBox("1st Dose");
JCheckBox c2 = new JCheckBox("2nd Dose");

JLabel lblVaccine = new JLabel("Vaccine:");


JRadioButton r1 = new JRadioButton("Covishield");
JRadioButton r2 = new JRadioButton("Covaxin");
JRadioButton r3 = new JRadioButton("Sputnik V");

ButtonGroup bg = new ButtonGroup();


[Link](r1); [Link](r2); [Link](r3);

JLabel lblDate = new JLabel("Date:");


JTextField txtDate = new JTextField();

JButton btnSave = new JButton("Save");

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);
}

public static void main(String[] args) {


new VaccinationForm();
}
}

16)​ Define an interface “Operation” which has methods area (),


volume (). Define a constant PI having a value 3.142. Create a class
circle (member – radius), cylinder (members – radius, height) which
implements this interface. Calculate and display the area and volume.
Ans.
abstract class Shape {
abstract double area();
abstract double volume();
}

class Cylinder extends Shape {


double radius, height;
Cylinder(double r, double h) {
radius = r;
height = h;
}

double area() {
return 2 * [Link] * radius * (radius + height);
}

double volume() {
return [Link] * radius * radius * height;
}

void display() {
[Link]("Area: " + area() + " Volume: " +
volume());
}
}

public class TestCylinder {


public static void main(String[] args) {
Cylinder c = new Cylinder(5, 10);
[Link]();
}
}

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 &parameterized 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.*;

public class GameTest {


public static void main(String[] args) {
Indoor i1 = new Indoor();
Indoor i2 = new Indoor("Carrom");
Outdoor o1 = new Outdoor();
Outdoor o2 = new Outdoor("Football");

[Link]();
[Link]();
[Link]();
[Link]();
}
}

18)​ Write a Java program to create a super class Vehicle having


members Company and Price. Derive two different classes
LightMotorVehicle (mileage) and HeavyMotorVehicle (capacity_in_tons).
Accept the information for “n” vehicles and display the information
in appropriate form. While taking data, ask user about the type of
vehicle first
Ans.
import [Link];

class Vehicle {
String company;
double price;

Vehicle(String company, double price) {


[Link] = company;
[Link] = price;
}

void display() {
[Link]("Company: " + company + ", Price: " +
price);
}
}

class LightMotorVehicle extends Vehicle {


double mileage;

LightMotorVehicle(String company, double price, double mileage) {


super(company, price);
[Link] = mileage;
}

void display() {
[Link]();
[Link]("Mileage: " + mileage + " km/l");
}
}

class HeavyMotorVehicle extends Vehicle {


double capacity;

HeavyMotorVehicle(String company, double price, double capacity)


{
super(company, price);
[Link] = capacity;
}

void display() {
[Link]();
[Link]("Capacity: " + capacity + " tons");
}
}

public class TestVehicle {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter number of vehicles: ");


int n = [Link]();
[Link]();

Vehicle[] vehicles = new Vehicle[n];

for (int i = 0; i < n; i++) {


[Link]("Enter type (1=LMV, 2=HMV): ");
int type = [Link]();
[Link]();

[Link]("Enter company: ");


String company = [Link]();
[Link]("Enter price: ");
double price = [Link]();

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);
}
}

[Link]("\n--- Vehicle Details ---");


for (Vehicle v : vehicles) {
[Link]();
[Link]("------------------");
}
[Link]();
}
}

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].*;

public class CitySTDCode {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
HashMap<String, Integer> map = new HashMap<>();

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;
}
}
}
}

20)​ Create a package named “Series” having three different


classes to print series: [Link] series b. Cube of numbers c.
Square of numbers Write a java program to generate “n” terms of the
above series. Accept n from user.
Ans.
File 1: Series/[Link]

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].*;

public class TestSeries {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter n: ");
int n = [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];

public class AreaCalculator {

// Method to calculate area of Circle


static double area(double radius) {
return [Link] * radius * radius;
}

// Method to calculate area of Rectangle


static double area(double length, double breadth) {
return length * breadth;
}

// Method to calculate area of Triangle


static double area(double base, double height, boolean
isTriangle) {
return 0.5 * base * height;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

[Link]("Choose shape to calculate area:");


[Link]("1. Circle");
[Link]("2. Rectangle");
[Link]("3. Triangle");
[Link]("Enter your choice: ");
int choice = [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]();
}
}

22)​ Define a class Employee having members – id, name, salary.


Define default constructor. Create a subclass called Manager with
private member bonus. Define methods accept and display in both the
classes. Create “n” objects of the Manager class and display the
details of the worker having the maximum total salary (salary
+bonus).
Ans.
import [Link];

class Employee {
int id;
String name;
double salary;

Employee() {}

void accept(Scanner sc) {


[Link]("Enter ID: ");
id = [Link]();
[Link]();
[Link]("Enter Name: ");
name = [Link]();
[Link]("Enter Salary: ");
salary = [Link]();
}

void display() {
[Link]("ID: " + id + ", Name: " + name + ",
Salary: " + salary);
}
}

class Manager extends Employee {


double bonus;

void accept(Scanner sc) {


[Link](sc);
[Link]("Enter Bonus: ");
bonus = [Link]();
}

double totalSalary() {
return salary + bonus;
}

void display() {
[Link]();
[Link]("Bonus: " + bonus + ", Total Salary: " +
totalSalary());
}
}

public class TestManager {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter number of Managers: ");


int n = [Link]();
Manager[] arr = new Manager[n];

Manager maxManager = null;


double maxSalary = 0;

for (int i = 0; i < n; i++) {


[Link]("\nEnter details for Manager " + (i +
1));
arr[i] = new Manager();
arr[i].accept(sc);

if (arr[i].totalSalary() > maxSalary) {


maxSalary = arr[i].totalSalary();
maxManager = arr[i];
}
}

[Link]("\nManager with Maximum Salary:");


[Link]();
[Link]();
}
}

23)​ Write a java program to design a following GUI. Use appropriate


Layout and Components.

Ans.
import [Link].*;
import [Link].*;
import [Link].*;

class LoginGUI extends JFrame implements ActionListener {


JTextField txtUser;
JPasswordField txtPass;
JButton btnLogin, btnReset;

LoginGUI() {
setTitle("Login");
setSize(300, 200);
setLayout(new GridLayout(3, 2, 10, 10));

JLabel lblUser = new JLabel("Username:");


JLabel lblPass = new JLabel("Password:");
txtUser = new JTextField();
txtPass = new JPasswordField();
btnLogin = new JButton("Login");
btnReset = new JButton("Reset");

add(lblUser);
add(txtUser);
add(lblPass);
add(txtPass);
add(btnLogin);
add(btnReset);

[Link](this);
[Link](this);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


if ([Link]() == btnLogin) {
[Link](this, "Welcome " +
[Link]());
} else {
[Link]("");
[Link]("");
}
}

public static void main(String[] args) {


new LoginGUI();
}
}

24)​ Define a class patient (patient_name, patient_age,


patient_oxy_level,patient_HRCT_report). Create an object of patient.
Handle appropriate exception while patient oxygen level less than 95%
and HRCT scan report greater than 10, then throw user defined
Exception “Patient is Covid Positive(+) and Need to Hospitalized”
otherwise display its information.
Ans.
import [Link];

// 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;

// Constructor to initialize patient details


Patient(String name, int age, double oxy, double hrct) {
this.patient_name = name;
this.patient_age = age;
this.patient_oxy_level = oxy;
this.patient_HRCT_report = hrct;
}

// Method to check patient condition


void checkStatus() throws CovidPositiveException {
if (patient_oxy_level < 95 && patient_HRCT_report > 10) {
throw new CovidPositiveException("Patient is Covid
Positive(+) and Need to be Hospitalized");
} else {
[Link]("\n--- Patient Information ---");
[Link]("Name : " + patient_name);
[Link]("Age : " + patient_age);
[Link]("Oxygen Level: " + patient_oxy_level +
"%");
[Link]("HRCT Score : " +
patient_HRCT_report);
[Link]("Status : Patient is Normal");
}
}
}

// Main class
public class PatientDetails {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter patient name: ");


String name = [Link]();

[Link]("Enter patient age: ");


int age = [Link]();

[Link]("Enter oxygen level (%): ");


double oxy = [Link]();

[Link]("Enter HRCT report score: ");


double hrct = [Link]();

// Create Patient object


Patient p = new Patient(name, age, oxy, hrct);

// 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].*;

public class LinkedListExample {


public static void main(String[] args) {
// Step 1: Create LinkedList and add elements
LinkedList<String> languages = new LinkedList<String>();
[Link]("CPP");
[Link]("Java");
[Link]("Python");
[Link]("PHP");

// Step 2: Display contents using Iterator


[Link]("Contents of Linked List (using
Iterator):");
Iterator<String> itr = [Link]();
while ([Link]()) {
[Link]([Link]());
}

// Step 3: Display contents in reverse order using


ListIterator
[Link]("\nContents of Linked List in Reverse
Order (using ListIterator):");
ListIterator<String> listItr =
[Link]([Link]()); // start from end

while ([Link]()) {
[Link]([Link]());
}
}
}

26)Write a program to read the contents of “[Link]” file. Display


the contents of file in uppercase as output.
Ans.
import [Link].*;

public class FileUppercase {


public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new
FileReader("[Link]"));
String line;

[Link]("File Contents in UPPERCASE:");


while ((line = [Link]()) != null) {
[Link]([Link]());
}
[Link]();
} catch (Exception e) {
[Link]("Error: " + e);
}
}
}

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].*;

class InvalidNameException extends Exception {


InvalidNameException(String msg) {
super(msg);
}
}

public class DoctorNameCheck {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try {
[Link]("Enter Doctor Name: ");
String name = [Link]();

if (![Link]("[a-zA-Z ]+"))
throw new InvalidNameException("Name is Invalid");

[Link]("Doctor Name: " + name);

} 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;
}

boolean isNegative() { return num < 0; }


boolean isPositive() { return num > 0; }
boolean isOdd() { return num % 2 != 0; }
boolean isEven() { return num % 2 == 0; }

public static void main(String[] args) {


int val = [Link](args[0]);
MyNumber obj = new MyNumber(val);

[Link]("Number: " + val);


[Link]("Is Negative? " + [Link]());
[Link]("Is Positive? " + [Link]());
[Link]("Is Odd? " + [Link]());
[Link]("Is Even? " + [Link]());
}
}

28)​ Write a java program to design a following GUI. Use


appropriate Layout and Components.

Ans.
import [Link].*;
import [Link].*;
import [Link].*;

class LanguageSelector extends JFrame implements ActionListener {


JComboBox<String> combo;
JLabel lblResult;
JButton btnShow;

LanguageSelector() {
setTitle("Programming Language Selector");
setSize(300, 200);
setLayout(new FlowLayout());

combo = new JComboBox<>(new String[]{"Java", "C++", "Python",


"C#", "PHP"});
btnShow = new JButton("Show");
lblResult = new JLabel("Selected Language: ");

add(combo);
add(btnShow);
add(lblResult);

[Link](this);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


String lang = (String) [Link]();
[Link]("Selected Language: " + lang);
}

public static void main(String[] args) {


new LanguageSelector();
}
}

29)​ Define an abstract class Shape with abstract methods area ()


and volume (). Derive Abstract class Shape into two classes Cone and
Cylinder. Write a java Program To calculate area and volume of Cone
and Cylinder.(Use Super Keyword).
Ans.
import [Link];

// Abstract class Shape


abstract class Shape {
double radius, height;
// Constructor
Shape(double r, double h) {
radius = r;
height = h;
}

// Abstract methods
abstract double area();
abstract double volume();
}

// Derived class: Cone


class Cone extends Shape {

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;
}
}

// Derived class: Cylinder


class Cylinder extends Shape {

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]);

[Link]("Choose shape to calculate:");


[Link]("1. Cone");
[Link]("2. Cylinder");
[Link]("Enter your choice: ");
int choice = [Link]();

[Link]("Enter radius: ");


double r = [Link]();
[Link]("Enter height: ");
double h = [Link]();

Shape s; // reference of abstract class

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]();
}
}

You might also like