0% found this document useful (0 votes)
233 views35 pages

BCA Java Lab Practical File

The document discusses several Java programs implemented as part of a lab practical file. It includes the aims, source code, and output for 6 programs covering topics like arithmetic operations using switch case, character checking, variable arguments in functions, wrapper classes, collections, and abstract classes/interfaces.

Uploaded by

SHUBHAM
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)
233 views35 pages

BCA Java Lab Practical File

The document discusses several Java programs implemented as part of a lab practical file. It includes the aims, source code, and output for 6 programs covering topics like arithmetic operations using switch case, character checking, variable arguments in functions, wrapper classes, collections, and abstract classes/interfaces.

Uploaded by

SHUBHAM
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

GALGOTIAS UNIVERSITY

SCHOOL OF COMPUTING SCIENCE & ENGINEERING

Lab Practical File

Name: SHUBHAM KUMAR SINGH


Adm. Number: 21SCSE1040169
Course: Programming in JAVA
Course code: E1UA505C
Program: BCA
Semester: 5th

Submitted to: Dr. Pramod Kumar Soni


INDEX
S. Experiment Date Signature
No.

1 Write a Java Program to perform the arithmetic 9/08/2023


operations using switch case

2 Write a program to check the input character for 16/08/2023


uppercase, lowercase, no. of digits and other
characters
3 Demonstration of Programs to Understand 23/08/2023
variable arguments in function using for(…)

4 Write a Program to implement WrapperClass 6/09/2023

5 Write a Program to implementCollections. 11/09/2023

6 Demonstration and implementation of programs 18/10/2023


to understand abstract classes and interfaces.

7 Implementation of Programs to Understand the 25/10/2023


concept of Overriding.

8 Implement Bank Transaction code fordeposit and 1/11/2023


withdrawal but synchronization should be
implemented..
9 Implement Bank Transaction code for deposit 08/11/2023
and withdrawal using the concept of
Multithreading.
10 Write a Program to implement HashMap. 08/11/2023

11 WAP for removing repeated characters instring. 22/11/2023

12 WAP for counting frequency ofcharacters in 22/11/2023


String
Program No. 1

Aim: Write a Java Program to perform the arithmetic operations using switch case

Source Code (If Statement) :

import [Link];

class Main {
public static void main(String[] args) {

char operator;
Double number1, number2, result;

// create an object of Scanner class


Scanner input = new Scanner([Link]);

// ask users to enter operator


[Link]("Choose an operator: +, -, *, or /");
operator = [Link]().charAt(0);

// ask users to enter numbers


[Link]("Enter first number");
number1 = [Link]();

[Link]("Enter second number");


number2 = [Link]();

switch (operator) {

// performs addition between numbers


case '+':
result = number1 + number2;
[Link](number1 + " + " + number2 + " = " + result);
break;

// performs subtraction between numbers


case '-':
result = number1 - number2;
[Link](number1 + " - " + number2 + " = " + result);
break;

// performs multiplication between numbers


case '*':
result = number1 * number2;
[Link](number1 + " * " + number2 + " = " + result);
break;

// performs division between numbers


case '/':
result = number1 / number2;
[Link](number1 + " / " + number2 + " = " + result);
break;

default:
[Link]("Invalid operator!");
break;
}

[Link]();
}
}

Output :

Choose an operator: +, -, *, or /
*
Enter first number
3
Enter second number
9
3.0 * 9.0 = 27

Choose an operator: +, -, *, or /
+
Enter first number
21
Enter second number
8
21.0 + 8.0 = 29.0

Choose an operator: +, -, *, or /
-
Enter first number
9
Enter second number
3
9.0 - 3.0 = 6.0
Program No. 2

Aim: Write a program to check the input character for uppercase, lowercase, no. of
digits and other characters.

Source Code:

#include <stdio.h>
#include <ctype.h> /* Used for isupper() and islower() */

int main()
{
char ch;

/* Input character from user */


printf("Enter any character: ");
scanf("%c", &ch);

if(isupper(ch))
{
printf("'%c' is uppercase alphabet.", ch);
}
else if(islower(ch))
{
printf("'%c' is lowercase alphabet.", ch);
}
else
{
printf("'%c' is not an alphabet.", ch);
}

return 0;
}

Output:

Enter any character: C

'C' is uppercase alphabet


Program No. 3

Aim: Demonstration of Programs to Understand variable arguments in function using for(…)

Source Code :
package [Link];

public class EXPVarargs {

static void fun(int... a)


{
[Link]("Number of arguments: "
+ [Link]);

// using for each loop to display contents of a


for (int i : a)
[Link](i + " ");
[Link]();
}

// Driver code
public static void main(String args[])
{
// Calling the varargs method with
// different number of parameters

// one parameter
fun(100);

// four parameters
fun(1, 2, 3, 4);

// no parameter
fun();
}
}
Output:

Results: Program Executed Successfully.


Program No. 4

Aim: Write a Program to implement Wrapper Class

Source Code :
package [Link];

import [Link];

class Employee {
private int empid;
private String name;
private String empdept;

public int getEmpId()


{
return empid;
}
public void setEmpId(int empid)
{
[Link] = empid++;
}

public String getEmpName()


{
return name;
}
public void setEmpName(String name)
{
[Link] = name;
}

public String getEmpDept()


{
return empdept;
}
public void setEmpDept(String empdept)
{
[Link] = empdept;
}

public String toString()


{
String str = "\n1. Id: " + getEmpId() + "\n2. Name: " + getEmpName() + "\n3.
Department: " + getEmpDept();
return str;
}
}

public class EXP4 {

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
Employee emp = new Employee();
int i;
int ID = 101;
[Link]("\t\tEmployee Details:\n");
for (i = 0; i<10; i++)
{
[Link](ID);
ID++;
[Link]("\nEnter Employee Name: ");
[Link]([Link]());
[Link]("CSE");

[Link]([Link]());
}

}
}
Output:

Results: Program Executed Successfully.


Program No. 5

Aim: Write a Program to implement Collections.

Source Code :
package [Link];
import [Link];
import [Link];

public class CollectionDemo {


public static void main(String[] args){
int arr[] = new int[] { 1, 2, 3, 4 };
Vector<Integer> v = new Vector();
Hashtable<Integer, String> h = new Hashtable();

[Link](1);
[Link](2);
[Link](1, "Swapnesh");
[Link](2, "3Swapnesh");

[Link](arr[0]);
[Link]([Link](0));
[Link]([Link](1));
}
}

Output:

Results: Program Executed Successfully.


Program No. 6

Aim: Demonstration and implementation of programs to understand abstract classes and


interfaces.

Source Code (Abstract Class):


package [Link];

abstract class Shape {

// Declare fields
String objectName = " ";

// Constructor of this class


Shape(String name) { [Link] = name; }

// Method
// Non-abstract methods
// Having as default implementation
public void moveTo(int x, int y)
{
[Link]([Link] + " "
+ "has been moved to"
+ " x = " + x + " and y = " + y);
}

// Method 2
// Abstract methods which will be
// implemented by its subclass(es)
abstract public double area();
abstract public void draw();
}

// Class 2
// Helper class extending Class 1
class Rectangle extends Shape {

// Attributes of rectangle
int length, width;
// Constructor
Rectangle(int length, int width, String name)
{

// Super keyword refers to current instance itself


super(name);

// this keyword refers to current instance itself


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

// Method 1
// To draw rectangle
@Override public void draw()
{
[Link]("Rectangle has been drawn ");
}

// Method 2
// To compute rectangle area
@Override public double area()
{
// Length * Breadth
return (double)(length * width);
}
}

// Class 3
// Helper class extending Class 1
class Circle extends Shape {

// Attributes of a Circle
double pi = 3.14;
int radius;

// Constructor
Circle(int radius, String name)
{
// Super keyword refers to parent class
super(name);
// This keyword refers to current instance itself
[Link] = radius;
}

// Method 1
// To draw circle
@Override public void draw()
{
// Print statement
[Link]("Circle has been drawn ");
}

// Method 2
// To compute circle area
@Override public double area()
{
return (double)((pi * radius * radius));
}
}

public class EXP6Abstract {


public static void main(String[] args)
{
// Creating the Object of Rectangle class
// and using shape class reference.
Shape rect = new Rectangle(2, 3, "Rectangle");

[Link]("Area of rectangle: "


+ [Link]());

[Link](1, 2);

[Link](" ");

// Creating the Objects of circle class


Shape circle = new Circle(2, "Circle");

[Link]("Area of circle: "


+ [Link]());

[Link](2, 4);
}
}

Output (Abstract Class):

Source Code (Interface):


package [Link];

interface Shapes {

// Abstract method
void draw();
double area();
}

// Class 1
// Helper class
class Rectangles implements Shapes {

int length, width;

// constructor
Rectangles(int length, int width)
{
[Link] = length;
[Link] = width;
}

@Override public void draw()


{
[Link]("Rectangle has been drawn ");
}

@Override public double area()


{
return (double)(length * width);
}
}

// Class 2
// Helper class
class Circles implements Shapes {

double pi = 3.14;
int radius;

// constructor
Circles(int radius) { [Link] = radius; }

@Override public void draw()


{
[Link]("Circle has been drawn ");
}

@Override public double area()


{

return (double)((pi * radius * radius));


}
}

public class EXP6Interface {


public static void main(String[] args)
{
// Creating the Object of Rectangle class
// and using shape interface reference.
Shapes rect = new Rectangles(2, 3);

[Link]("Area of rectangle: "


+ [Link]());

// Creating the Objects of circle class


Shapes circles = new Circles(2);

[Link]("Area of circle: "


+ [Link]());
}
}

Output (Interface):

Results: Program Executed Successfully.


Program No. 7

Aim: Implementation of Programs to understand the concept of Overriding.

Source Code :
package [Link];

class Employees {
public static int base = 10000;
int salary()
{
return base;
}
}

// Inherited class
class Manager extends Employees {
// This method overrides salary() of Parent
int salary()
{
return base + 20000;
}
}

// Inherited class
class Clerk extends Employees {
// This method overrides salary() of Parent
int salary()
{
return base + 10000;
}
}

public class EXP7 {


static void printSalary(Employees e)
{
[Link]([Link]());
}
public static void main(String[] args)
{
Employees obj1 = new Manager();

// We could also get type of employee using


// one more overridden [Link] getType()
[Link]("Manager's salary : ");
printSalary(obj1);

Employees obj2 = new Clerk();


[Link]("Clerk's salary : ");
printSalary(obj2);
}
}

Output:

Results: Program Executed Successfully.


Program No. 8

Aim: Implement Bank Transaction code for deposit and withdrawal but synchronization should
be implemented..

Source Code :
public class Bank {
int total = 100;
void withdrawn(String name, int withdrawal)
{
if(total >= withdrawal)
{
[Link](name + "'s Withdrawal Amount : " + withdrawal);
total = total - withdrawal;
[Link]("Remaining Amount : " + total);

try {
[Link](1000);
}
catch (InterruptedException e) {
[Link]();
}
}
else {
[Link](name + " you cannot withdraw : " + withdrawal);
[Link]("Remaining Balance : " + withdrawal);

try {
[Link](1000);
}
catch (InterruptedException e) {
[Link]();
}
}
}
void deposit(String name, int deposit)
{
[Link](name + " Deposited : " + deposit);
total = total + deposit;
[Link]("Remaining Balance : " + total);
try {
[Link](1000);
}
catch (InterruptedException e) {
[Link]();
}
}
}
public class RookieApproach {
public static void main(String[] args)
{
Bank obj = new Bank();

[Link]("Swapnesh", 70);
[Link]("Swapnesh", 90);
[Link]("Swapnesh", 30);
[Link]("Swapnesh", 70);
[Link]("Swapnesh", 40);
}
}

Output:

Results: Program Executed Successfully.


Program No. 9

Aim: Implement Bank Transaction code for deposit and withdrawal using the concept of
Multithreading.

Source Code :
package [Link];

public class Bank {


int total = 100;

void withdrawn(String name, int withdrawal)


{
if(total >= withdrawal)
{
[Link](name + "'s Withdrawal Amount : " + withdrawal);
total = total - withdrawal;
[Link]("Remaining Balance : " + total);

try {
[Link](1000);
}
catch (InterruptedException e) {
[Link]();
}
}
else {
[Link](name + " you cannot withdraw : " + withdrawal);
[Link]("Remaining Balance : " + withdrawal);

try {
[Link](1000);
}
catch (InterruptedException e) {
[Link]();
}
}
}
void deposit(String name, int deposit)
{
[Link](name + " Deposited : " + deposit);
total = total + deposit;
[Link]("Remaining Balance : " + total);

try {
[Link](1000);
}
catch (InterruptedException e) {
[Link]();
}
}
}

public class ThreadDeposit extends Thread{

Bank object;
String name;
int dollar;

ThreadDeposit(Bank ob, String name, int money)


{
[Link] = ob;
[Link] = name;
[Link] = money;
}

public void run()


{
[Link](name, dollar);
}
}

public class ThreadWithdrawal extends Thread {

Bank object;
String name;
int dollar;
ThreadWithdrawal(Bank ob, String name, int money)
{
[Link] = ob;
[Link] = name;
[Link] = money;
}

public void run()


{
[Link](name, dollar);
}
}

public class MultithreadingApproach {


public static void main(String[] args)
{
Bank obj = new Bank();

ThreadWithdrawal t1 = new ThreadWithdrawal(obj, "Swapnesh", 20);


ThreadDeposit t2 = new ThreadDeposit(obj, "Swapnesh", 40);
ThreadWithdrawal t3 = new ThreadWithdrawal(obj, "Swapnesh", 35);
ThreadDeposit t4 = new ThreadDeposit(obj, "Swapnesh", 80);
ThreadWithdrawal t5 = new ThreadWithdrawal(obj, "Swapnesh", 40);

[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output:

Results: Program Executed Successfully.


Program No. 10

Aim: Write a Program to implement Hash Map.

Source Code :
package [Link].module1;

public class WrapperEX {


public static void main(String args[]){
byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c='a';
boolean b2=true;

//Autoboxing: Converting primitives into objects


Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;

//Printing objects
[Link]("---Printing object values---");
[Link]("Byte object: "+byteobj);
[Link]("Short object: "+shortobj);
[Link]("Integer object: "+intobj);
[Link]("Long object: "+longobj);
[Link]("Float object: "+floatobj);
[Link]("Double object: "+doubleobj);
[Link]("Character object: "+charobj);
[Link]("Boolean object: "+boolobj);
//Unboxing: Converting Objects to Primitives
byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;

//Printing primitives
[Link]("---Printing primitive values---");
[Link]("byte value: "+bytevalue);
[Link]("short value: "+shortvalue);
[Link]("int value: "+intvalue);
[Link]("long value: "+longvalue);
[Link]("float value: "+floatvalue);
[Link]("double value: "+doublevalue);
[Link]("char value: "+charvalue);
[Link]("boolean value: "+boolvalue);
}
}

Output:
Source Code :
package [Link];
import [Link];
import [Link];

public class HashMap2 {


public static void main(String args[])
{
HashMap<Integer, String> hm = new HashMap<Integer, String>();
[Link]("Initial list of Elements : "+hm);
[Link](100,"Swapnesh");
[Link](101,"Rohit");
[Link](102,"Vrushabh");
[Link](103,"Vishal");

[Link](("After Invoking put() method : "));


for([Link] m : [Link]())
{
[Link]([Link]() + " " + [Link]());
}

[Link](104, "Aaditya");
[Link]("After invoking putIfAbsent() method : ");
for([Link] m : [Link]())
{
[Link]([Link]() + " " + [Link]());
}

HashMap<Integer, String> map = new HashMap<Integer, String>();

[Link](105, "Gautam");
[Link](hm);

[Link]("After Invoking putAll() method : ");


for([Link] m : [Link]())
{
[Link]([Link]() + " " + [Link]());
}
}
}
Output:

Source Code :
package [Link];

import [Link];

public class HashMap3 {


public static void main(String args[])
{
HashMap<Integer, String> hm = new HashMap<Integer, String>();

[Link](100, "Swapnesh");
[Link](101, "Rohit");
[Link](102, "Vrushabh");
[Link](103, "Vishal");
[Link]("Initial list of Elements : " + hm);

[Link](102);
[Link]("Update list of Elements : " + hm);

[Link](103);
[Link]("Update list of Elements : " + hm);

[Link](101, "Rohit");
[Link]("Update list of Elements : " + hm);
}
}

Output:

Source Code :
package [Link];

import [Link];

public class HashMap4 {


public static void main(String args[])
{
HashMap<Integer, String> hm = new HashMap<Integer, String>();

[Link](100, "Swapnesh");
[Link](101, "Rohit");
[Link](102, "Vrushabh");
[Link](103, "Vishal");

[Link]("Initial list of Elements : " + hm);


[Link](102, "Koli");
[Link]("Update list of Elements : " + hm);

[Link](103, "Vishal", "Adhikari");


[Link]("Update list of Elements : " + hm);

[Link]((k,v) -> "Swapnesh");


[Link]("Update list of Elements : " + hm);
}
}

Output:

Results: Program Executed Successfully.


Program No. 11

Aim: WAP for removing repeated characters in string.

Source Code :
package [Link];

import [Link].*;
import [Link];

public class removeDuplicate1 {


static String removeDuplicate(char str[], int n)
{
int index = 0;

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


{
int j;
for(j = 0; j < i; j++)
{
if(str[i] == str[j])
{
break;
}
}

if(j == i)
{
str[index++] = str[i];
}
}
return [Link]([Link](str, index));
}

public static void main(String[] args)


{
char str[] = "aapapalaea".toCharArray();
int n = [Link];
[Link]("Original String : ");
[Link](str);
[Link]("Result : " + removeDuplicate(str, n));
}
}

Output:

Results: Program Executed Successfully.


Program No. 12

Aim: WAP for counting frequency of characters in String

Source Code :
package [Link];

import [Link];
import [Link];
import [Link];

public class StringFrequency2 {


public static void prCharWithFreq(String s)
{
Map<Character, Integer> d = new HashMap<Character, Integer>();

for (int i = 0; i<[Link]();i++)


{
if ([Link]([Link](i)))
{
[Link]([Link](i), [Link]([Link](i) + 1));
}
else
{
[Link]([Link](i), 1);
}
}

for (int i = 0; i<[Link](); i++)


{
if([Link]([Link](i)) != 0)
{
[Link]([Link](i));
[Link]([Link]([Link](i)) + " ");
[Link]([Link](i), 0);
}
}
}
public static void main(String args[])
{
Scanner sc= new Scanner([Link]);
[Link]("Enter a string: ");
String str= [Link]();
prCharWithFreq(str);
}
}

Output:

Results: Program Executed Successfully.

Common questions

Powered by AI

HashMap facilitates efficient memory usage in Java by storing key-value pairs, enabling quick retrieval of data through hashing mechanisms. It provides average time complexity of O(1) for put and get operations, making it well-suited for scenarios with high-frequency access needs. However, its limitations include non-synchronized access, requiring manual synchronization for thread safety, and lack of ordering which can lead to unpredictable data access patterns. Additionally, hash collisions can affect performance if not managed properly .

Using abstract classes is more advantageous over interfaces when a group of related objects shares common code and behavior. For instance, if several GUI components (like buttons and sliders) need to inherit a common graphical representation method, an abstract base class could provide this implementation. This approach promotes code reuse and reduces redundancy, allowing derived classes to focus solely on behavior differences. It also enables using constructors for field initialization, offering greater control over object construction compared to interfaces .

Abstract classes in Java can have both abstract and concrete methods, allowing for partial implementation, whereas interfaces can only have abstract methods (before Java 8). Abstract classes are used when there is a common base of similar classes sharing methods, while interfaces are implemented when different classes need to implement those methods differently. These differences affect their practical implementation by guiding design choices based on whether a class requires shared code, in which case an abstract class would be more suitable, or needs to follow a particular design contract without a common codebase, in which case interfaces are used .

The switch case is used in Java to perform different arithmetic operations by allowing a selection between multiple options based on the operator provided. It is often preferred over if-else statements when there are multiple discrete values to choose from, as it makes the code more readable and reduces complexity. By using a switch case, the specific block of code that corresponds to the operator is executed, making the decision process faster for clear and distinct options .

Collections in Java are crucial for handling groups of objects, providing powerful tools for data management. Different types of collections, such as List, Set, and Map, offer unique characteristics: Lists allow duplicates and maintain order, Sets prevent duplicates, and Maps store key-value pairs. This diversity facilitates various tasks, such as dynamically resizing groups of data, searching efficiently, and managing complex data structures with ease. Collections improve data manipulation efficiency and flexibility while abstracting the underlying complexity from developers .

Method overriding in Java occurs when a subclass provides a specific implementation for a method already defined in its superclass. For instance, in the given example, the 'salary' method in the 'Employees' class is overridden by both 'Manager' and 'Clerk' subclasses to return different salary values. This allows dynamic method dispatch, where the method that gets invoked is determined at runtime depending on the object's instance calling the method. It enhances polymorphism, allowing a single action to behave differently based on the object that it acts on .

The key benefit of using variable arguments (varargs) in Java is the flexibility it provides, allowing methods to accept arbitrary numbers of arguments without needing to overload methods for different argument counts. This results in cleaner, more maintainable code. However, the drawback is that it can lead to ambiguity if not implemented carefully, as it may not clearly convey the method's intention when multiple types are involved or when used indiscriminately, potentially leading to runtime errors if the method isn’t correctly managed .

Autoboxing and unboxing in Java automatically convert primitive types to their corresponding object wrapper classes and vice versa. This simplifies coding by reducing the manual conversion overhead. Challenges with these features include performance implications due to the additional object creation during boxing and potential for 'NullPointerExceptions' if unboxing a null reference. Care should be taken to manage memory and ensure that such conversions do not inadvertently lead to inefficient or erroneous code execution .

Synchronization in Java ensures that bank transactions like deposits and withdrawals are mutually exclusive, preventing concurrent threads from leading to race conditions and data inconsistency. It addresses challenges such as deadlock and ensures thread safety by allowing only one thread to access the critical section of code at a time. This prevents situations where a withdrawal could occur on an incorrect balance due to simultaneous account access, hence maintaining integrity .

Multithreading enhances performance in financial applications by allowing simultaneous processing of transactions, improving throughput, and reducing wait times. It enables parallel execution of deposits and withdrawals, thus speeding up operations and improving user responsiveness. However, it introduces potential issues like race conditions, where multiple threads may interleave in unintended ways, leading to inconsistent data states. Thread management becomes crucial to avoid these issues, necessitating synchronization or other concurrency management techniques to ensure data integrity .

You might also like