You are on page 1of 43

Assignment A/01:

Write a program to convert the given temperature in Fahrenheit to Celsius


using the following
Conversion formula C = (F-32)/1.8 and display the values in a tabular form.

Code:
Import java.lang.*;
import java.util.Scanner;
class temperature{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for(int j=0 ; j<5 ;j++) {
System.out.print("Enter temperature in fahrenheit: "+" ");
Double fahrenheit = sc.nextDouble();
Double celsius = (fahrenheit - 32) / 1.8;
System.out.println("celcious temprature is "+ celsius);

}
sc.close();
}
}
Output:

Page-1
Assignment A/02:
Write a program to find the number of and sum of all integers greater than 100
and less than 200 that are divisible by 7.

Code:
Import java.lang.*;
class DivisibleBySeven {
public static void main(String[] args) {
int count = 0;
int sum = 0;

for (int i = 101; i < 200; i++) {


if (i % 7 == 0) {
count++;
sum += i;
}
}

System.out.println("Number of integers divisible by 7: " +


count);
System.out.println("Sum of integers divisible by 7: " +
sum);
}
}

Output:

Page-2
Assignment A/03:
Write a program to print Floyd’s triangle.
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21

Code:
import java.lang.*;
import java.util.Scanner;
class FloydTriangle{
public static void main (String[]args){
int i,j;

Scanner sc = new Scanner(System.in);


System.out.print("Enter the Number of rows : ");
int rows = sc.nextInt();

int num =1;


System.out.println("Floyd's triangle:");
for(i=1;i<=rows;i++){
for(j=1;j<=i;j++){
System.out.print(num+" ");
num++;
}
System.out.println();
}
}
}

Page-3
Output:

Page-4
Assignment A/04:
Write a program to reverse the digits of the number.

Code:
import java.lang.*;
import java.util.Scanner;
public class ReverseNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
int reversedNumber = 0;
while (number != 0) {
int remainder = number % 10;
reversedNumber = reversedNumber * 10 + remainder;
number = number / 10;
}
System.out.println("Reversed number: " +
reversedNumber);
sc.close();
}
}

Output:

Page-5
Assignment A/05:
Write a program to evaluate the following investment equation.
V = P * (1 + R) N
and print the tables which would give the value of V for various combinations
of the following values of P, R and N.

Code:
import java.lang.*;
import java.util.Scanner;

public class InvestmentTable {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter the principal amount (P): ");


double principal = sc.nextDouble();

System.out.print("Enter the annual interest rate (R): ");


double rate = sc.nextDouble();

System.out.print("Enter the number of years (n): ");


int years = sc.nextInt();

System.out.println("\nYear\tValue");
System.out.println("-------------");

for (int i = 1; i <= years; i++) {


double value = principal * Math.pow(1 + rate/100, i);
System.out.printf("%d\t%.2f%n", i, value);
}

sc.close();
}
}

Page-6
Output:

Page-7
Assignment B/01:
Given are two 1D array A and B which are sorted in ascending order. Write a
program to merge them into a single sorted array C that contains every item
from array A and B in ascending order.

Code:
import java.lang.*;
import java.util.Arrays;
public class MergeSortedArrays {
public static void main(String[] args) {
int[] A = {1, 3, 5, 7};
int[] B = {2, 4, 6, 8};
int[] C = new int[A.length + B.length];
int i = 0, j = 0, k = 0;

System.out.print("Array A :");
System.out.println(Arrays.toString(A));

System.out.print("Array B :");
System.out.println(Arrays.toString(B));

while (i < A.length && j < B.length) {


if (A[i] < B[j]) {
C[k++] = A[i++];
} else {
C[k++] = B[j++];
}
}

while (i < A.length) {


C[k++] = A[i++];
}
while (j < B.length) {
C[k++] = B[j++];
}
System.out.println("Merged array :");
for (int num : C) {
System.out.print(num + " ");
}
}
}

Page-8
Output:

Page-9
Assignment B/02:
Write a program that will read the values of elements of A and B and produce
the product matrix C.

Code:
import java.lang.*;
import java.util.Scanner;
class MatrixProduct {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Read the dimensions of matrix A


System.out.print("Enter the number of rows of matrix A: ");
int rowsA = scanner.nextInt();
System.out.print("Enter the number of columns of matrix A: ");
int colsA = scanner.nextInt();

// Read the dimensions of matrix B


System.out.print("Enter the number of rows of matrix B: ");
int rowsB = scanner.nextInt();
System.out.print("Enter the number of columns of matrix B: ");
int colsB = scanner.nextInt();
// Check if the matrices can be multiplied
if (colsA != rowsB) {
System.out.println("Error: The number of columns of
matrix A must be equal to the number of rows of matrix B.");
scanner.close();
}

// Create matrix A
int[][] matrixA = new int[rowsA][colsA];
System.out.println("Enter the elements of matrix A:");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsA; j++) {
matrixA[i][j] = scanner.nextInt();
}
}
// Create matrix B
int[][] matrixB = new int[rowsB][colsB];
System.out.println("Enter the elements of matrix B:");
for (int i = 0; i < rowsB; i++) {
for (int j = 0; j < colsB; j++) {
matrixB[i][j] = scanner.nextInt();
}
}
Page-10
// Create matrix C (product matrix)
int[][] matrixC = new int[rowsA][colsB];

// Calculate the product matrix


for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
int sum = 0;
for (int k = 0; k < colsA; k++) {
sum += matrixA[i][k] * matrixB[k][j];
}
matrixC[i][j] = sum;
}
}
// Print the product matrix C
System.out.println("Product matrix C:");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
System.out.print(matrixC[i][j] + " ");
}
System.out.println();
}

}
}

Output:

Page-11
Assignment B/03:
Write a program, which will read a text and count all occurrences of a
particular word.

Code:
import java.lang.*;
import java.util.Scanner;
public class WordCounter {
public static void main(String[] args) {
// Read the text from the user
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the text: ");
String text = scanner.nextLine();

// Read the word to count occurrences


System.out.print("Enter the word to count occurrences: ");
String word = scanner.nextLine();

// Count occurrences of the word


int count = countOccurrences(text, word);

// Display the result


System.out.println("Occurrences of '" + word + "': " + count);

// Close the scanner


scanner.close();
}

public static int countOccurrences(String text, String word) {


// Split the text into an array of words
String[] words = text.split("\\s+");

// Initialize the count variable


int count = 0;

// Iterate through the words and count occurrences


for (String w : words) {
if (w.equalsIgnoreCase(word)) {
count++;
}
}

return count;
}
} Page-12
Output:

Page-13
Assignment B/04:
Write a program which will read a string and rewrite it in the alphabetical
order. For example, the word STRING should be written as GINRST.

Code:
import java.lang.*;
import java.util.Arrays;
import java.util.Scanner;

public class AlphabeticalOrder {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();

String sortedString = sortStringAlphabetically(input);


System.out.println("String in alphabetical order: " +
sortedString);
scanner.close();
}

private static String sortStringAlphabetically(String input) {


char[] charArray = input.toCharArray();
Arrays.sort(charArray);
return new String(charArray);
}
}

Output:

Page-14
Assignment B/05:
Write a program that will count the number of characters in a file.

Code:
import java.lang.*;
import java.io.FileReader;
import java.io.IOException;

public class CharacterCounter {


public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java CharacterCounter
<filename>");
return;
}
String filename = args[0];
int characterCount = 0;

try (FileReader reader = new FileReader(filename)) {


int data;
while ((data = reader.read()) != -1) {
characterCount++;
}
} catch (IOException e) {
System.out.println("An error occurred: " +
e.getMessage());
}

System.out.println("Number of characters in the file: " +


characterCount);
}
}
Output:

Page-15
Assignment C/01:
Write a program to create a distance class with methods where distance is
computed in terms of feet and inches, how to create objects of a class and to
see the use of this pointer.

Code:
import java.lang.*;
import java.util.Scanner;

class Distance {
private int feet;
private int inches;

public Distance(int feet, int inches) {


this.feet = feet;
this.inches = inches;
}

public void display() {


System.out.println("Distance: " + feet + " feet and " +
inches + " inches");
}

public void add(Distance d) {


feet += d.feet;
inches += d.inches;
if (inches >= 12) {
feet += inches / 12;
inches %= 12;
}
}
}

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter the first distance:");


System.out.print("Feet: ");
int feet1 = scanner.nextInt();
System.out.print("Inches: ");
int inches1 = scanner.nextInt();
Distance distance1 = new Distance(feet1, inches1);

Page-16
System.out.println("Enter the second distance:");
System.out.print("Feet: ");
int feet2 = scanner.nextInt();
System.out.print("Inches: ");
int inches2 = scanner.nextInt();
Distance distance2 = new Distance(feet2, inches2);

System.out.println("Distances entered:");
distance1.display();
distance2.display();

distance1.add(distance2);
System.out.println("After adding distances:");
distance1.display();

scanner.close();
}
}

Output:

Page-17
Assignment C/02:
Modify the distance class by creating constructor for assigning values (feet and
inches) to the distance object. Create another object and assign the second
object as reference variable to another object reference variable. Further
create a third object which is a clone of the first object.

Code:
import java.lang.*;
import java.util.Scanner;

class Distance {
private int feet;
private int inches;

public Distance(int feet, int inches) {


this.feet = feet;
this.inches = inches;
}

public int getFeet() {


return feet;
}

public int getInches() {


return inches;
}

@Override
public String toString() {
return feet + " feet, " + inches + " inches";
}

public Distance clone() {


return new Distance(feet, inches);
}
}

public class MainDistance {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter feet for first distance: ");


int feet1 = scanner.nextInt();
System.out.print("Enter inches for first distance: ");
int inches1 = scanner.nextInt();
page-18
Distance distance1 = new Distance(feet1, inches1);
System.out.println("First distance: " + distance1);

Distance distance2 = distance1; // Assigning reference


System.out.println("Second distance (reference): " +
distance2);

Distance distance3 = distance1.clone(); // Cloning the object


System.out.println("Third distance (clone): " + distance3);

scanner.close();
}
}

Output:

Page-19
Assignment C/03:
Write a program to show that during function overloading, if no matching
argument is found, then java will apply automatic type conversions (from
lower to higher data type).

Code:
import java.lang.*;
public class TypeConversion {
// Method to add two integers
public static int add(int a, int b) {
System.out.println("Adding two integers");
return a + b;
}

// Method to add two doubles


public static double add(double a, double b) {
System.out.println("Adding two doubles");
return a + b;
}

public static void main(String[] args) {


int intResult = add(5, 10);
System.out.println("Result of adding integers: " +
intResult);

double doubleResult = add(3.14, 2.71);


System.out.println("Result of adding doubles: " +
doubleResult);
// The following line will result in automatic type conversion

Page-20
double mixedResult = add(7, 4.5);
System.out.println("Result of adding mixed types: " +
mixedResult);
}
}

Output:

Page-21
Assignment C/04:
Write a program to show the use of static functions.

Code:
import java.lang.*;
import java.util.Scanner;

public class StaticFunctions{

// Static function to calculate the square of a number


public static int calculateSquare(int num) {
return num * num;
}
// Static function to calculate the cube of a number
public static int calculateCube(int num) {
return num * num * num;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

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


int number = scanner.nextInt();

// Calling static functions using the class name


int squareResult = StaticFunctions.calculateSquare(number);
int cubeResult = StaticFunctions.calculateCube(number);

System.out.println("Number: " + number);


System.out.println("Square: " + squareResult);
System.out.println("Cube: " + cubeResult);
Page-22
scanner.close();
}
}

Output:

Page-23
Assignment C/05:
Write a program to implementation of pass variable length arguments in a
function.

Code:
import java.lang.*;
public class VarArgs {

// Function with variable-length arguments


public static void printNumbers(int... numbers) {
System.out.println("Number of arguments: " +
numbers.length);
System.out.print("Arguments: ");

for (int num : numbers) {


System.out.print(num + " ");
}

System.out.println();
}

public static void main(String[] args) {


// Calling the function with different numbers of arguments
printNumbers(1, 2, 3);
printNumbers(10, 20, 30, 40, 50);
printNumbers(100);
}
}

Output:

Page-24
Assignment D/01:
Write a program to illustrate multilevel inheritance.

Code:
import java.lang.*;
class Animal {
void eat() {
System.out.println("The animal is eating.");
}
}
class Mammal extends Animal {
void run() {
System.out.println("The mammal is running.");
}
}
class Dog extends Mammal {
void bark() {
System.out.println("The dog is barking.");
}
}
public class MultilevelInheritance {
public static void main(String[] args) {
Dog myDog = new Dog();

myDog.eat(); // Inherited from Animal class


myDog.run(); // Inherited from Mammal class
myDog.bark(); // Specific to Dog class
}
}

Output:

Page-25
Assignment D/02:
Write a program to illustrate multiple inheritances using interface.

Code:
import java.lang.*;
// Define two interfaces
interface A {
void methodA();
}
interface B {
void methodB();
}
// Implement the interfaces in a class
class MyClass implements A, B {
@Override
public void methodA() {
System.out.println("Method A implementation");
}
@Override
public void methodB() {
System.out.println("Method B implementation");
}
}
public class Interfaces {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.methodA();
obj.methodB();
}
}

Output:

Page-26
Assignment D/03:
Write a program to show the calling sequence of construction of super and sub
class.

Code:
import java.lang.*;
class Superclass {
public Superclass() {
System.out.println("Superclass constructor");
}

public void printMessage() {


System.out.println("Message from Superclass");
}
}
class Subclass extends Superclass {
public Subclass() {
System.out.println("Subclass constructor");
}

public void printMessage() {


System.out.println("Message from Subclass");
}
}
public class ConstructorCallingSequence {
public static void main(String[] args) {
Subclass subclassObj = new Subclass();
subclassObj.printMessage();
}
}

Output:

Page-27
Assignment D/04:
Write a program to show function overriding and dynamic method dispatch.
Code:
import java.lang.*;
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat meows");
}
}
public class DynamicDethodDispatch {
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();

animal1.makeSound(); // Dynamic method dispatch


animal2.makeSound(); // Dynamic method dispatch
}
}

Output:

Page-28
Assignment D/05:
Write a program that creates illustrates different levels of protection in
classes/subclasses belonging to same packages.

Code:
import java.lang.*;
package mypackage;

class Parent {
private int privateVar = 10;
int defaultVar = 20;
protected int protectedVar = 30;
public int publicVar = 40;

void display() {
System.out.println("Private Variable: " + privateVar);
System.out.println("Default Variable: " + defaultVar);
System.out.println("Protected Variable: " + protectedVar);
System.out.println("Public Variable: " + publicVar);
}
}

class Child extends Parent {


void displayInChild() {
// Inherited variables from Parent class
// System.out.println(privateVar); // Error: privateVar not
accessible
System.out.println("Inherited Default Variable: " +
defaultVar);
System.out.println("Inherited Protected Variable: " +
protectedVar);
System.out.println("Inherited Public Variable: " +
publicVar);
}
}
public class Main {
public static void main(String[] args) {
Parent parentObj = new Parent();
parentObj.display();

System.out.println("----------------");

Child childObj = new Child();


Page-29
childObj.displayInChild();
}
}

Output:

Page-30
Assignment E/01:
Write a program to illustrate index out of bound exception.
Code:
import java.lang.*;
public class IndexOutOfBoundsExceptionExample {
public static void main(String[] args) {
int[] numbers = { 1, 2, 3, 4, 5 };

try {
int index = 10; // Trying to access an index that is out
of bounds
int value = numbers[index];
System.out.println("Value at index " + index + ": " +
value);
} catch (IndexOutOfBoundsException e) {
System.out.println("IndexOutOfBoundsException caught: "
+ e.getMessage());
}
}
}

Output:

Page-31
Assignment E/02:
Write a program to create your own exception types to handle situation
specific to your application.

Code:
import java.lang.*;
import java.util.Scanner;
// Custom exception class
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// Application class
class MyApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

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


int age = scanner.nextInt();

try {
if (age < 0) {
throw new CustomException("Age cannot be negative");
}
System.out.println("Age: " + age);
} catch (CustomException e) {
System.out.println("Error: " + e.getMessage());
} finally {
scanner.close();
}
}
}

Output:

Page-32
Assignment E/03:
Write a program to demonstrate priorities among multiple threads.

Code:
import java.lang.*;
class Priority implements Runnable {
private String name;

public Priority(String name) {


this.name = name;
}

@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(name + ": " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class ThreadPriority {


public static void main(String[] args) {
Thread thread1 = new Thread(new Priority("Thread 1"));
Thread thread2 = new Thread(new Priority("Thread 2"));

// Set thread priorities


thread1.setPriority(Thread.MIN_PRIORITY); // 1
thread2.setPriority(Thread.MAX_PRIORITY); // 10

thread1.start();
thread2.start();
}
}

Page-33
Output:

Page-34
Assignment F/01:
Write a program that create a Banner and then creates a thread to scroll the
message in the banner from left to right across the applet's window.

Code:
File-1 :
import java.lang.*;
import javax.swing.*;
import java.awt.*;
import java.util.concurrent.TimeUnit;

public class BannerApplet extends JApplet implements Runnable {


private String message = "Welcome to My Banner!";
private int xCoordinate = 0;
private boolean running = true;

@Override
public void init() {
// Set the size of the applet window
setSize(400, 100);
// Create a thread to scroll the message
Thread scrollThread = new Thread(this);
scrollThread.start();
}

public void run() {


while (running) {
try {
// Pause to slow down the animation
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Increment the x coordinate to move the message to the
right
xCoordinate += 5;
// Repaint the applet to update the position of the
message
repaint();
}
}

Page-35
@Override
public void paint(Graphics g) {
super.paint(g);
// Clear the applet's window
g.clearRect(0, 0, getWidth(), getHeight());

// Draw the message at the current x coordinate


g.drawString(message, xCoordinate, 50);

// Check if the message has moved off the right side of the
window
if (xCoordinate >= getWidth()) {
// Reset the x coordinate to the left side of the window
xCoordinate = -g.getFontMetrics().stringWidth(message);
}
}

@Override
public void stop() {
// Stop the thread when the applet is stopped or destroyed
running = false;
}
}

File-2 :
<html>
<head>
<title>My First Applet Program</title>
</head>
<body>
<applet code =BannerApplet.class width = 600 height =
100></applet>
</body>
</html>

Note:
File-2 save as a MyApplet.html.

Page-36
Output:

Page-37
Assignment F/04:
Write a program to generate a windows without an applet window.

Code:
import java.lang.*;
import javax.swing.*;

public class SimpleWindow {

public static void main(String[] args) {


// Create a new JFrame (window) instance
JFrame frame = new JFrame("Simple Window");

// Set the size of the window


frame.setSize(400, 300);

// Set the default close operation (exit when the window is


closed)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a JLabel with your message


JLabel label = new JLabel("Hello, this is a simple
window!");

// Add the label to the content pane of the frame


frame.getContentPane().add(label);

// Center the window on the screen


frame.setLocationRelativeTo(null);

// Make the window visible


frame.setVisible(true);
}
}

Page-38
Output:

Page-39
Assignment F/05:
Write a program to demonstrate the use of push buttons.

Code:
File-1 :
import java.lang.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class PushButtonDemo extends Applet implements ActionListener


{

Button clickButton;
Label clickLabel;
int clickCount;

public void init() {


clickButton = new Button("Click Me!");
clickLabel = new Label("No clicks yet.");
clickCount = 0;

clickButton.addActionListener(this);

add(clickButton);
add(clickLabel);
}

public void actionPerformed(ActionEvent e) {


if (e.getSource() == clickButton) {
clickCount++;
clickLabel.setText(String.format("Clicked %d times.",
clickCount));
}
}
}

Page-40
File-2 :
<html>
<head>
<title>My First Applet Program</title>
</head>
<body>
<applet code =PushButtonDemo.class width = 600 height =
100></applet>
</body>
</html>

Note:
File-2 save as a MyApplet.html.

Output:

Page-41
INDEX
S ASSIGNMENT DATE OF PAGE SIGNATURE
NO. NO. ASSIGNMENT NO.
1 A/01, A/02, A/03 02/03/23 1-4

2 A/04, A/05 16/03/23 5-7

3 B/01, B/02, B/03 23/03/23 8-13

4 B/04, B/05 06/04/23 14-15

5 C/01, C/02, C/03 13/04/23 16-21

6 C/04, C/05 27/04/23 22-24

7 D/01, D/02, D/03 04/05/23 25-27

8 D/04, D/05, D/06 11/05/23 28-30

9 E/01, E/02 18/05/23 31-32

10 E/03 25/05/23 33-34

11 F/01 08/06/23 35-37

12 F/04 22/06/23 38-39

13 F/05 13/07/23 40-41

You might also like