0% found this document useful (0 votes)
11 views8 pages

Java Programs: Prime, Fibonacci, Calculator

The document contains multiple Java programs demonstrating various concepts, including prime number generation, Fibonacci series (both iterative and recursive), matrix addition, file reading, a simple calculator, file information retrieval, and exception handling for negative numbers and arithmetic errors. Each program is structured with a main method that takes user input and performs the respective operations. The code is organized into separate packages for clarity and modularity.

Uploaded by

arvindhaari
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)
11 views8 pages

Java Programs: Prime, Fibonacci, Calculator

The document contains multiple Java programs demonstrating various concepts, including prime number generation, Fibonacci series (both iterative and recursive), matrix addition, file reading, a simple calculator, file information retrieval, and exception handling for negative numbers and arithmetic errors. Each program is structured with a main method that takes user input and performs the respective operations. The code is organized into separate packages for clarity and modularity.

Uploaded by

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

EXP-1

2.1.1. Prime Numbers List

package q81017;
import [Link];

public class PrimeNumbersList {


public static boolean isPrime(int num) {
if (num <= 1) return false;
if (num == 2) return true;
if (num % 2 == 0) return false;
for (int i = 3; i <= [Link](num); i += 2) {
if (num % i == 0) return false;
}
return true;
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);
int limit = [Link]();
[Link]();

boolean foundPrime = false;

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


if (isPrime(i)) {
[Link](i + " ");
foundPrime = true;
}
}

if (!foundPrime) {
[Link]("No prime numbers found");
}
}

}
EXP-2

2.1.2. Fibonacci Series without Recursion


package q81023;
import [Link];
public class FibonacciSequence {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);
int n = [Link]();
[Link]();

if (n <= 0) {
[Link]("Invalid input");
return;
}

// Handle the first two terms separately


int a = 0, b = 1;

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


[Link](a + " ");
int next = a + b;
a = b;
b = next;
}
}

2.1.3. Fibonacci Series using Recursion

package q81024;
import [Link];
public class FibonacciSeries {
public static void printFibonacci(int n, int firstTerm, int secondTerm) {
if (n == 0) {
return; // base case: no more terms to print
}
[Link](firstTerm + " ");

// Write your code here...


printFibonacci(n - 1, secondTerm, firstTerm + secondTerm);

}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int n = [Link]();
[Link]();
if (n <= 0) {
[Link]("Invalid input");
} else {
printFibonacci(n, 0, 1);
}
}
}

EXP-3

2.1.4. Matrix Addition


package q81026;
import [Link];

public class MatrixAddition {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

int n = [Link]();

int[][] matrix1 = new int[n][n];


int[][] matrix2 = new int[n][n];
int[][] sum = new int[n][n];

// Input first matrix


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix1[i][j] = [Link]();
}
}

// Input second matrix


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix2[i][j] = [Link]();
}
}

// Add matrices
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

// Print result
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
[Link](sum[i][j] + " ");
}
[Link]();
}

[Link]();
}

EXP-4

2.1.5. Read File

package q81029;
import [Link];
import [Link];
import [Link];
import [Link];

public class FileReaderExample {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);
String fileName = [Link]();
[Link]();

try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {


String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]("File not found");
}
}
}
EXP-5

2.1.6. Simple Calculator using Class, Objects and Methods

package q81039;
import [Link];

public class Calculator {


private double operand1;
private double operand2;

// Constructor
public Calculator(double operand1, double operand2) {
this.operand1 = operand1;
this.operand2 = operand2;
}

// add method
public double add() {
return operand1 + operand2;
}

// subtract method
public double subtract() {
return operand1 - operand2;
}

// multiply method
public double multiply() {
return operand1 * operand2;
}

// divide method
public double divide() {
if (operand2 == 0) {
throw new ArithmeticException("Division by zero");
}
return operand1 / operand2;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

double num1 = [Link]();


double num2 = [Link]();

Calculator calc = new Calculator(num1, num2);

[Link]("Addition: " + [Link]());


[Link]("Subtraction: " + [Link]());
[Link]("Multiplication: " + [Link]());

try {
[Link]("Division: " + [Link]());
} catch (ArithmeticException e) {
[Link]([Link]());
}

[Link]();
}
}

EXP-6

2.1.7. File Information


package q81036;
import [Link];
import [Link];

public class FileInfo {

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

// Read file name from user


String fileName = [Link]();
[Link]();

File file = new File(fileName);

if ([Link]()) {
[Link]("File exists: true");
[Link]("Readable: " + [Link]());
[Link]("Writable: " + [Link]());

if ([Link]()) {
[Link]("File type: File");
} else if ([Link]()) {
[Link]("File type: Directory");
} else {
[Link]("File type: Unknown");
}

[Link]("Length: " + [Link]() + " bytes");


} else {
[Link]("File does not exist");
}
}
}
EXP-7

2.1.8. Negative Number Exception

package q81037;
import [Link];
//write your code here..
class NegativeNumberException extends Exception {
public NegativeNumberException(String message) {
super(message);
}
}

// Validator class with validateNumber method


class NumberValidator {
public static void validateNumber(int num) throws NegativeNumberException {
if (num < 0) {
throw new NegativeNumberException("Number cannot be negative");
} else {
[Link]("Number is valid: " + num);
}
}
}

public class Main {


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

try {
int num = [Link]();
[Link](num);
} catch (NegativeNumberException e) {
[Link]("Error: " + [Link]());
}
}
}

2.1.9. Arithmetic Exception


package q81038;
import [Link].*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

int dividend = [Link]();


int divisor = [Link]();
try {
int result = dividend / divisor;
[Link](result);

} catch (ArithmeticException e ) {
[Link]("division by zero is not allowed");
}
}
}

Common questions

Powered by AI

The 'FileReaderExample' program handles IOExceptions, which are triggered if the specified file cannot be found or accessed during execution, such as if the file name is incorrect or the file is absent in the directory. It catches this exception to alert the user when the file cannot be opened, using a simple message output to inform about a 'File not found' scenario, thus preventing a crash .

Using method overloading allows multiple methods in the same class with the same name but different parameters, which can simplify the interface when performing similar operations requiring different data types or additional parameters. This is efficient for syntax-inclined overuse without redefining method names. In contrast, method overriding involves modifying existing inherited behavior, essential in polymorphic settings to change or extend base class behavior universally, offering deeper flexibility through subclass specialization but not applicable in arithmetic operation contexts where inherited logic doesn’t differ in fundamental functionality .

The 'Simple Calculator' prevents division by zero using an if-conditional statement in the divide method, where it throws an ArithmeticException if the second operand is zero. This safeguard specifically addresses the undefined operation in division. However, the absence of similar mechanisms in operations like addition or multiplication indicates either fewer risks or undefined results possible, as standard operations with any given integers generally do not have invalid states except in overflow scenarios, which are inherently managed by Java’s constraints on data types .

The 'PrimeNumbersList' Java program determines if a number is prime by checking divisibility starting from 2. It returns false if the number is less than or equal to one and true if it is exactly two. For numbers greater than two, it returns false if divisible by 2. Then, it checks divisibility from 3 through to the square root of the number incremented by 2, only for odd numbers. Using Math.sqrt() reduces the number of potential divisors significantly, enhancing efficiency because if a number can be divided evenly by any number greater than its square root, it would have already been divided by the lesser factor pair .

The 'MatrixAddition' Java program ensures correct addition by iterating through each corresponding element of two matrices of the same dimensions (n x n) and summing them elementwise to store in a third matrix. It assumes that input matrices are square (same number of rows and columns) and that the user correctly inputs numbers for each matrix position as per dimension entered, enforcing dimensional compatibility implicitly through structure rather than explicit checks .

When using validateNumber(), challenges might arise with the expectation of boundary values, especially zero. The method is explicitly designed to throw an exception only if a number is negative, meaning it accepts zero as valid. This behavior might not align with all use cases where non-negative numbers are permissible but not zero. The method might need to adjust its logic or its implementation needs to make explicit decisions about whether zero is an acceptable value .

The 'FibonacciSequence' program does not explicitly manage integer overflow; it uses the standard int type for calculations, which will overflow if 'n' is large enough. Typically, for positive n beyond 46, Fibonacci numbers exceed the range of the int type, thus resulting in overflow errors. The program is limited by the maximum size of int and does not include logic to handle such overflow conditions .

The main difference between the recursive and non-recursive implementations of the Fibonacci series is their approach to generating the sequence. The non-recursive implementation uses a loop to iteratively calculate Fibonacci numbers, reducing computing time and memory usage. Conversely, the recursive version uses a method that calls itself, which can be less memory efficient due to the overhead from stacking calls, but it is more expressive and mirrors the mathematical definition of Fibonacci series .

Using BufferedReader is preferred over alternatives like FileReader directly for large files due to its efficiency in handling input. BufferedReader reads a chunk of characters at a time, minimizing the number of I/O operations, unlike basic FileReader which reads one character at a time, which could be considerably slower for large data sets. BufferedReader's buffer mechanism reduces disk I/O overhead, speeding up line-by-line reading while also providing convenient methods like readLine() for text-based file manipulation .

The implementation of arithmetic exception handling, specifically for division by zero, enhances robustness by preventing runtime crashes when such errors occur. This mechanism ensures program stability and provides meaningful feedback to users instead of abrupt terminations. Without these checks, the application risks encountering unhandled exceptions leading to a halt, rendering software unreliable in scenarios of erroneous user input or unexpected calculations leading to division by zero .

You might also like