Java Programs From Model Answer
Java Programs From Model Answer
Output:
The ASCII value of 9 is: 57
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.*;
try {
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
int c;
while ((c = bufferedReader.read()) != -1) {
if (c == ' ') {
wordCount++;
}
}
wordCount++;
bufferedReader.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
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:");
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);
}
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;
void display() {
System.out.println(this.real + " + " + this.imaginary + "i");
}
}
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.*;
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);
}
}
}
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];
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 + " ");
}
}
}
class Student {
String S_name;
int Roll_no, m1, m2, m3;
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);
}
}
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());
}
}
}
}
OR
OR
import java.util.Scanner;
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);
}
}
String line;
while ((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
bufferedReader.close();
}
catch (IOException e)
{
System.out.println("An error occurred: " + e.getMessage());
}
}
}
while (number != 0)
{
int digit = number % 10;
reversedNumber = reversedNumber * 10 + digit;
number /= 10;
}
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.*;
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;
void display()
{
System.out.println("Empid: " + empid);
System.out.println("Name: " + name);
System.out.println("Basic Salary: " + basicsalary);
}
}
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);
}
}
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;
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.*;
Sample() {
l1 = new Label("First No.");
l1.setBounds(10, 10, 70, 20);
tf1 = new TextField();
tf1.setBounds(90, 10, 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);
}
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());
}
}
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.*;
for(Integer element : v)
{
System.out.println(element);
}
for(Integer element : v)
{
System.out.println(element);
}
}
}
br.close();
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);
}
}
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);
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];
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);
}
}
}
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());
}
}
}
}
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;
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();
}
}
}