java file
java file
3
Program to check whether the given numbers are friendly pair or
not
1
Printing an array into Zigzag fashion. Suppose you were given an
array of integers, and you are told to sort the integers in a zigzag
5 pattern.
4
Question 1
Problem Statement:
Write a Java program to take input as a command line argument: your name, course,
university roll no, and semester. Display the information.
Java Code:
Sample Output:
5
Question 2
Problem Statement:
Using the switch statement, write a menu-driven program to calculate the maturity amount
of a bank deposit for Term Deposit and Recurring Deposit options.
Java Code:
import java.util.Scanner;
switch (choice) {
case 1:
System.out.println("Enter Principal, Rate of Interest, and Time (years):");
double p = sc.nextDouble();
double r = sc.nextDouble();
int n = sc.nextInt();
double a = p * Math.pow((1 + r / 100), n);
System.out.println("Maturity Amount: " + a);
break;
case 2:
System.out.println("Enter Monthly Installment, Rate of Interest, and Time
(months):");
double mp = sc.nextDouble();
double mr = sc.nextDouble();
int mn = sc.nextInt();
double ma = mp * mn + mp * mn * (mn + 1) / 2.0 * mr / 100 * 1 / 12.0;
System.out.println("Maturity Amount: " + ma);
break;
default:
System.out.println("Invalid option selected.");
}
sc.close();
}
}
Sample Output:
6
Question 3
Problem Statement:
Write a Java program to check whether two numbers are Friendly Pairs or not. A Friendly
Pair has equal abundance: (sum of divisors / number) is the same for both.
Java Code:
import java.util.Scanner;
sc.close();
}
}
Sample Output:
Input: 6 28
Output: Friendly Pair
7
Question 4
Problem Statement:
Write a Java program to replace all 0's with 1 in a given integer.
Java Code:
import java.util.Scanner;
Sample Output:
Input: 102405
Output: 112415
8
Question 5
Problem Statement:
Write a Java program to print an array in Zigzag fashion: a < b > c < d > e < f.
Java Code:
import java.util.Scanner;
Sample Output:
Input: 7
4378621
Output: 3 7 4 8 2 6 1
9
Question 6
Problem Statement:
Write a Java program to rearrange positive and negative numbers in an array. Move
negatives to the beginning.
Java Code:
import java.util.Scanner;
int j = 0;
for (int i = 0; i < 6; i++) {
if (arr[i] < 0) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
j++;
}
}
Sample Output:
Input: 1 -1 2 -2 3 -3
Output: -1 -2 -3 1 3 2
10
Question 7
Problem Statement:
Write a Java program to find the saddle point in a matrix. It should be the min in its row and
max in its column.
Java Code:
import java.util.Scanner;
if (isSaddle) {
System.out.println("Saddle Point: " + minRow + " at (" + i + "," + colIdx + ")");
sc.close();
return;
}
}
11
Question 8
Problem Statement:
Write a Java program to count all 0(1+)0 patterns in a binary string using String class.
Java Code:
import java.util.Scanner;
Sample Output:
Input: 01101111010
Output: 3
13
Question 9
Problem Statement:
Write a Java program to delete vowels from a string using StringBuffer class.
Java Code:
import java.util.Scanner;
Sample Output:
14
Question 10
Problem Statement:
Write a Java program to create a class 'Bank' with account details. Include features like
deposit, withdraw, and change address.
Java Code:
import java.util.Scanner;
class Bank {
String name, address;
int accNo;
double balance;
static int count = 1000;
void display() {
System.out.println("Name: " + name + "\nAddress: " + address +
"\nAccNo: " + accNo + "\nBalance: " + balance);
}
15
Question 11
Define a class WordExample having the following description:
Member Methods:
void countWord(): Find the number of words beginning and ending with a vowel.
void placeWord(): Place the words which begin and end with a vowel at the beginning,
followed by the remaining words as they occur in the sentence.
Java Code:
import java.util.*;
public WordExample(String s) {
strdata = s.trim();
}
17
Question 12
Method Overloading (Compile time Polymorphism):
Create a class called ArrayDemo and overload arrayFunc() function.
1. void arrayFunc(int [], int) – Find all pairs of elements in an array whose sum is equal to a
given number.
2. void arrayFunc(int A[], int p, int B[], int q) – Merge two sorted arrays maintaining order
and filling A with smallest p and B with remaining.
Java Code:
import java.util.*;
System.out.println("Sorted Arrays:");
System.out.println("A: " + Arrays.toString(A));
System.out.println("B: " + Arrays.toString(B));
}
19
Question 13
Method overriding (Runtime Polymorphism), Abstract class and Abstract method,
Inheritance, interfaces:
Write a java program to calculate the area of a rectangle, a square and a circle. Create an
abstract class 'Shape' with three abstract methods namely rectangleArea() taking two
parameters, squareArea() and circleArea() taking one parameter each.
Now create another class ‘Area’ containing all the three methods rectangleArea(),
squareArea() and circleArea() for printing the area of rectangle, square and circle
respectively. Create an object of class Area and call all the three methods.
Java Program
abstract class Shape {
abstract void rectangleArea(double l, double b);
abstract void squareArea(double side);
abstract void circleArea(double radius);
}
Question 14
Write a java program to implement abstract class and abstract method with following
details:
Create a abstract Base Class Temperature Data members: double temp;
Method members: void setTempData(double) abstract void changeTemp()
21
Sub Class Celsius (subclass of Temperature)
Override abstract method changeTemp() to convert degree Celsius into Fahrenheit
temperature by using formula F=9/5*c+32 and display converted temperature
Java Program
abstract class Temperature {
double temp;
void setTempData(double t) {
temp = t;
}
abstract void changeTemp();
}
22
Question: Write a Java program to create an interface that consists of a method to display
volume() as an abstract method and redefine this method in the derived classes to suit their
requirements. Create classes called Cone, Hemisphere and Cylinder that implements the
interface. Using these three classes, design a program that will accept dimensions of a cone,
cylinder and hemisphere interactively and display the volumes.
Volume of cone = (1/3)πr2h Volume of hemisphere = (2/3)πr3 Volume of cylinder = πr2h
Java Code:
Java
import java.util.Scanner;
interface Volume {
void displayVolume();
}
@Override
public void displayVolume() {
@Override
public void displayVolume() {
23
Enter radius: 3
Enter height: 5
Volume of Cone: 47.12
class Employee {
private int employeeId;
private String name;
private int deptId;
25
}
}
}
Output Examples:
2. Valid Input:
3. Enter Employee ID: 2500
4. Enter Employee Name: John
5. Enter Department ID: 3
6.
7. Employee details accepted successfully:
8. Employee ID: 2500
9. Name: John
10. Department ID: 3
11. Invalid Name (first letter not capital):
12. Enter Employee ID: 2500
13. Enter Employee Name: john
14. Enter Department ID: 3
15. Error: First letter of employee name must be in capital letter.
16. Invalid Employee ID (out of range):
17. Enter Employee ID: 1000
18. Enter Employee Name: Alice
19. Enter Department ID: 2
20. Error: Employee ID must be between 2001 and 5001.
class MyCalculator {
/**
* Calculates n raised to the power of p (n^p).
* Throws specific exceptions based on input constraints.
*
* @param n The base integer.
* @param p The exponent integer.
* @return The result of n^p.
27
* @throws Exception if n or p are negative, or if both are zero.
*/
public long power(int n, int p) throws Exception {
if (n < 0 || p < 0) {
throw new Exception("n or p should not be negative.");
}
if (n == 0 && p == 0) {
throw new Exception("n and p should not be zero.");
}
while (in.hasNextInt()) {
int n = in.nextInt();
int p = in.nextInt();
try {
System.out.println(myCalculator.power(n, p));
} catch (Exception e) {
System.out.println(e.toString());
}
}
in.close();
}
}
Output for Sample Input:
243
16
java.lang.Exception: n and p should not be zero.
java.lang.Exception: n or p should not be negative.
java.lang.Exception: n or p should not be negative.
28
ARORA is my friend
Java Code:
Java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* Checks if a given string is a palindrome.
* It ignores case and non-alphanumeric characters.
*
* @param str The string to check.
* @return true if the string is a palindrome, false otherwise.
*/
public static boolean isPalindrome(String str) {
if (str == null || str.isEmpty()) {
return false;
}
if (cleanedStr.isEmpty()) {
return false;
}
int left = 0;
int right = cleanedStr.length() - 1;
29
String
for (String word : words) {
if (isPalindrome(word)) {
palindromeCount++;
}
}
}
public CSthread() {
super("CSthread");
}
@Override
public void run() {
30
Output Example (actual order may vary slightly due to thread scheduling):
CSthread executed 1 times.
ITthread executed 1 times.
CSthread executed 2 times.
ITthread executed 2 times.
CSthread executed 3 times.
ITthread executed 3 times.
CSthread executed 4 times.
ITthread executed 4 times.
CSthread executed 5 times.
ITthread executed 5 times.
CSthread executed 6 times.
ITthread executed 6 times.
CSthread executed 7 times.
ITthread executed 7 times.
CSthread executed 8 times.
ITthread executed 8 times.
CSthread executed 9 times.
ITthread executed 9 times.
CSthread executed 10 times.
ITthread executed 10 times.
Main thread finished.
class SharedBuffer {
synchronized (this) {
32
Problem 21: Collection and Generic Framework - removeEvenLength
Question: Write a method removeEvenLength that takes an ArrayList of Strings as a
parameter and that removes all the strings of even length from the list. (Use ArrayList)
Java Code:
Java
import java.util.ArrayList;
import java.util.Arrays;
System.out.println("\n---");
System.out.println("\n---");
System.out.println("\n---");
36
List 1 after removing even length strings: [hello, program]
---
Original list 2: [four, score, and, seven, years, ago]
List 2 after removing even length strings: [score, seven]
---
Original list 3: [aa, bbbb, cccccc]
List 3 after removing even length strings: []
---
Original list 4: [a, bbb, eeeee]
List 4 after removing even length strings: [a, bbb, eeeee]
list.set(i, second);
list.set(i + 1, first);
}
}
37
System.out.println("\n---");
System.out.println("\n---");
---
Original swapList 2 (odd length): [to, be, or, not, to, be, hamlet]
Swapped swapList 2: [be, to, not, or, be, to, hamlet]
---
39
List C: [10, 20, 30]
List D: [1, 2]
Alternating List 2: [10, 1, 20, 2, 30]
---
List E: [100, 200]
List F: [1, 2, 3, 4]
List E: [100, 200]
List F: [1, 2, 3, 4]
Alternating List 3: [100, 1, 200, 2, 3, 4]
---
List G: []
List H: [1, 2, 3]
Alternating List 4: [1, 2, 3]
Question 23
Problem Statement:
Write a method called alternate that accepts two Lists of integers as its parameters and
returns a new List containing alternating elements from the two lists, in the following order:
• First element from first list
• First element from second list
• Second element from first list
• Second element from second list
• Third element from first list
• Third element from second list
If the lists do not contain the same number of elements, the remaining elements from the
longer list should be placed consecutively at the end.
Java Code:
import java.util.ArrayList;
import java.util.List;
return result;
}
Sample Output:
Input:
List 1: [1, 2, 3, 4, 5]
List 2: [6, 7, 8, 9, 10, 11, 12]
Output:
[1, 6, 2, 7, 3, 8, 4, 9, 5, 10, 11, 12]
Question 24
Problem Statement:
Write a GUI program to develop an application that receives a string in one text field, and
counts the number of vowels in the string and returns it in another text field, when the
button named 'CountVowel' is clicked. When the button named 'Reset' is clicked it will reset
the value of textfield one and textfield two. When the button named 'Exit' is clicked it will
close the application.
Java Code:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
41
frame.add(panel);
frame.setVisible(true);
}
}
Sample Output:
Input: Hello World
Output: 3 vowels
Question 25
Problem Statement:
Building a To-Do Application using JavaFX. Create a GUI-based application where users can
add tasks, mark tasks as complete, and delete tasks from the list.
Java Code:
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) {
tasks = FXCollections.observableArrayList();
ListView<String> taskList = new ListView<>(tasks);
addButton.setOnAction(e -> {
String task = taskInput.getText();
if (!task.isEmpty()) {
tasks.add(task);
43
taskInput.clear();
}
});
deleteButton.setOnAction(e -> {
String selectedTask = taskList.getSelectionModel().getSelectedItem();
tasks.remove(selectedTask);
});
Sample Output:
The application opens a window where users can add tasks, view them in a list, and delete
selected tasks.
Question 26
Problem Statement:
Create a database of employees with the following fields:
• Name
• Code
• Designation
• Salary
a) Write a Java program to create a GUI application that accepts employee data from
TextFields and stores it in a database using JDBC.
b) Write a JDBC program to retrieve all the records from the employee database.
44
stmt.setDouble(4, Double.parseDouble(salaryField.getText()));
stmt.executeUpdate();
JOptionPane.showMessageDialog(frame, "Employee added successfully.");
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, "Error: " + ex.getMessage());
}
});
viewButton.addActionListener(e -> {
try (Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/employee_db", "root",
"password")) {
String query = "SELECT * FROM employees";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
StringBuilder results = new StringBuilder("Employees:
");
while (rs.next()) {
results.append("Name: ").append(rs.getString("name"))
.append(", Code: ").append(rs.getString("code"))
.append(", Designation: ").append(rs.getString("designation"))
.append(", Salary: ").append(rs.getDouble("salary"))
.append("
");
}
JOptionPane.showMessageDialog(frame, results.toString());
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, "Error: " + ex.getMessage());
}
});
frame.add(panel);
frame.setVisible(true);
}
}
Sample Output:
Sample GUI allows user to add employee details and view all employees in the database.
Database Example:
Name: John, Code: E101, Designation: Manager, Salary: 50000.0
Name: Jane, Code: E102, Designation: Developer, Salary: 40000.0
46