0% found this document useful (0 votes)
24 views19 pages

Avi Oops

oops file ggsip

Uploaded by

Pranay Sharma
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)
24 views19 pages

Avi Oops

oops file ggsip

Uploaded by

Pranay Sharma
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/ 19

INDEX

Date of Checked Signature /


S. No. Name of the experiment
implementation date Remarks

Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11


Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11
Experiment-1

Generate a random number up to 100 and print whether it is prime or not

import java.util.Random;

public class PrimeNumberChecker {


public static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}

public static void main(String[] args) {


Random random = new Random();
int randomNumber = random.nextInt(100) + 1;
boolean isPrimeNumber = isPrime(randomNumber);

System.out.println("Random number generated: " + randomNumber);


if (isPrimeNumber) {
System.out.println("The number is prime.");
} else {
System.out.println("The number is not prime.");
}
}
}

Output:

Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11


Experiment-2 (A)

Design a program to generate first 10 terms of Fibonacci series

public class FibonacciSeries {


public static void main(String[] args) {
int n = 10;
int firstTerm = 0, secondTerm = 1;

System.out.println("First " + n + " terms of Fibonacci series:");

System.out.print(firstTerm + " " + secondTerm + " ");

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


int nextTerm = firstTerm + secondTerm;
System.out.print(nextTerm + " ");
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}

Output:

Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11


Experiment-2 (B)

Find the factorial of a given number using recursion

public class FactorialCalculator {


public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}

public static void main(String[] args) {


int number = 5; // Change this to the desired number
int result = factorial(number);
System.out.println("Factorial of " + number + " is: " + result);
}
}

Output:

Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11


Experiment-3

Find the average and sum of array of N numbers entered by user

import java.util.Scanner;

public class ArrayAverageAndSum {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();

int[] arr = new int[n];

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


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

int sum = 0;
for (int num : arr) {
sum += num;
}
double average = (double) sum / n;

System.out.println("Sum of the numbers: " + sum);


System.out.println("Average of the numbers: " + average);
scanner.close();
}
}

Output:

Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11


Experiment-4

Create a class to find out the area & perimeter of a rectangle

public class Rectangle {


private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

public double calculateArea() {


return length * width;
}

public double calculatePerimeter() {


return 2 * (length + width);
}

public static void main(String[] args) {


Rectangle rectangle = new Rectangle(5, 3);

System.out.println("Area of the rectangle: " + rectangle.calculateArea());


System.out.println("Perimeter of the rectangle: " + rectangle.calculatePerimeter());
}
}

Output:

Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11


Experiment-5

Design a class that performs string operations (Equal, Reverse the string,
Change case)

public class StringOperations {


private String inputString;

public StringOperations(String inputString) {


this.inputString = inputString;
}

public boolean isEqual(String otherString) {


return inputString.equals(otherString);
}

public String reverseString() {


StringBuilder reversedString = new StringBuilder(inputString);
return reversedString.reverse().toString();
}

public String changeCase() {


return inputString.toUpperCase();
}

public static void main(String[] args) {


StringOperations stringOps = new StringOperations("Hello");

String otherString = "hello";


System.out.println("Are the strings equal? " + stringOps.isEqual(otherString));
System.out.println("Reversed string: " + stringOps.reverseString());
System.out.println("Uppercase string: " + stringOps.changeCase());
}
}

Output:

Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11


Experiment-6

Demonstrate the use of final keyword with data member, function & class

public class FinalDemo {


final int constantValue = 10;

final void displayMessage() {


System.out.println("This is a final method.");
}

public static void main(String[] args) {


FinalDemo finalObj = new FinalDemo();
System.out.println("Constant value: " + finalObj.constantValue);
finalObj.displayMessage();

// finalObj.constantValue = 20; // Uncommenting this line will result in a


compilation error

// class SubClass extends FinalDemo {


// void displayMessage() {
// System.out.println("This is an overridden final method.");
// }
// }
// Uncommenting this code will result in a compilation error
}
}

Output:

Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11


Experiment-7

Demonstrate the use of keywords try, catch, finally, throw & throws
import java.util.Scanner;

public class ExceptionHandlingDemo {


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

try {
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();

double result = divide(num1, num2);


System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
scanner.close();
System.out.println("Scanner closed.");
}
}

public static double divide(int dividend, int divisor) throws ArithmeticException {


if (divisor == 0) {
throw new ArithmeticException("Division by zero error.");
}
return (double) dividend / divisor;
}
}

Output:

Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11


Experiment-8

Design a program to demonstrate multi-threading using Thread class


public class MultiThreadingDemo {
public static void main(String[] args) {
Thread thread1 = new MyThread("Thread 1");
Thread thread2 = new MyThread("Thread 2");
thread1.start();
thread2.start();
}
}

class MyThread extends Thread {


private String threadName;
public MyThread(String threadName) {
this.threadName = threadName;
}

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

Output:

Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11


Experiment-9

Design a program to create game ‘Tic Tac Toe’


import java.util.Scanner;

public class TicTacToe {


private static final int BOARD_SIZE = 3;
private static final char EMPTY_CELL = ' ';
private static final char PLAYER_X = 'X';
private static final char PLAYER_O = 'O';
private static char[][] board = new char[BOARD_SIZE][BOARD_SIZE];
private static char currentPlayer = PLAYER_X;

public static void main(String[] args) {


initializeBoard();
displayBoard();

Scanner scanner = new Scanner(System.in);


boolean gameRunning = true;

while (gameRunning) {
System.out.println("Player " + currentPlayer + "'s turn.");
System.out.print("Enter row number (0-2): ");
int row = scanner.nextInt();
System.out.print("Enter column number (0-2): ");
int col = scanner.nextInt();

if (isValidMove(row, col)) {
makeMove(row, col);
displayBoard();
if (isWinner()) {
System.out.println("Player " + currentPlayer + " wins!");
gameRunning = false;
} else if (isBoardFull()) {
System.out.println("It's a draw!");
gameRunning = false;
} else {
switchPlayer();
}
} else {
System.out.println("Invalid move! Please try again.");
}
}
Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11
scanner.close();
}

private static void initializeBoard() {


for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = EMPTY_CELL;
}
}
}

private static void displayBoard() {


System.out.println("-------------");
for (int i = 0; i < BOARD_SIZE; i++) {
System.out.print("| ");
for (int j = 0; j < BOARD_SIZE; j++) {
System.out.print(board[i][j] + " | ");
}
System.out.println();
System.out.println("-------------");
}
}

private static boolean isValidMove(int row, int col) {


return row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE &&
board[row][col] == EMPTY_CELL;
}

private static void makeMove(int row, int col) {


board[row][col] = currentPlayer;
}

private static boolean isWinner() {


return checkRows() || checkColumns() || checkDiagonals();
}

private static boolean checkRows() {


for (int i = 0; i < BOARD_SIZE; i++) {
if (board[i][0] == currentPlayer && board[i][1] == currentPlayer && board[i][2]
== currentPlayer) {
return true;

}
Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11
}
return false;
}

private static boolean checkColumns() {


for (int i = 0; i < BOARD_SIZE; i++) {
if (board[0][i] == currentPlayer && board[1][i] == currentPlayer && board[2][i]
== currentPlayer) {
return true;
}
}
return false;
}

private static boolean checkDiagonals() {


return (board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2]
[2] == currentPlayer) ||
(board[0][2] == currentPlayer && board[1][1] == currentPlayer &&
board[2][0] == currentPlayer);
}

private static boolean isBoardFull() {


for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == EMPTY_CELL) {
return false;
}
}
}
return true;
}

private static void switchPlayer() {


currentPlayer = (currentPlayer == PLAYER_X) ? PLAYER_O : PLAYER_X;
}
}

Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11


Output:

Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11


Experiment-10

Design a program to read a text file and after printing that on screen, write
the content to another file
import java.io.*;

public class FileReadWrite {


public static void main(String[] args) {
String inputFile = "input.txt";
String outputFile = "output.txt";

try {
FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);

String line;
System.out.println("Content of input file:");
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();

FileWriter fileWriter = new FileWriter(outputFile);


BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

fileReader = new FileReader(inputFile);


bufferedReader = new BufferedReader(fileReader);

System.out.println("\nWriting content to output file:");


while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
bufferedWriter.newLine();
System.out.println(line);
}

bufferedReader.close();
bufferedWriter.close();

System.out.println("Content successfully written to output file.");

} catch (IOException e) {
e.printStackTrace();

Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11


}
}
}

Output:

Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11


Experiment-11

Design a program to count number of words, characters, vowels in a text file


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TextFileAnalysis {

public static void main(String[] args) {


String filename = "input.txt";
int wordCount = 0;
int charCount = 0;
int vowelCount = 0;

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


String line;
while ((line = reader.readLine()) != null) {
charCount += line.length();
String[] words = line.split("\\s+");
wordCount += words.length;
for (String word : words) {
for (char ch : word.toLowerCase().toCharArray()) {
if (isVowel(ch)) {
vowelCount++;
}
}
}
}

System.out.println("Number of words: " + wordCount);


System.out.println("Number of characters: " + charCount);
System.out.println("Number of vowels: " + vowelCount);

} catch (IOException e) {
e.printStackTrace();
}
}

private static boolean isVowel(char ch) {


return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}
}

Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11


Output:

Name: PRANAY SHARMA Enrolment No.: 04415611922 Section: S11

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy