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

Java Code Only Answers-1

The document contains a series of Java programming exercises covering basic syntactical constructs, inheritance, exception handling, multithreading, and event handling using AWT and Swing. Each exercise includes a specific task followed by a Java code solution. The tasks range from finding even numbers, sorting arrays, checking for prime numbers, to implementing multithreading and creating user-defined exceptions.

Uploaded by

aestheditsedit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Java Code Only Answers-1

The document contains a series of Java programming exercises covering basic syntactical constructs, inheritance, exception handling, multithreading, and event handling using AWT and Swing. Each exercise includes a specific task followed by a Java code solution. The tasks range from finding even numbers, sorting arrays, checking for prime numbers, to implementing multithreading and creating user-defined exceptions.

Uploaded by

aestheditsedit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

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) {
System.out.print(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 < arr.length-1; i++) {
for (int j = 0; j < arr.length-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) {
System.out.print(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 <= Math.sqrt(num); i++) {
if (num % i == 0) {
flag = true;
break;
}
}
System.out.println(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];
java.util.Scanner sc = new java.util.Scanner(System.in);
for (int i = 0; i < 3; i++) {
emp[i] = new Employee();
emp[i].empid = sc.nextInt();
emp[i].name = sc.next();
emp[i].salary = sc.nextDouble();
}
for (Employee e : emp) {
System.out.println(e.empid + " " + e.name + " " + e.salary);
}
}
}

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;
}
System.out.println(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 java.util.Vector;
class VectorDemo {
public static void main(String[] args) {
Vector<Object> v = new Vector<>();
v.add(10);
v.add(20);
v.add("Hello");
v.add("World");
v.add(3.14f);
v.add(6.28f);
java.util.Scanner sc = new java.util.Scanner(System.in);
Object elem = sc.nextLine();
v.remove(elem);
for (Object o : v) {
System.out.print(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();
System.out.println(str.equals(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 = String.valueOf(i).length();
while (temp > 0) {
sum += Math.pow(temp % 10, digits);
temp /= 10;
}
if (sum == i) System.out.print(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[src.length];
for (int i = 0; i < src.length; i++) {
dest[i] = src[i];
}
for (int num : dest) {
System.out.print(num + " ");
}
}
}

10. Write a program to display the ASCII value of a number 9.

class ASCIIValue {
public static void main(String[] args) {
System.out.println((int)'9');
}
}

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

import java.util.Arrays;
class ArraySort {
public static void main(String[] args) {
int[] arr = {5,2,9,1,5};
Arrays.sort(arr);
for (int num : arr) {
System.out.print(num + " ");
}
}
}

12. Write a program to show the use of a copy constructor.

class Box {
int length, width;
Box(Box b) {
this.length = b.length;
this.width = b.width;
}
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);
System.out.println(b2.length + " " + b2.width);
}
}

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(c1.real + c2.real, c1.imag + c2.imag);
}
static Complex subtract(Complex c1, Complex c2) {
return new Complex(c1.real - c2.real, c1.imag - c2.imag);
}
static Complex multiply(Complex c1, Complex c2) {
return new Complex(c1.real*c2.real - c1.imag*c2.imag, c1.real*c2.imag +
c1.imag*c2.real);
}
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);
System.out.printf("Sum: %.1f+%.1fi\n", sum.real, sum.imag);
System.out.printf("Difference: %.1f+%.1fi\n", diff.real, diff.imag);
System.out.printf("Product: %.1f+%.1fi\n", prod.real, prod.imag);
}
}

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;
System.out.println("Square root: " + Math.sqrt(num));
System.out.println("Power: " + Math.pow(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 = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = Integer.parseInt(args[2]);
int d = Integer.parseInt(args[3]);
int min = Math.min(Math.min(a,b), Math.min(c,d));
System.out.println("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 = String.valueOf(num).length();
while (temp > 0) {
sum += Math.pow(temp % 10, digits);
temp /= 10;
}
System.out.println(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() {
System.out.println(author + " " + title + " " + price + " " + stockposition);
}
public static void main(String[] args) {
BookInfo[] books = new BookInfo[3];
java.util.Scanner sc = new java.util.Scanner(System.in);
for (int i = 0; i < 3; i++) {
books[i] = new BookInfo();
books[i].author = sc.nextLine();
books[i].title = sc.nextLine();
books[i].price = sc.nextDouble();
sc.nextLine();
books[i].stockposition = sc.nextLine();
}
for (BookInfo b : books) {
b.display();
}
}
}

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);
System.out.println("Net Salary: " + net);
}
public static void main(String[] args) {
Salary s = new Salary();
s.basicsalary = 50000;
s.calculateNet();
}
}

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 * Math.pow(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) {
System.out.println("A: " + i);
if (i % 6 == 0) {
try { Thread.sleep(500); } catch (InterruptedException e) {}
}
}
}).start();
new Thread(() -> {
for (int i = 1; i <= 49; i += 2) {
System.out.println("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 (!input.equals("MSBTE")) throw new NoMatchException("Password
mismatch");
} catch (NoMatchException e) {
System.out.println(e.getMessage());
}
}
}

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) {
System.out.println("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) {
System.out.println("Even: " + i);
try { Thread.sleep(1000); } catch (InterruptedException e) {}
}
}).start();
new Thread(() -> {
for (int i = 1; i <= 9; i += 2) {
System.out.println("Odd: " + i);
try { Thread.sleep(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() {
System.out.println("Thread running");
}
public static void main(String[] args) {
new MyThread().start();
}
}

// Implementing Runnable interface


class MyRunnable implements Runnable {
public void run() {
System.out.println("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) {
System.out.println(e.getMessage());
}
}
}

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) {
System.out.println("Odd: " + i);
}
}).start();
new Thread(() -> {
for (int i = 2; i <= 50; i += 2) {
System.out.println("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 javax.swing.*;
class ATMSimulation {
static double balance = 0;
public static void main(String[] args) {
while (true) {
String choice = JOptionPane.showInputDialog("1. Withdraw\n2.
Deposit\n3. Check Balance\n4. Exit");
switch (choice) {
case "1":
double amt =
Double.parseDouble(JOptionPane.showInputDialog("Enter amount"));
balance -= amt;
break;
case "2":
amt = Double.parseDouble(JOptionPane.showInputDialog("Enter
amount"));
balance += amt;
break;
case "3":
JOptionPane.showMessageDialog(null, "Balance: " + balance);
break;
case "4":
System.exit(0);
}
}
}
}

You might also like