0% found this document useful (0 votes)
108 views15 pages

Java Programming Exercises and Solutions

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
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)
108 views15 pages

Java Programming Exercises and Solutions

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

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 (![Link]("MSBTE")) 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);
}
}
}
}

Common questions

Powered by AI

The `PalindromeCheck` class determines whether a string is a palindrome by first reversing the input string using `StringBuilder(str).reverse().toString()`. It then compares the reversed string to the original string with `str.equals(rev)`. If the two strings are equal, it prints 'Palindrome'; otherwise, it prints 'Not Palindrome'. The logic effectively checks if the string reads the same backward as forward .

The `SmallestNumber` program handles potential input-related errors by using `Integer.parseInt` to safely convert string arguments to integers, ensuring that inappropriate input types will result in managed exceptions rather than program termination. However, it assumes four arguments will be provided, which could generate `ArrayIndexOutOfBoundsException` if fewer are given, though this potential issue was not explicitly addressed within the code. The approach focuses on type conversion assurance and calculation logic encapsulation .

Polymorphism is utilized in Java through interfaces by allowing a class to implement multiple interfaces, thereby exhibiting multiple forms. In the example with `Exam`, `Student`, and `Result`, `Result` extends `Student` and implements `Exam`, which means `Result` can be treated either as a `Student` or as an `Exam`, depending on the context. This flexibility allows methods to interact with objects of any class that implements the `Exam` interface, promoting code reusability and flexibility .

The `Account` class handles exceptions by defining a custom exception `MinBalException` thrown when the account balance is below 500. In the `main` method, the balance is checked, and if below the threshold, `MinBalException` is thrown and caught. This approach provides more meaningful error handling that is specific to the application, improving readability and pinpointing exact issues, which enhances debugging and maintenance processes .

The `Box` class utilizes a copy constructor, which is a form of the prototype design pattern. This pattern is used to create a new object as a copy of an existing object. The constructor `Box(Box b)` copies the values of fields `length` and `width` from an existing instance, `b`, to a new instance. This reduces the risk of side effects from unintended changes to shared references, promoting object cloning .

The `Salary` interface and its implementing class `Salary` separate concerns by defining constants and a structure for calculating allowances (DA, HRA, PF) in the interface, while the executing logic for calculating net salary resides in the implementing class. This separation allows for clear encapsulation of payroll constants and calculation logic, enhancing modularity and maintainability of code. The interface acts as a contract for what a `Salary` should include, while the class specifies how these elements are actually calculated .

Using interfaces like `Interest` to manage common functionality is effective in Java due to polymorphism, allowing different classes to implement the same interface methods uniquely while maintaining a consistent contract. The `Interest` interface defines methods for calculating simple and compound interest, encapsulating these operations under a shared interface, allowing for flexible and modular design and reducing code duplication .

The bubble sort algorithm, as demonstrated in the `BubbleSort` class, has potential drawbacks when applied to large datasets. It is an O(n^2) algorithm, making it inefficient for large datasets due to its quadratic time complexity. The algorithm repeatedly steps through the list, compares adjacent elements, and swaps them if necessary, which can result in a high number of swaps and comparisons. This leads to increased time consumption compared to more efficient algorithms like quicksort or mergesort for large datasets .

The Java `BubbleSort` program sorts a 1-D array using the bubble sort algorithm. It performs sorting by repeatedly iterating over the array and comparing adjacent elements. If an element is greater than the next one, they are swapped. This process is repeated for each element until the array is sorted. The key steps include initializing a for loop to pass through the array, another nested loop for comparing elements, checking and swapping elements if they are out of order, and printing the sorted array at the end .

Extending the `Thread` class directly allows for the creation of a thread by inheriting from `Thread` and overriding the `run()` method. However, it doesn't allow the inheritance of other classes due to Java's single inheritance model. Implementing `Runnable` separates the task to be executed in the thread from the thread management itself, allowing the class to extend other classes if necessary. This approach is generally preferred for flexibility and adherence to good design principles, such as separation of concerns .

You might also like