0% found this document useful (0 votes)
5 views34 pages

Java Assignment

Java Assignment
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views34 pages

Java Assignment

Java Assignment
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

ASSIGNMENT-1

Set A:
a) Using javap, view the methods of the following classes from the lang
package: java.lang.Object, java.lang.String and java.util.Scanner. and also
Compile sample program 8. Type the following command and view the
bytecodes. javap-c MyClass.

Ans:

1. java.lang.Object
2. java.lang.String
3. java.util.Scanner
4. Sample Program 8 : Program to define a class and an object of the class.

import java.io.*;
public class MyClass {
int num;

public MyClass() {
num = 0;
}

public MyClass(int num) {


this.num = num;
}

public static void main(String[] args) throws IOException {


BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));

MyClass m1 = new MyClass();

System.out.print("Enter a number: ");


String input = br.readLine();

if (input != null && !input.isEmpty()) {


int n = Integer.parseInt(input);
MyClass m2 = new MyClass(n);

System.out.println("m1.num = " + m1.num);


System.out.println("m2.num = " + m2.num);
} else {
System.out.println("Insufficient arguments");
}
}
}
b) Write a program to calculate perimeter and area of rectangle.
(hint : area = length * breadth , perimeter=2*(length+breadth))

Ans:

import java.io.*;

public class Rectangle


{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));

System.out.print("Enter length of rectangle: ");


int length = Integer.parseInt(br.readLine());

System.out.print("Enter breadth of rectangle: ");


int breadth = Integer.parseInt(br.readLine());

int area = length * breadth;


int perimeter = 2 * (length + breadth);

System.out.println("Area of Rectangle = " + area);


System.out.println("Perimeter of Rectangle = " + perimeter);
}
}

Output:
c) Write a menu driven program to perform the following operations:
i. Calculate the volume of cylinder. (hint : Volume: π × r² × h) .
ii. Find the factorial of given number.
iii. Check the number is Armstrong or not.
iv. Exit

Ans:

import java.io.*;

public class MenuProgram {


public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int choice;

do {
System.out.println("\n===== MENU =====");
System.out.println("1. Calculate Volume of Cylinder");
System.out.println("2. Find Factorial of a Number");
System.out.println("3. Check Armstrong Number");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = Integer.parseInt(br.readLine());

switch (choice) {
case 1: // Volume of cylinder
System.out.print("Enter radius: ");
double r = Double.parseDouble(br.readLine());
System.out.print("Enter height: ");
double h = Double.parseDouble(br.readLine());
double volume = Math.PI * r * r * h;
System.out.println("Volume of Cylinder = " + volume);
break;
case 2: // Factorial
System.out.print("Enter a number: ");
int n = Integer.parseInt(br.readLine());
long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
System.out.println("Factorial of " + n + " = " + fact);
break;

case 3: // Armstrong check


System.out.print("Enter a number: ");
int num = Integer.parseInt(br.readLine());
int temp = num, sum = 0, digit, digits = 0;

// count digits
int t = num;
while (t != 0) {
digits++;
t /= 10;
}

// calculate Armstrong sum


t = num;
while (t != 0) {
digit = t % 10;
sum += Math.pow(digit, digits);
t /= 10;
}

if (sum == num) {
System.out.println(num + " is an Armstrong Number.");
} else {
System.out.println(num + " is NOT an Armstrong Number.");
}
break;

case 4:
System.out.println("Exiting program...");
break;

default:
System.out.println("Invalid choice. Please try again.");
}

} while (choice != 4);


}
}

Output:
d) Write a program to accept the array element and display in reverse order.

Ans:

import java.io.*;

public class ReverseArray {

public static void main(String[] args) throws IOException {

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter number of elements: ");

int n = Integer.parseInt(br.readLine());

int arr[] = new int[n];

System.out.println("Enter " + n + " elements:");

for (int i = 0; i < n; i++) {

arr[i] = Integer.parseInt(br.readLine());

System.out.println("Array elements in reverse order:");

for (int i = n - 1; i >= 0; i--) {

System.out.print(arr[i] + " ");

}
Output:
Set B :
a. Write a java program to display the system date and time in various
formats shown below:
Current date is : 31/08/2021
Current date is : 08-31-2021
Current date is : Tuesday August 31 2021
Current date and time is : Fri August 31 15:25:59 IST 2021
Current date and time is : 31/08/21 15:25:59 PM +0530
Current time is : 15:25:59
Current week of year is : 35
Current week of month : 5
Current day of the year is : 243
(Note: Use java.util.Date and java.text.SimpleDateFormat class)

Ans:

import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class DateFormats {


public static void main(String[] args) {
// Current system date and time
Date now = new Date();

// Different date formats


SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat sdf3 = new SimpleDateFormat("EEEE MMMM dd
yyyy");
SimpleDateFormat sdf4 = new SimpleDateFormat("EEE MMMM dd
HH:mm:ss z yyyy");
SimpleDateFormat sdf5 = new SimpleDateFormat("dd/MM/yy
HH:mm:ss a Z");
SimpleDateFormat sdf6 = new SimpleDateFormat("HH:mm:ss");

// Print outputs
System.out.println("Current date is : " + sdf1.format(now));
System.out.println("Current date is : " + sdf2.format(now));
System.out.println("Current date is : " + sdf3.format(now));
System.out.println("Current date and time is : " +
sdf4.format(now));
System.out.println("Current date and time is : " +
sdf5.format(now));
System.out.println("Current time is : " + sdf6.format(now));

// Using Calendar for week/day info


Calendar cal = Calendar.getInstance();
System.out.println("Current week of year is : " +
cal.get(Calendar.WEEK_OF_YEAR));
System.out.println("Current week of month : " +
cal.get(Calendar.WEEK_OF_MONTH));
System.out.println("Current day of the year is : " +
cal.get(Calendar.DAY_OF_YEAR));
}
}

Output:
b. Define a class MyNumber having one private int data member. Write a
default constructor to initialize it to 0 and another constructor to
initialize it to a value (Use this). Write methods isNegative, isPositive,
isZero, isOdd, isEven. Create an object in main. Use command line
arguments to pass a value to the object (Hint : convert string argument
to integer) and perform the above tests. Provide javadoc comments for
all constructors and methods and generate the html help file.

Ans:

/**
* The MyNumber class provides methods to test properties of an
integer number.
* It allows checking whether the number is positive, negative, zero, odd,
or even.
*/
public class MyNumber {
// private data member
private int num;

/**
* Default constructor
* Initializes the number to 0.
*/
public MyNumber() {
this.num = 0;
}

/**
* Parameterized constructor
* Initializes the number to the given value.
* @param num the integer value to initialize
*/
public MyNumber(int num) {
this.num = num;
}

/**
* Checks if the number is negative.
* @return true if number is less than 0, false otherwise
*/
public boolean isNegative() {
return num < 0;
}

/**
* Checks if the number is positive.
* @return true if number is greater than 0, false otherwise
*/
public boolean isPositive() {
return num > 0;
}

/**
* Checks if the number is zero.
* @return true if number is equal to 0, false otherwise
*/
public boolean isZero() {
return num == 0;
}

/**
* Checks if the number is odd.
* @return true if number is not divisible by 2, false otherwise
*/
public boolean isOdd() {
return num % 2 != 0;
}

/**
* Checks if the number is even.
* @return true if number is divisible by 2, false otherwise
*/
public boolean isEven() {
return num % 2 == 0;
}

/**
* Main method to test MyNumber class.
* Accepts a command line argument, converts it to integer,
* creates a MyNumber object and performs checks.
* @param args command line arguments
*/
public static void main(String[] args) {
if (args.length > 0) {
int n = Integer.parseInt(args[0]); // convert string to int
MyNumber myNum = new MyNumber(n);

System.out.println("Number entered: " + n);


System.out.println("isNegative: " + myNum.isNegative());
System.out.println("isPositive: " + myNum.isPositive());
System.out.println("isZero: " + myNum.isZero());
System.out.println("isOdd: " + myNum.isOdd());
System.out.println("isEven: " + myNum.isEven());
} else {
System.out.println("Please provide a number as command line
argument.");
}
}
}

Output:
c. Write a menu driven program to perform the following operations on
multidimensional array ie matrix :

i. Addition

ii. Multiplication

iii. Transpose of any matrix.

iv. Exit

Ans :

import java.io.*;

public class MatrixOperations {

public static void main(String[] args) throws IOException {

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

int choice;

do {

System.out.println("\n===== MATRIX MENU =====");

System.out.println("1. Addition of Matrices");

System.out.println("2. Multiplication of Matrices");

System.out.println("3. Transpose of a Matrix");

System.out.println("4. Exit");

System.out.print("Enter your choice: ");

choice = Integer.parseInt(br.readLine());
switch (choice) {

case 1: // Matrix Addition

System.out.print("Enter rows of matrices: ");

int r1 = Integer.parseInt(br.readLine());

System.out.print("Enter columns of matrices: ");

int c1 = Integer.parseInt(br.readLine());

int[][] A = new int[r1][c1];

int[][] B = new int[r1][c1];

int[][] sum = new int[r1][c1];

System.out.println("Enter elements of Matrix A:");

for (int i = 0; i < r1; i++) {

for (int j = 0; j < c1; j++) {

A[i][j] = Integer.parseInt(br.readLine());

System.out.println("Enter elements of Matrix B:");

for (int i = 0; i < r1; i++) {

for (int j = 0; j < c1; j++) {

B[i][j] = Integer.parseInt(br.readLine());
}

for (int i = 0; i < r1; i++) {

for (int j = 0; j < c1; j++) {

sum[i][j] = A[i][j] + B[i][j];

System.out.println("Resultant Matrix after Addition:");

for (int i = 0; i < r1; i++) {

for (int j = 0; j < c1; j++) {

System.out.print(sum[i][j] + " ");

System.out.println();

break;

case 2: // Matrix Multiplication

System.out.print("Enter rows of Matrix A: ");

int ra = Integer.parseInt(br.readLine());

System.out.print("Enter columns of Matrix A: ");

int ca = Integer.parseInt(br.readLine());
System.out.print("Enter rows of Matrix B: ");

int rb = Integer.parseInt(br.readLine());

System.out.print("Enter columns of Matrix B: ");

int cb = Integer.parseInt(br.readLine());

if (ca != rb) {

System.out.println("Matrix multiplication not possible (columns


of A != rows of B).");

break;

int[][] MA = new int[ra][ca];

int[][] MB = new int[rb][cb];

int[][] prod = new int[ra][cb];

System.out.println("Enter elements of Matrix A:");

for (int i = 0; i < ra; i++) {

for (int j = 0; j < ca; j++) {

MA[i][j] = Integer.parseInt(br.readLine());

System.out.println("Enter elements of Matrix B:");


for (int i = 0; i < rb; i++) {

for (int j = 0; j < cb; j++) {

MB[i][j] = Integer.parseInt(br.readLine());

for (int i = 0; i < ra; i++) {

for (int j = 0; j < cb; j++) {

prod[i][j] = 0;

for (int k = 0; k < ca; k++) {

prod[i][j] += MA[i][k] * MB[k][j];

System.out.println("Resultant Matrix after Multiplication:");

for (int i = 0; i < ra; i++) {

for (int j = 0; j < cb; j++) {

System.out.print(prod[i][j] + " ");

System.out.println();

break;
case 3: // Transpose

System.out.print("Enter rows of Matrix: ");

int r = Integer.parseInt(br.readLine());

System.out.print("Enter columns of Matrix: ");

int c = Integer.parseInt(br.readLine());

int[][] M = new int[r][c];

System.out.println("Enter elements of Matrix:");

for (int i = 0; i < r; i++) {

for (int j = 0; j < c; j++) {

M[i][j] = Integer.parseInt(br.readLine());

System.out.println("Transpose of Matrix:");

for (int i = 0; i < c; i++) {

for (int j = 0; j < r; j++) {

System.out.print(M[j][i] + " ");

System.out.println();

break;
case 4:

System.out.println("Exiting program...");

break;

default:

System.out.println("Invalid choice. Please try again.");

} while (choice != 4);

Output :

1. Addition of Matrices.
2. Multiplication of Matrices

3. Transpose of a Matrix & Exit


Set C :
a. Write a program to accept n names of country and display them in
descending order.

Ans :

import java.io.*;

import java.util.Arrays;

import java.util.Collections;

public class CountrySort {

public static void main(String[] args) throws IOException {

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

// Accept number of countries

System.out.print("Enter number of countries: ");

int n = Integer.parseInt(br.readLine());

String[] countries = new String[n];

// Accept country names

System.out.println("Enter " + n + " country names:");

for (int i = 0; i < n; i++) {

countries[i] = br.readLine();
}

// Sort in descending order

Arrays.sort(countries, Collections.reverseOrder());

// Display result

System.out.println("\nCountries in Descending Order:");

for (String country : countries) {

System.out.println(country);

Output:
b. Write a menu driven program to perform the following operations on
2D array:
i. Sum of diagonal elements
ii. Sum of upper diagonal elements
iii. Sum of lower diagonal elements
iv. Exit.

Ans:

import java.io.*;

public class MatrixDiagonalOperations {


public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));

// Accept matrix size


System.out.print("Enter order of square matrix (n): ");
int n = Integer.parseInt(br.readLine());

int[][] matrix = new int[n][n];

// Accept matrix elements


System.out.println("Enter elements of " + n + "x" + n + "
matrix:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = Integer.parseInt(br.readLine());
}
}

int choice;
do {
System.out.println("\n===== MATRIX MENU =====");
System.out.println("1. Sum of Diagonal Elements");
System.out.println("2. Sum of Upper Diagonal
Elements");
System.out.println("3. Sum of Lower Diagonal
Elements");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = Integer.parseInt(br.readLine());

switch (choice) {
case 1: // Diagonal sum
int diagSum = 0;
for (int i = 0; i < n; i++) {
diagSum += matrix[i][i];
}
System.out.println("Sum of Diagonal Elements = " +
diagSum);
break;

case 2: // Upper diagonal sum


int upperSum = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) { // elements above
main diagonal
upperSum += matrix[i][j];
}
}
System.out.println("Sum of Upper Diagonal
Elements = " + upperSum);
break;

case 3: // Lower diagonal sum


int lowerSum = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) { // elements below main
diagonal
lowerSum += matrix[i][j];
}
}
System.out.println("Sum of Lower Diagonal
Elements = " + lowerSum);
break;

case 4:
System.out.println("Exiting program...");
break;

default:
System.out.println("Invalid choice. Try again.");
}
} while (choice != 4);
}
}

Output :
c. Write a program to display the 1 to 15 tables.

(1 * 1 = 1 2*1=2 3*1=3 ... 15 * 1 = 15

1*2=2 2*2=4 3*2=6 ... 15 * 2 = 30

1*3=3 2*3=6 3*3=9 ... 15 * 3 = 45

...

1 * 10 = 10 2 * 10 = 20 3 * 10 = 30 ... 15 * 10 = 150)

Ans:

import java.io.*;
public class Tables {
public static void main(String[] args) throws IOException {
// Outer loop for multiplier (1 to 10)
for (int i = 1; i <= 10; i++) {
// Inner loop for numbers 1 to 15
for (int j = 1; j <= 15; j++) {
// Print each expression in fixed width
System.out.printf("%-12s", j + " * " + i + " = " + (j * i));
}
System.out.println(); // move to next line
}
}
}
Output :

***************************************************

You might also like