[Go to site: main page, start]

0% found this document useful (0 votes)
17 views22 pages

Average and Sum Calculation in Java

The document outlines a Java lab course for BCA students at Manav Rachna International Institute, detailing various programming experiments. Each experiment includes a specific task, such as calculating averages, generating prime numbers, and demonstrating object-oriented concepts. The document also provides example code and expected outputs for each experiment.

Uploaded by

gameamazono10
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)
17 views22 pages

Average and Sum Calculation in Java

The document outlines a Java lab course for BCA students at Manav Rachna International Institute, detailing various programming experiments. Each experiment includes a specific task, such as calculating averages, generating prime numbers, and demonstrating object-oriented concepts. The document also provides example code and expected outputs for each experiment.

Uploaded by

gameamazono10
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

JAVA LAB

FILE
BCA-DS-
452A

Manav Rachna International Institute of Research and


Studies School of Computer Applications
Department of Computer Applications

Submitted By
Student Name ROHIT MAJUMDER
Roll No 22/FCA/BCA(AIML)/042
Subject JAVA LAB
Semester 4TH

Section/Group D
Department Computer Applications
Batch 2023-2025

Submitted To
Faculty Name Ritu

SCHOOL OF COMPUTER APPLICATIONS


S.
No. Date Aim of the Experiment Signature Grade
1 Write a program to find the average and sum of the
N numbers using Command line argument.

2 Write a program to demonstrate type casting.

3 Write a program to generate prime numbers between


1 & given number

4 Write a program to generate pyramid of stars using


nested for loops

5 Write a program to reversed pyramid using for


loops & decrement operator.

6 Write a program for demonstrate Nested Switch

7 Write a program to calculate area of a circle using


radius

8 Write a program to count the number of objects


created for a class using static member function

9 Write a program to design a class account using the


inheritance and static members which show all
functions of a bank (Withdrawl, deposit)
10 Write a program to create a simple class to find
out the area and perimeter of rectangle using super
and this keyword.

11

12

13

14

15
Experiment 1:- Write a program to find the average and sum of
the N numbers using Command line argument.

public class AverageAndSum {

public static void main(String[] args) {

if ([Link] == 0) {
[Link]("Usage: java AverageAndSum <num1> <num2> <num3>
...");
return;
}
int sum = 0;
for (String arg : args)
{ try {
int num = [Link](arg);
sum += num;
} catch (NumberFormatException e) {
[Link]("Invalid input: " + arg + ". Please enter valid integers.");
return;
}
}
double average = (double) sum / [Link];

[Link]("Sum: " + sum);


[Link]("Average: " + average);
}
}

Output :-
java AverageAndSum 5 10 15
Sum: 30
Average: 10.0
Experiment 2:- Write a program to demonstrate type casting.

public class TypeCastingDemo {


public static void main(String[] args) {
int intValue = 10;
double doubleValue = intValue;
[Link]("Implicit Type Casting (Widening):");
[Link]("int value: " + intValue);
[Link]("double value after casting: " + doubleValue);

[Link]("\n-------------------\n");
double anotherDoubleValue = 15.75;
int anotherIntValue = (int) anotherDoubleValue;
[Link]("Explicit Type Casting (Narrowing):");
[Link]("double value: " + anotherDoubleValue);
[Link]("int value after casting: " + anotherIntValue);
}
}

Output:-

Implicit Type Casting


(Widening): int value: 10
double value after casting: 10.0

Explicit Type Casting


(Narrowing): double value:
15.75
int value after casting: 15
Experiment 3:- Write a program to generate prime numbers
between 1 & given number

import [Link];

public class PrimeNumberGenerator {


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

[Link]("Enter a number to find prime numbers up to that number: ");


int n = [Link]();

[Link]("Prime numbers between 1 and " + n + ":");


generateAndPrintPrimes(n);

[Link]();
}

private static void generateAndPrintPrimes(int limit) {


for (int i = 2; i <= limit; i++) {
if (isPrime(i)) {
[Link](i + " ");
}
}
}

private static boolean isPrime(int num) {


if (num <= 1) {
return false;
}
for (int i = 2; i <= [Link](num); i++)
{ if (num % i == 0) {
return false;
}
}
return true;
}
}
Output:-

Enter a number to find prime numbers up to that number: 10


Prime numbers between 1 and 10:
2357
EEeew

Experiment 4:- Write a program to generate pyramid of stars using


nested for loops

import [Link].*;

public class GeeksForGeeks


{

public static void printStars(int n)


{
int i, j;
for(i=0; i<n; i++)
{
for(j=0; j<=i; j++)
{
// printing stars
[Link]("* ");
}

// ending line after each row


[Link]();
}
}

public static void main(String args[])


{
int n = 5;
printStars(n);
}
}

Output:-

*
**
EEeew

***
****
*****
Experiment 5:- Write a program to reversed pyramid using for loops &
decrement operator.

public class JavaExample


{
public static void main(String[] args)
{
int numberOfRows=7;
//This loop runs based on the number of rows
//In this case, the loop runs 7 times to print 7 rows
for (int i= 0; i<= numberOfRows-1; i++)
{

//This loop prints starting spaces for each row of pattern


for (int j=0; j<=i; j++)
{
[Link](" ");
}
//This loop prints stars and the space between stars for each row
for (int k=0; k<=numberOfRows-1-i; k++)
{
[Link]("*" + " ");
}
//To move the cursor to new line after each row
[Link]();
}
}
}

Output:-
dddsda

Experiment 6:- Write a program for demonstrate Nested Switch.

import [Link].*;

class GFG {

public static void main (String[] args)


{
int x = 1, y = 2;

// Outer Switch
switch (x) {

// If x == 1
case 1:

// Nested Switch

switch (y) {

// If y == 2
case 2:
[Link]("Choice is 2");
break;

// If y == 3
case 3:
[Link]("Choice is 3");
break;
}
break;

// If x == 4
case 4:
[Link]("Choice is 4");
break;

// If x == 5
case 5:
[Link]("Choice is 5");
dddsda

break;

default:
[Link]("Choice is other than 1, 2 3, 4, or 5");

}
}
}

Output:-

Choice is 2
dddsda

Experiment 7:- Write a program to calculate area of a circle using


radius

abstract class Shape {


abstract double
calculateArea(); void
display() {
[Link]("This is a shape.");
}
}
class Circle extends Shape
{ private double radius;

Circle(double radius)
{ [Link] =
radius;
}
@Override
double calculateArea() {
return [Link] * radius * radius;
}
}
class Rectangle extends Shape
{ private double length;
private double width;

Rectangle(double length, double


width) { [Link] = length;
[Link] = width;
}
@Override
double calculateArea()
{ return length *
width;
}
}

public class ShapeDemo {


public static void main(String[]
args) { Circle circle = new
dddsda

Circle(5.0);
Rectangle rectangle = new Rectangle(4.0,
6.0); [Link]();
[Link]("Area of Circle: " + [Link]());

[Link]();
[Link]("Area of Rectangle: " + [Link]());
}
}

Output:-

This is a shape.
Area of Circle:
78.53981633974483 This is a
shape.
Area of Rectangle: 24.0
Experiment 8:- Write a program to find G.C.D of the number.

import [Link].*;
public class GFG {
static int gcd(int a, int b)
{
int result = [Link](a, b);
while (result > 0) {
if (a % result == 0 && b % result == 0) {
break;
}
result--;
}
return result;
}
public static void main(String[] args)
{
int a = 98, b = 56;
[Link]("GCD of " + a + " and " + b
+ " is " + gcd(a, b));
}
}

Output:-

GCD of 98 and 56 is 14
Experiment 9:- Write a program to design a class account using the
inheritance and static members which show all functions of a bank
(Withdrawl, deposit)

import [Link];

class Account {
private static int nextAccountNumber = 1;

protected int accountNumber;


protected String
accountHolder; protected
double balance;

public Account(String accountHolder, double initialBalance) {


[Link] = nextAccountNumber++;
[Link] = accountHolder;
[Link] = initialBalance;
}

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
[Link]("Deposited: $" + amount);
displayBalance();
} else {
[Link]("Invalid deposit amount.");
}
}

public void withdraw(double amount) {


if (amount > 0 && amount <= balance)
{ balance -= amount;
[Link]("Withdrawn: $" + amount);
displayBalance();
} else {
[Link]("Invalid withdrawal amount or insufficient funds.");
}
}

public void displayBalance() {


[Link]("Current Balance: $" + balance);
}

public static void main(String[] args)


{ Scanner scanner = new
Scanner([Link]);

[Link]("Enter account holder's name: ");


String accountHolder = [Link]();

[Link]("Enter initial balance: $");


double initialBalance = [Link]();

Account account = new Account(accountHolder, initialBalance);

// Perform bank transactions


[Link]();

[Link]("Enter deposit amount: $");


double depositAmount = [Link]();
[Link](depositAmount);

[Link]("Enter withdrawal amount: $");


double withdrawalAmount = [Link]();
[Link](withdrawalAmount);

[Link]();
}
}

Output:-

Enter account holder's name:


John Doe Enter initial balance:
$1000
Current Balance: $1000.0

Enter deposit amount:


$200 Deposited:
$200.0
Current Balance: $1200.0

Enter withdrawal
amount: $50 Withdrawn:
$50.0
Current Balance: $1150.0
Experiment 10:- Write a program to create a simple class to find out
the area and perimeter of rectangle using super and this keyword.

import

[Link];

class Rectangle {
protected double
length; protected
double width;

public Rectangle(double length, double


width) { [Link] = length;
[Link] = width;
}

public void display() {


[Link]("Rectangle
Information:");
[Link]("Length: " + length);
[Link]("Width: " + width);
}
}

class RectangleDetails extends Rectangle {


public RectangleDetails(double length, double width) {
super(length, width);
}

public double
calculateArea() { return
[Link] * [Link];
}

public double
calculatePerimeter() { return
2 * ([Link] + [Link]);
}
@Override
public void
display() {
[Link]()
;
[Link]("Area: " + calculateArea());
[Link]("Perimeter: " + calculatePerimeter());
}
}
public class RectangleProgram {
public static void main(String[] args)
{ Scanner scanner = new
Scanner([Link]);

[Link]("Enter length of the


rectangle: "); double length =
[Link]();

[Link]("Enter width of the


rectangle: "); double width =
[Link]();

RectangleDetails rectangle = new RectangleDetails(length,


width); [Link]();

[Link]();
}
}

Output:-

Enter length of the


rectangle: 5.5 Enter width
of the rectangle: 3.2
Rectangle Information:
Length: 5.5
Width: 3.2
Area: 17.6
Perimeter: 17.4

Common questions

Powered by AI

The use of a Scanner provides a convenient and flexible way to read different types of input from the user, such as integers or strings, from the console. This simplifies obtaining runtime data, as seen in examples like 'PrimeNumberGenerator' and 'Account,' and allows programs to be more interactive and responsive to user input .

Implicit type casting, also known as 'widening,' occurs automatically when a smaller data type is converted to a larger type, such as assigning an int to a double. Explicit type casting, or 'narrowing,' requires the programmer to specify the conversion, such as from a double to an int. This type of casting is essential for maintaining precision and performance in Java programs, as shown in 'TypeCastingDemo,' where explicit casting prevents data loss or errors when converting data types .

Static members in the 'Account' class facilitate handling data that is common across all instances, such as the account number, which must be unique and increment across new accounts. By utilizing static members, the program efficiently manages shared data, ensuring each account created has a unique identifier while encapsulating common functionalities like deposit and withdrawal .

Nested switch statements allow structuring complex conditional logic that relies on multiple variables. However, this approach can quickly become challenging to maintain and debug due to increasing complexity, particularly as more levels of nesting or cases are added, making the code less readable and increasing the risk of errors .

The 'super' keyword is used to refer to the immediate parent class's constructors or methods, supporting inheritance by allowing subclasses to access superclass properties. In 'RectangleDetails,' 'super' facilitates invoking the base class constructor for efficient code reuse. Meanwhile, 'this' points to the current instance, enhancing readability and disambiguation of class members. These keywords improve code maintainability and clarity by clearly differentiating between class hierarchies and current instance members .

The 'PrimeNumberGenerator' uses a basic algorithm that checks divisibility up to the square root of each number to determine primality, which is more efficient than checking up to the number itself. However, it still checks each number up to the limit individually, which can become inefficient for very large numbers due to its simple trial division method lacking optimizations like the Sieve of Eratosthenes .

Using command-line arguments provides flexibility by allowing the user to input a varying number of parameters directly when executing the Java program. In the 'AverageAndSum' example, this approach enables the calculation of the sum and average of an arbitrary number of integers without modifying the source code, thus supporting dynamic input .

Nesting loops allows the program to execute a loop within another loop, creating complex patterns or sequences. In 'GeeksForGeeks,' nested loops are used to print a pyramid pattern by incrementally increasing the number of stars on each line, with the outer loop controlling the rows and the inner loop managing the count of stars per row .

The GCD method in 'GFG' employs a simple loop to decrementally check divisibility until finding the greatest common divisor. This straightforward approach minimizes complexity and avoids recursion, which can improve runtime efficiency and memory usage for small inputs while ensuring the algorithm remains straightforward and easily understandable .

The 'ShapeDemo' program uses an abstract class 'Shape' with an abstract method 'calculateArea()' for enforcing implementation in subclasses such as 'Circle' and 'Rectangle'. This setup promotes polymorphism, allowing the program to handle different shape objects uniformly and extend easily for new shapes without modifying existing code, thus enhancing flexibility and adherence to the open/close principle of object-oriented design .

You might also like