0% found this document useful (0 votes)
105 views

Java Programs From Model Answer

Uploaded by

Vighnesh Pote
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)
105 views

Java Programs From Model Answer

Uploaded by

Vighnesh Pote
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
You are on page 1/ 33

Java Programs from Model Answer

1. Write a program lo display ASCII value of a number 9.


Ans) public class asciivalue
{
public static void main(String args[])
{
char ch = '9';
int ascii = ch;
System.out.println("The ASCII value of " + ch+ " is: " + ascii);
}
}

Output:
The ASCII value of 9 is: 57

2. Write a program to sort the elements of an array in ascending order.


OR
Write a java program to sort an 1-d array in ascending order using bubble-sort.
Ans) class ArraySort
{
public static void main(String args[])
{
int a[]={85,95,78,45,12,56,78,19};
int i=0;
int j=0;
int temp=0;
int l=a.length;

for(i=0;i<l;i++)
{
for(j=(i+1);j<l;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.println("Ascending order of numbers:");
for(i=0;i<l;i++)
{
System.out.println(""+a[i]);
}
}
}
Output:
Ascending order of numbers:
12
19
45
56
78
78
85
95
3. Write a program to read a file and then count number of words.
Ans) import java.io.*;

public class FileWordCount {


public static void main(String args[]) {
File file = new File("input.txt");
int wordCount = 0;

try {
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);

int c;
while ((c = bufferedReader.read()) != -1) {
if (c == ' ') {
wordCount++;
}
}

wordCount++;

System.out.println("Number of words: " + wordCount);

bufferedReader.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}

4. Write a program which displays functioning of ATM machine,


(Hint: Withdraw, Deposit, Check Balance and Exit)
Ans) import java.util.Scanner;

public class ATM_Transaction


{
public static void main(String args[])
{
int balance = 5000, withdraw, deposit;
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("Automated Teller Machine");
System.out.println("1:Withdraw");
System.out.println("2:Deposit");
System.out.println("3:Check Balance");
System.out.println("4:EXIT");
System.out.print("Choose the operation you want to perform:");

int choice = scanner.nextInt();


switch (choice) {
case 1:
System.out.print("Enter money to be withdrawn:");
withdraw = scanner.nextInt();
if (balance >= withdraw) {
balance -= withdraw;
System.out.println("Please collect your money");
} else {
System.out.println("Insufficient Balance");
}
System.out.println("");
break;
case 2:
System.out.print("Enter money to be deposited:");
deposit = scanner.nextInt();
balance += deposit;
System.out.println("Your Money has been successfully deposited");
System.out.println("");
break;
case 3:
System.out.println("Balance : " + balance);
System.out.println("");
break;
case 4:
System.exit(0);
}
}
}
}
5. Write a program to show the use of copy constructor.
Ans) class Student {
int id;
String name;

Student(int i, String n) {
id = i;
name = n;
}

Student(Student s) {
id = s.id;
name = s.name;
}

void display() {
System.out.println(id + " " + name);
}

public static void main(String args[]) {


Student s1 = new Student(111, "ABC");
s1.display();

Student s2 = new Student(s1);


s2.display();
}
}

6. Write a program to show the Hierarchical inheritance.


Ans) class Animal {
void eat() {
System.out.println("Animal is eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking...");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat is meowing...");
}
}

public class HierarchicalInheritance {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.bark();

Cat cat = new Cat();


cat.eat();
cat.meow();
}
}
7. Write a program to append content of one file into another file.
Ans) import java.io.*;
class copyf
{
public static void main(String args[]) throws IOException
{
BufferedReader f1=null;
BufferedWriter f2=null;
try
{
f1=new BufferedReader(new FileReader("input.txt"));
f2=new BufferedWriter(new FileWriter("output.txt",true));
int c;
while((c=f1.read())!=-1)
{
f2.write(c);
}
System.out.println("File appended successfully");
}
finally
{
f1.close();
f2.close();
}
}
}
8. Develop and Interest Interface which contains Simple Interest and
Compound Interest methods and static final field of rate 25%. Write a
class to implement those methods.
Ans) interface Interest
{
double RATE = 0.25;

double simple(double p, double r, double t);

double compound(double p, double r, double t);


}

class Calculator implements Interest


{
public double simple(double p, double r, double t)
{
// Simple Interest = (Principal * Rate * Time) / 100
return (p * r * t) / 100;
}
public double compound(double p, double r, double t)
{
// Compound Interest = Principal * (1 + annualInterestRate /
compoundingFrequency) ^(Time) - Principal
double a = p * Math.pow((1 + r / 100), t)-p;
return a ;
}
}

public class Main {


public static void main(String[] args)
{
Calculator c = new Calculator();
double p = 1000, t = 2;

double simpleInterest = c.simple(p, Interest.RATE, t);


double compoundInterest = c.compound(p, Interest.RATE, t);

System.out.println("Simple Interest: " + simpleInterest);


System.out.println("Compound Interest: " + compoundInterest);
}
}
9. Write a program that throws an exception called "NoMatchException"
when a string is not equal to "India".
Ans) class NoMatchException extends Exception {
public NoMatchException(String message) {
super(message);
}
}

public class StringMatcher {


public static void main(String[] args) {
try {
String input = "USA";
if (!input.equals("India")) {
throw new NoMatchException("String does not match 'India'");
}
} catch (NoMatchException e) {
System.out.println("Caught NoMatchException: " + e.getMessage());
}
}
}

10. Write a program to print the sum, difference and product of two complex
numbers by creating a class named "Complex" with separate methods for
each operation whose real and imaginary parts are entered by user.
Ans) import java.util.Scanner;
class Complex {
double real;
double imaginary;

Complex(double real, double imaginary) {


this.real = real;
this.imaginary = imaginary;
}

Complex add(Complex num) {


return new Complex(this.real + num.real, this.imaginary + num.imaginary);
}

Complex subtract(Complex num) {


return new Complex(this.real - num.real, this.imaginary - num.imaginary);
}

Complex multiply(Complex num) {


double realPart = this.real * num.real - this.imaginary * num.imaginary;
double imaginaryPart = this.real * num.imaginary + this.imaginary * num.real;
return new Complex(realPart, imaginaryPart);
}

void display() {
System.out.println(this.real + " + " + this.imaginary + "i");
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter the real part of first complex number:");


double real1 = scanner.nextDouble();
System.out.println("Enter the imaginary part of first complex number:");
double imaginary1 = scanner.nextDouble();

System.out.println("Enter the real part of second complex number:");


double real2 = scanner.nextDouble();
System.out.println("Enter the imaginary part of second complex number:");
double imaginary2 = scanner.nextDouble();

Complex complex1 = new Complex(real1, imaginary1);


Complex complex2 = new Complex(real2, imaginary2);

System.out.print("Sum: ");
complex1.add(complex2).display();
System.out.print("Difference: ");
complex1.subtract(complex2).display();

System.out.print("Product: ");
complex1.multiply(complex2).display();

scanner.close();
}
}
Output:
Enter the real part of first complex number:
3
Enter the imaginary part of first complex number:
2
Enter the real part of second complex number:
1
Enter the imaginary part of second complex number:
4
Sum: 4.0 + 6.0i
Difference: 2.0 + -2.0i
Product: -5.0 + 14.0i
11. Write a program to draw a chessboard in Java Applet.
Ans) import java.applet.*;
import java.awt.*;

/* <applet code="Chess" width=600 height=600>


</applet> */

public class Chess extends Applet {


static int N = 10;

public void paint(Graphics g) {


int x, y;
for (int row = 0; row < N; row++)
{
for (int col = 0; col < N; col++)
{
x = row * 20;
y = col * 20;
if ((row % 2 == 0 && col % 2 == 0) || (row % 2 != 0 && col % 2 != 0))
g.setColor(Color.BLACK);
else
g.setColor(Color.WHITE);
g.fillRect(x, y, 20, 20);
}
}
}
}
12. Write a program to copy content of one file to another file.
Ans) class fileCopy
{
public static void main(String args[]) throws IOException
{
FileInputStream in= new FileInputStream("input.txt");
FileOutputStream out= new FileOutputStream("output.txt");
int c=0;
try
{
while(c!=-1)
{
c=in.read();
out.write(c);
}
System.out.println("File copied to output.txt....");
}
finally
{
if(in!=null)
in.close();
if(out!=null)
out.close();
}
}
}
13. Write a Java Program to find out the even numbers from 1 to 100 using for loop.
Ans) public class EvenNumbers
{
public static void main(String[] args)
{
System.out.println("Even numbers from 1 to 100:");
for (int i = 2; i <= 100; i += 2)
{
System.out.print(i + " ");
}
}
}
14. Write a java applet to display the following output in Red color.

Ans) import java.awt.*;


import java.applet.*;

public class MyApplet extends Applet {


public void paint(Graphics g) {
int x[] = {10, 200, 70};
int y[] = {10, 10, 100};
g.setColor(Color.red);
g.drawPolygon(x, y, 3);
}
}

/* <applet code="MyApplet" height=400 width=400>


</applet> */

15. Write a Java program in which thread A will display the even numbers between 1 to
50 and thread B will display the odd numbers between 1 to 50. After 3 iterations
thread A should go to sleep for 500ms.
Ans) class EvenThread extends Thread {
public void run() {
for (int i = 2; i <= 50; i += 2) {
System.out.println("Even: " + i);
}
}
}

class OddThread extends Thread {


public void run() {
for (int i = 1; i <= 50; i += 2) {
System.out.println("Odd: " + i);
}
}
}

public class Main {


public static void main(String[] args) {
EvenThread evenThread = new EvenThread();
OddThread oddThread = new OddThread();
evenThread.start();
oddThread.start();
}
}
16. Write a Java applet to draw a bar chart for the following values.

Ans) import java.awt.*;


import java.applet.*;

/* <applet code="BarChart" width=400 height=400>


<param name="c1" value="110">
<param name="c2" value="120">
<param name="c3" value="170">
<param name="c4" value="160">
<param name="label1" value="2011">
<param name="label2" value="2012">
<param name="label3" value="2013">
<param name="label4" value="2014">
<param name="Columns" value="4">
</applet> */

public class BarChart extends Applet {


String label[];
int value[];

public void init() {


setBackground(Color.yellow);
try {
int n = Integer.parseInt(getParameter("Columns"));
label = new String[n];
value = new int[n];
label[0] = getParameter("label1");
label[1] = getParameter("label2");
label[2] = getParameter("label3");
label[3] = getParameter("label4");
value[0] = Integer.parseInt(getParameter("c1"));
value[1] = Integer.parseInt(getParameter("c2"));
value[2] = Integer.parseInt(getParameter("c3"));
value[3] = Integer.parseInt(getParameter("c4"));
}
}
public void paint(Graphics g) {
for (int i = 0; i < 4; i++) {
g.setColor(Color.black);
g.drawString(label[i], 20, i * 50 + 30);
g.setColor(Color.red);
g.fillRect(50, i * 50 + 10, value[i], 40);
}
}
}
-------------------------------------------------------------------------------------------------------------------
OR
----------------------------------------------------------------------------------------------------------------
import java.awt.*;
import java.applet.*;

/* <applet code="BarChart" width=400 height=400>


</applet> */

public class BarChart extends Applet {


String[] labels = {"2011", "2012", "2013", "2014"};
int[] values = {110, 120, 170, 160};
int barWidth = 100;
int barHeight = 20;

public void paint(Graphics g) {


setBackground(Color.yellow);
for (int i = 0; i < labels.length; i++) {
g.setColor(Color.black);
g.drawString(labels[i], 20, i * 50 + 30);
g.setColor(Color.red);
g.fillRect(50, i * 50 + 10, values[i], barHeight);
}
}
}
Output:

17. Write a program to create a user defined exception in java.


Ans) class MyException extends Exception {
public MyException(String message) {
super(message);
}
}

public class UserDefinedExceptionDemo {


public static void main(String[] args) {
try {
throw new MyException("This is a user-defined exception");
} catch (MyException e) {
System.out.println("Caught the exception: " + e.getMessage());
}
}
}
18. Write a program for reading and writing character to and from the given files
using character stream classes.
Ans) import java.io.*;

public class CharacterStreamExample


{
public static void main(String[] args) throws IOException
{
try
{
FileReader fileReader = new FileReader("input.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter("output.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

String line;
while ((line = bufferedReader.readLine()) != null)
{
bufferedWriter.write(line);
bufferedWriter.newLine();
}
System.out.println("File copied successfully!");
}
finally {
if (bufferedReader != null) {
bufferedReader.close();
}
if (bufferedWriter != null) {
bufferedWriter.close();
}
}
}
}
19. Write a program to print all the Armstrong numbers from 0 to 999
Ans) class ArmstrongWhile {
public static void main(String[] arg) {
int i = 0; // Loop counter for numbers from 0 to 999
int a, arm, n; // 'a' is the current digit, 'arm' is the Armstrong number candidate, 'n' is
the current number being checked
System.out.println("Armstrong numbers between 0 to 999 are");
while (i <= 999) {
n = i;
arm = 0;
while (n > 0) {
a = n % 10; // Extract the last digit of the number
arm = arm + (a * a * a); // Add the cube of the digit to 'arm'
n = n / 10; // Remove the last digit from the number
}
if (arm == i) // If 'arm' is equal to the original number, it's an Armstrong number
System.out.println(i);
i++;
}
}
}
20. Write an applet program for following graphics method.
i) Drawoval ( )
ii) Drawline ( )
Ans) import java.awt.*;
import java.applet.*;
/*
<applet code="GraphicsDemo.class" width="300" height="300">
Your browser does not support the Java applet tag.
</applet>
*/
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawOval(50, 50, 100, 80);

g.setColor(Color.blue);
g.drawLine(20, 20, 180, 180);
}
}

21. Write a program to copy all elements of one array into another array.
Ans) public class ArrayCopy
{
public static void main(String[] args)
{
int[] originalArray = {1, 2, 3, 4, 5};
int[] copiedArray = new int[originalArray.length];

for (int i = 0; i < originalArray.length; i++)


{
copiedArray[i] = originalArray[i];
}

System.out.println("Original array:");
for (int num : originalArray) {
System.out.print(num + " ");
}
System.out.println("\nCopied array:");
for (int num : copiedArray) {
System.out.print(num + " ");
}
}
}

22. Write a program to implement the following inheritance.

Ans) interface Exam {


int sports_mark = 20;
}

class Student {
String S_name;
int Roll_no, m1, m2, m3;

Student(String n, int a, int b, int c, int d) {


S_name = n;
Roll_no = a;
m1 = b;
m2 = c;
m3 = d;
}

void showData() {
System.out.println("Name of student: " + S_name);
System.out.println("Roll no. of the student: " + Roll_no);
System.out.println("Marks of subject 1: " + m1);
System.out.println("Marks of subject 2: " + m2);
System.out.println("Marks of subject 3: " + m3);
}
}

class Result extends Student implements Exam {


Result(String n, int a, int b, int c, int d) {
super(n, a, b, c, d);
}
void display() {
super.showData();
int total = m1 + m2 + m3;
float result = (total + Exam.sports_mark) / total * 100;
System.out.println("Result of student is: " + result);
}
}

public class StudentsDetails {


public static void main(String args[]) {
Result r = new Result("Sanika", 170, 78, 85, 97);
r.display();
}
}

23. Write a program to print even and odd number using two threads with delay
of 1000ms after each number.
Ans) class OddThread extends Thread
{
public void run()
{
for (int i = 1; i <= 20; i += 2)
{
System.out.println("ODD = " + i);
try
{
sleep(1000);
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
}
}
}
}

class EvenThread extends Thread


{
public void run()
{
for (int i = 0; i <= 20; i += 2)
{
System.out.println("EVEN = " + i);
try
{
sleep(1000);
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
}
}
}
}
public class OddEven
{
public static void main(String[] args)
{
OddThread odd = new OddThread();
EvenThread even = new EvenThread();
odd.start();
even.start();
}
}

24. Write a program to generate following output using drawline () method.

Ans) import java.applet.*;


import java.awt.*;
public class Triangle extends Applet {
public void paint(Graphics g) {
// Using drawLine() method
g.drawLine(100, 200, 200, 100);
g.drawLine(200, 100, 300, 200);
g.drawLine(300, 200, 100, 200);

OR

// Using drawPolygon() method


int[] a = { 100, 200, 300, 100 };
int[] b = { 200, 100, 200, 200 };
int n = 4;
g.drawPolygon(a, b, n);
}
}
/*
<applet code="Triangle.class" width="600" height="600">
</applet>
*/
25. Write a program to check whether the given number is prime or not.
Ans) class PrimeExample {
public static void main(String args[]) {
int i, m = 0, flag = 0;
int n = 7; // it is the number to be checked
m = n / 2;
if (n == 0 || n == 1) {
System.out.println(n + " is not prime number");
} else {
for (i = 2; i <= m; 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
}
}

OR
import java.util.Scanner;

public class PrimeCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
scanner.close();

boolean isPrime = true;


if (num <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}

if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
}

26. Define a class employee with data members 'empid , name and salary. Accept data for
three objects and display it.
Ans) import java.util.Scanner;

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

void input()
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter employee ID: ");
empid = scanner.nextInt();
System.out.print("Enter employee name: ");
name = scanner.next();
System.out.print("Enter employee salary: ");
salary = scanner.nextDouble();
}

void display()
{
System.out.println("Employee ID: " + empid);
System.out.println("Employee Name: " + name);
System.out.println("Employee Salary: " + salary);
}
}

public class Main


{
public static void main(String[] args)
{
Employee[] employees = new Employee[3];

System.out.println("Enter details for three employees:");


for (int i = 0; i < 3; i++)
{
System.out.println("\nEnter details for Employee " + (i + 1) + ":");
employees[i] = new Employee();
employees[i].input();
}
System.out.println("\n Employee details:");
for (int i = 0; i < 3; i++)
{
System.out.println("\n Details of Employee " + (i + 1) + ":");
employees[i].display();
}
}
}

27. Write a program to read a file (Use character stream)


Ans) import java.io.*;

public class FileWordReader


{
public static void main(String args[])
{
File file = new File("input.txt");
try
{
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);

String line;
while ((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}

bufferedReader.close();
}
catch (IOException e)
{
System.out.println("An error occurred: " + e.getMessage());
}
}
}

28. Write a program to find reverse of a number.


Ans) public class ReverseNumber
{
public static void main(String[] args)
{
int number = 123456;
int reversedNumber = 0;

while (number != 0)
{
int digit = number % 10;
reversedNumber = reversedNumber * 10 + digit;
number /= 10;
}

System.out.println("Reverse of the number: " + reversedNumber);


}
}

29. Write a program to add 2 integer, 2 string and 2 float values in a vector. Remove the
element specified by the user and display the list.
Ans) import java.util.*;

public class VectorExample


{
public static void main(String[] args)
{
Vector<object> v1 = new Vector<>();
v1.add(10);
v1.add(20);
v1.add("Hello");
v1.add("World");
v1.add(3.14f);
v1.add(5.67f);

System.out.println("Original Vector: " + vector);

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the index of the element to remove: ");


int index = scanner.nextInt();

if (index >= 0 && index < vector.size())


{
vector.remove(index);
System.out.println("Element removed successfully.");
}
else
{
System.out.println("Invalid index! Please enter a valid index.");
}
scanner.close();

System.out.println("Updated Vector: " + vector);


}
}
30. Develop a program to create a class ‘Book’ having data members author, title and
price. Derive a class 'Booklnfo' having data member 'stock position’ and method to
initialize and display the information for three objects.
Ans) class Book
{
String author, title, publisher;
Book(String a, String t, String p)
{
author = a;
title = t;
publisher = p;
}
}

class BookInfo extends Book


{
float price;
int stock_position;

BookInfo(String a, String t, String p, float amt, int s)


{
super(a, t, p);
price = amt;
stock_position = s;
}

void show() {
System.out.println("Book Details:");
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Publisher: " + publisher);
System.out.println("Price: " + price);
System.out.println("Stock Available: " + stock_position);
}
}
class BookDemo
{
public static void main(String[] args)
{
BookInfo ob1 = new BookInfo("Author1", "Title1", "Publisher1", 359.50F, 10);
BookInfo ob2 = new BookInfo("Author2", "Title2", "Publisher2", 359.50F, 20);
BookInfo ob3 = new BookInfo("Author3", "Title3", "Publisher3", 879.50F, 15);
ob1.show();
ob2.show();
ob3.show();
}
}
31. Write a program to create a class 'salary with data members empid', ‘name' and
‘basicsalary'. Write an interface 'Allowance’ which stores rates of calculation for da as
90% of basic salary, hra as 10% of basic salary and pf as 8.33% of basic salary.
Include a method to calculate net salary and display it.
Ans) interface Allowance
{
double DA_RATE = 0.9;
double HRA_RATE = 0.1;
double PF_RATE = 0.0833;

void calculateNetSalary();
}

class Salary
{
int empid;
String name;
float basicsalary;

Salary(int empid, String name, float basicsalary)


{
this.empid = empid;
this.name = name;
this.basicsalary = basicsalary;
}

void display()
{
System.out.println("Empid: " + empid);
System.out.println("Name: " + name);
System.out.println("Basic Salary: " + basicsalary);
}
}

class NetSalary extends Salary implements Allowance


{
float ta;

NetSalary(int empid, String name, float basicsalary, float ta)


{
super(empid, name, basicsalary);
this.ta = ta;
}
public void calculateNetSalary()
{
double da = DA_RATE * basicsalary;
double hra = HRA_RATE * basicsalary;
double pf = PF_RATE * basicsalary;

double netSalary = basicsalary + ta + hra + da - pf;


System.out.println("Net Salary: " + netSalary);
}
}
public class EmpDetail
{
public static void main(String[] args)
{
NetSalary emp = new NetSalary(11, "abcd", 50000, 2000);
emp.display();
emp.calculateNetSalary();
}
}

32. Define an exception called 'No Match Exception' that is thrown when the passward
accepted is not equal to "MSBTE'. Write the program.
Ans) class NoMatchException extends Exception {
public NoMatchException(String message) {
super(message);
}
}

public class PasswordChecker {


public static void main(String[] args) {
String password = "XYZ"; // Assume this is the password entered by the user

try {
if (!password.equals("MSBTE")) {
throw new NoMatchException("Password does not match.");
}
System.out.println("Password is correct.");
} catch (NoMatchException e) {
System.out.println("No Match Exception: " + e.getMessage());
}
}
}

33. Write a program to check whether the string provided by the user is palindrome
or not.
Ans) import java.util.Scanner;

public class Palindrome {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String word = scanner.nextLine();
int len = word.length() - 1;
int l = 0;
int flag = 1;
int r = len;
while (l <= r) {
if (word.charAt(l) == word.charAt(r)) {
l++;
r--;
} else {
flag = 0;
break;
}
}
if (flag == 1) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
scanner.close();
}
}

34. Design an applet to perform all arithmetic operations and display the result by using
labels. textboxes and buttons.
Ans) import java.awt.*;
import java.awt.event.*;

public class Sample extends Frame implements ActionListener {


Label l1, l2, l3;
TextField tf1, tf2, tf3;
Button b1, b2, b3, b4;

Sample() {
l1 = new Label("First No.");
l1.setBounds(10, 10, 70, 20);
tf1 = new TextField();
tf1.setBounds(90, 10, 150, 20);

l2 = new Label("Second No.");


l2.setBounds(10, 40, 70, 20);
tf2 = new TextField();
tf2.setBounds(90, 40, 150, 20);

l3 = new Label("Result");
l3.setBounds(10, 70, 70, 20);
tf3 = new TextField();
tf3.setBounds(90, 70, 150, 20);
tf3.setEditable(false);

b1 = new Button("+");
b1.setBounds(50, 120, 50, 50);
b2 = new Button("-");
b2.setBounds(120, 120, 50, 50);
b3 = new Button("*");
b3.setBounds(190, 120, 50, 50);
b4 = new Button("/");
b4.setBounds(260, 120, 50, 50);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);

add(l1);
add(tf1);
add(l2);
add(tf2);
add(l3);
add(tf3);
add(b1);
add(b2);
add(b3);
add(b4);

setSize(350, 200);
setLayout(null);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


String s1 = tf1.getText();
String s2 = tf2.getText();
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
int c = 0;
if (e.getSource() == b1) {
c = a + b;
} else if (e.getSource() == b2) {
c = a - b;
} else if (e.getSource() == b3) {
c = a * b;
} else if (e.getSource() == b4) {
if (b != 0) {
c = a / b;
} else {
tf3.setText("Divide by zero error");
return;
}
}
String result = String.valueOf(c);
tf3.setText(result);
}

public static void main(String[] args) {


new Sample();
}
}

35. Define a class circle having data members pi and radius. Initialize and display values
of data members also calculate area of circle and display it.
Ans) class Circle {
double pi = 3.14;
double radius;

Circle(double r) {
radius = r;
}

double calculateArea() {
return pi * radius * radius;
}

void display() {
System.out.println("Radius of the circle: " + radius);
System.out.println("Area of the circle: " + calculateArea());
}
}

public class Main {


public static void main(String[] args) {
Circle circle = new Circle(5);
circle.display();
}
}

36. Write a program to create a vector with five elements as (5, 15, 25, 35, 45). Insert new
element at 2nd position. Remove 1st and 4th element from vector.
Ans) import java.util.*;

public class VectorOperations


{
public static void main(String[] args)
{
Vector<Integer> v = new Vector<>();
v.addElement(new Integer(5));
v.addElement(new Integer(15));
v.addElement(new Integer(25));
v.addElement(new Integer(35));
v.addElement(new Integer(45));

for(Integer element : v)
{
System.out.println(element);
}

v.insertElementAt(new Integer(20), 1);


v.removeElementAt(0);
v.removeElementAt(3);

for(Integer element : v)
{
System.out.println(element);
}
}
}

37. Write a program to perform following task:


(i) Create a text file and store data in it.
(ii) Count number of lines and words in that file.
Ans) import java.io.*;

public class FileProgram


{
public static void main(String[] args)
{
int lineCount = 0, wordCount = 0;
try
{
FileWriter fw = new FileWriter("Sample.txt");
BufferedWriter bw = new BufferedWriter(fw);

bw.write("This is sample data.\n");


bw.write("It contains multiple lines.\n");
bw.write("Each line has some words.\n");
bw.close();

BufferedReader br = new BufferedReader(new FileReader("Sample.txt"));


String line;
while ((line = br.readLine()) != null)
{
lineCount++;
}
String word;
while ((word = br.read()) != -1)
{
if (c == ' ')
{
wordCount++;
}
}

br.close();

System.out.println("Number of lines: " + lineCount);


System.out.println("Number of words: " + (wordcount+1));
}
catch (IOException e)
{
System.out.println("An error occurred: " + e.getMessage());
}
}
}

38. Implement the following inheritance.

Ans) interface Salary {


double BasicSalary = 10000.0;
void BasicSal();
}

class Employee {
String Name;
int age;

Employee(String n, int b) {
Name = n;
age = b;
}

void Display() {
System.out.println("Name of Employee: " + Name);
System.out.println("Age of Employee: " + age);
}
}

class GrossSalary extends Employee implements Salary {


double HRA, TA, DA;

GrossSalary(String n, int b, double h, double t, double d) {


super(n, b);
HRA = h;
TA = t;
DA = d;
}

public void BasicSal() {


System.out.println("Basic Salary: " + BasicSalary);
}

void TotalSal() {
Display();
BasicSal();
double TotalSal = BasicSalary + TA + DA + HRA;
System.out.println("Total Salary: " + TotalSal);
}
}

class EmpDetails {
public static void main(String args[]) {
GrossSalary s = new GrossSalary("Sachin", 20, 1000, 2000, 7000);
s.TotalSal();
}
}

39. Define a class student with int id and string name as data members and a method
void SetData ( ). Accept and display the data for five students.
Ans) import java.util.Scanner;
class Student
{
int id;
String name;
void SetData()
{
Scanner scanner = new Scanner(System.in);

System.out.println("Enter student ID:");


id = scanner.nextInt();

System.out.println("Enter student name:");


name = scanner.nextLine();
}

void DisplayData()
{
System.out.println("Student ID: " + id);
System.out.println("Student Name: " + name);
}
}
public class Main
{
public static void main(String[] args)
{
Student[] s = new Student[5];

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


s[i] = new Student();
System.out.println("Enter details for student " + (i + 1) + ":");
s[i].SetData();
}

System.out.println("\nDetails of all students:");


for (int i = 0; i < 5; i++) {
System.out.println("\nStudent " + (i + 1) + ":");
s[i].DisplayData();
}
}
}

40. Write a program to create two threads. One thread will display the numbers from 1 to
50 (ascending order) and other thread will display numbers from 50 to 1
(descending order).
Ans) class EvenThread extends Thread {
public void run() {
for (int i = 2; i <= 50; i += 2) {
System.out.println("Even: " + i);
}
}
}
class OddThread extends Thread {
public void run() {
for (int i = 1; i <= 50; i += 2) {
System.out.println("Odd: " + i);
}
}
}

public class Main {


public static void main(String[] args) {
EvenThread evenThread = new EvenThread();
OddThread oddThread = new OddThread();
evenThread.start();
oddThread.start();
}
}

OR
class DescendingThread extends Thread {
public void run() {
for (int i = 50; i >= 1; i--) {
System.out.println("Descending: " + i);
try {
sleep(1000);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}

class AscendingThread extends Thread {


public void run() {
for (int i = 1; i <= 50; i++) {
System.out.println("Ascending: " + i);
try {
sleep(1000);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}

public class Main {


public static void main(String[] args) {
DescendingThread descendingThread = new DescendingThread();
AscendingThread ascendingThread = new AscendingThread();
descendingThread.start();
ascendingThread.start();
}
}

41. Write a program to input name and salary of employee and throw user defined
exception if entered salary is negative.
Ans) import java.util.Scanner;

class NegativeSalaryException extends Exception


{
public NegativeSalaryException(String message)
{
super(message);
}
}
public class SalaryInput
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);

System.out.print("Enter name of employee: ");


String name = scanner.nextLine();

try {
System.out.print("Enter salary of employee: ");
double salary = scanner.nextDouble();

if (salary < 0) {
throw new NegativeSalaryException("Salary cannot be negative!");
}
System.out.println("Employee name: " + name);
System.out.println("Employee salary: " + salary);
}
catch (NegativeSalaryException e)
{
System.out.println("Error: " + e.getMessage());
}
finally {
scanner.close();
}
}
}

You might also like