Java Code Only Answers
Unit I: Basic Syntactical Constructs in Java (CO1)
1. Write a Java program to find out the even numbers from 1 to 100 using
for loop.
class EvenNumbers {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) {
[Link](i + " ");
}
}
}
}
2. Write a java program to sort a 1-D array in ascending order using
bubble-sort.
class BubbleSort {
public static void main(String[] args) {
int[] arr = {5,3,8,4,2};
for (int i = 0; i < [Link]-1; i++) {
for (int j = 0; j < [Link]-i-1; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
for (int num : arr) {
[Link](num + " ");
}
}
}
3. Write a program to check whether the given number is prime or not.
class PrimeCheck {
public static void main(String[] args) {
int num = 7;
boolean flag = false;
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) {
flag = true;
break;
}
}
[Link](flag ? "Not Prime" : "Prime");
}
}
4. Define a class employee with data members ‘empid’, ‘name’, and
‘salary’. Accept data for three objects and display it.
class Employee {
int empid;
String name;
double salary;
public static void main(String[] args) {
Employee[] emp = new Employee[3];
[Link] sc = new [Link]([Link]);
for (int i = 0; i < 3; i++) {
emp[i] = new Employee();
emp[i].empid = [Link]();
emp[i].name = [Link]();
emp[i].salary = [Link]();
}
for (Employee e : emp) {
[Link]([Link] + " " + [Link] + " " + [Link]);
}
}
}
5. Write a program to find the reverse of a number.
class ReverseNumber {
public static void main(String[] args) {
int num = 1234, rev = 0;
while (num != 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
[Link](rev);
}
}
6. 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.
import [Link];
class VectorDemo {
public static void main(String[] args) {
Vector<Object> v = new Vector<>();
[Link](10);
[Link](20);
[Link]("Hello");
[Link]("World");
[Link](3.14f);
[Link](6.28f);
[Link] sc = new [Link]([Link]);
Object elem = [Link]();
[Link](elem);
for (Object o : v) {
[Link](o + " ");
}
}
}
7. Write a program to check whether the string provided by the user is a
palindrome or not.
class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
String rev = new StringBuilder(str).reverse().toString();
[Link]([Link](rev) ? "Palindrome" : "Not Palindrome");
}
}
8. Write a program to print all the Armstrong numbers from 0 to 999.
class ArmstrongNumbers {
public static void main(String[] args) {
for (int i = 0; i <= 999; i++) {
int sum = 0, temp = i, digits = [Link](i).length();
while (temp > 0) {
sum += [Link](temp % 10, digits);
temp /= 10;
}
if (sum == i) [Link](i + " ");
}
}
}
9. Write a program to copy all elements of one array into another array.
class CopyArray {
public static void main(String[] args) {
int[] src = {1,2,3,4,5};
int[] dest = new int[[Link]];
for (int i = 0; i < [Link]; i++) {
dest[i] = src[i];
}
for (int num : dest) {
[Link](num + " ");
}
}
}
10. Write a program to display the ASCII value of a number 9.
class ASCIIValue {
public static void main(String[] args) {
[Link]((int)'9');
}
}
11. Write a program to sort the elements of an array in ascending order.
import [Link];
class ArraySort {
public static void main(String[] args) {
int[] arr = {5,2,9,1,5};
[Link](arr);
for (int num : arr) {
[Link](num + " ");
}
}
}
12. Write a program to show the use of a copy constructor.
class Box {
int length, width;
Box(Box b) {
[Link] = [Link];
[Link] = [Link];
}
Box(int l, int w) {
length = l;
width = w;
}
public static void main(String[] args) {
Box b1 = new Box(10,20);
Box b2 = new Box(b1);
[Link]([Link] + " " + [Link]);
}
}
13. Write a program to print the sum, difference, and product of two
complex numbers.
class Complex {
double real, imag;
Complex(double r, double i) {
real = r;
imag = i;
}
static Complex add(Complex c1, Complex c2) {
return new Complex([Link] + [Link], [Link] + [Link]);
}
static Complex subtract(Complex c1, Complex c2) {
return new Complex([Link] - [Link], [Link] - [Link]);
}
static Complex multiply(Complex c1, Complex c2) {
return new Complex([Link]*[Link] - [Link]*[Link], [Link]*[Link] +
[Link]*[Link]);
}
public static void main(String[] args) {
Complex c1 = new Complex(2,3);
Complex c2 = new Complex(4,5);
Complex sum = add(c1, c2);
Complex diff = subtract(c1, c2);
Complex prod = multiply(c1, c2);
[Link]("Sum: %.1f+%.1fi\n", [Link], [Link]);
[Link]("Difference: %.1f+%.1fi\n", [Link], [Link]);
[Link]("Product: %.1f+%.1fi\n", [Link], [Link]);
}
}
14. Write a program using sqrt() and pow() to calculate the square root and
power of a given number.
class MathOperations {
public static void main(String[] args) {
double num = 25;
[Link]("Square root: " + [Link](num));
[Link]("Power: " + [Link](num, 3));
}
}
15. Write a program to accept four numbers from the user using command
line arguments and print the smallest number.
class SmallestNumber {
public static void main(String[] args) {
int a = [Link](args[0]);
int b = [Link](args[1]);
int c = [Link](args[2]);
int d = [Link](args[3]);
int min = [Link]([Link](a,b), [Link](c,d));
[Link]("Smallest: " + min);
}
}
16. Write a program to check whether the entered number is an Armstrong
number or not.
class ArmstrongCheck {
public static void main(String[] args) {
int num = 153;
int sum = 0, temp = num, digits = [Link](num).length();
while (temp > 0) {
sum += [Link](temp % 10, digits);
temp /= 10;
}
[Link](sum == num ? "Armstrong" : "Not Armstrong");
}
}
Unit II: Inheritance, Interface, and Packages (CO2)
1. Develop a program to create a class Book having data members ‘author’,
‘title’, and ‘price’. Derive a class BookInfo having data member
‘stockposition’ and method to initialize and display the information for
three objects.
class Book {
String author, title;
double price;
}
class BookInfo extends Book {
String stockposition;
void display() {
[Link](author + " " + title + " " + price + " " + stockposition);
}
public static void main(String[] args) {
BookInfo[] books = new BookInfo[3];
[Link] sc = new [Link]([Link]);
for (int i = 0; i < 3; i++) {
books[i] = new BookInfo();
books[i].author = [Link]();
books[i].title = [Link]();
books[i].price = [Link]();
[Link]();
books[i].stockposition = [Link]();
}
for (BookInfo b : books) {
[Link]();
}
}
}
2. 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.
interface Allowance {
double DA_RATE = 0.9;
double HRA_RATE = 0.1;
double PF_RATE = 0.0833;
}
class Salary implements Allowance {
String empid, name;
double basicsalary;
void calculateNet() {
double net = basicsalary + (basicsalary * DA_RATE) + (basicsalary *
HRA_RATE) - (basicsalary * PF_RATE);
[Link]("Net Salary: " + net);
}
public static void main(String[] args) {
Salary s = new Salary();
[Link] = 50000;
[Link]();
}
}
3. Write a program to implement the following inheritance: Interface:
Exam, Class: Student, Class: Result
interface Exam {}
class Student {}
class Result extends Student implements Exam {}
4. Write a program to show Hierarchical inheritance.
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
5. Develop an Interest Interface which contains Simple Interest and
Compound Interest methods and a static final field of rate 25%. Write a
class to implement those methods.
interface Interest {
double RATE = 0.25;
double simpleInterest(double p, double t);
double compoundInterest(double p, double t);
}
class InterestCalc implements Interest {
public double simpleInterest(double p, double t) {
return p * RATE * t;
}
public double compoundInterest(double p, double t) {
return p * [Link](1 + RATE, t) - p;
}
}
6. Implement the following inheritance: Interface: Salary, Class: Employee,
Class: Gross_Salary
interface Salary {}
class Employee {}
class GrossSalary extends Employee implements Salary {}
Unit III: Exception Handling and Multithreading (CO3)
1. 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 500 ms.
class EvenOddThreads {
public static void main(String[] args) {
new Thread(() -> {
for (int i = 2; i <= 50; i += 2) {
[Link]("A: " + i);
if (i % 6 == 0) {
try { [Link](500); } catch (InterruptedException e) {}
}
}
}).start();
new Thread(() -> {
for (int i = 1; i <= 49; i += 2) {
[Link]("B: " + i);
}
}).start();
}
}
2. Define an exception called No Match Exception that is thrown when the
password accepted is not equal to ‘MSBTE’. Write the program.
class NoMatchException extends Exception {
NoMatchException(String msg) { super(msg); }
}
class PasswordCheck {
public static void main(String[] args) {
String input = "password";
try {
if () throw new NoMatchException("Password
mismatch");
} catch (NoMatchException e) {
[Link]([Link]());
}
}
}
3. Write a program to create a user-defined exception in Java.
class CustomException extends Exception {}
class TestException {
public static void main(String[] args) {
try {
throw new CustomException();
} catch (CustomException e) {
[Link]("Custom exception caught");
}
}
}
4. Write a program to print even and odd numbers using two threads with
a delay of 1000ms after each number.
class DelayedThreads {
public static void main(String[] args) {
new Thread(() -> {
for (int i = 0; i <= 10; i += 2) {
[Link]("Even: " + i);
try { [Link](1000); } catch (InterruptedException e) {}
}
}).start();
new Thread(() -> {
for (int i = 1; i <= 9; i += 2) {
[Link]("Odd: " + i);
try { [Link](1000); } catch (InterruptedException e) {}
}
}).start();
}
}
5. Explain two ways of creating threads in Java with a suitable example.
// Extending Thread class
class MyThread extends Thread {
public void run() {
[Link]("Thread running");
}
public static void main(String[] args) {
new MyThread().start();
}
}
// Implementing Runnable interface
class MyRunnable implements Runnable {
public void run() {
[Link]("Runnable running");
}
public static void main(String[] args) {
new Thread(new MyRunnable()).start();
}
}
6. Write a program to create a user-defined exception MIN-BAL. Throw
the exception when the balance in the account is below 500 rupees.
class MinBalException extends Exception {
MinBalException(String msg) { super(msg); }
}
class Account {
public static void main(String[] args) {
int balance = 300;
try {
if (balance < 500) throw new MinBalException("Balance below 500");
} catch (MinBalException e) {
[Link]([Link]());
}
}
}
7. Write a program to create two threads. One thread will display the odd
numbers from 1 to 50, and the other thread will display the even numbers.
class OddEvenThreads {
public static void main(String[] args) {
new Thread(() -> {
for (int i = 1; i <= 49; i += 2) {
[Link]("Odd: " + i);
}
}).start();
new Thread(() -> {
for (int i = 2; i <= 50; i += 2) {
[Link]("Even: " + i);
}
}).start();
}
}
Unit IV: Event Handling using AWT & Swing (CO4)
1. Write a program which displays the functioning of an ATM machine
(Withdraw, Deposit, Check Balance, and Exit).
import [Link].*;
class ATMSimulation {
static double balance = 0;
public static void main(String[] args) {
while (true) {
String choice = [Link]("1. Withdraw\n2.
Deposit\n3. Check Balance\n4. Exit");
switch (choice) {
case "1":
double amt =
[Link]([Link]("Enter amount"));
balance -= amt;
break;
case "2":
amt = [Link]([Link]("Enter
amount"));
balance += amt;
break;
case "3":
[Link](null, "Balance: " + balance);
break;
case "4":
[Link](0);
}
}
}
}