You are on page 1of 29

Lab Record

for
Java Programming and Introduction
of python Lab (BCE-C657)

2022 - 2023
Submitted
By:
Gautam Singh Kushwaha
206320055
Branch-ECE
Submitted
to
Mr. Namit Khanduja,
Assistant Professor, Department of Computer Science & Engineering,
Faculty of Engineering & Technology,
Gurukul Kangri Deemed to be University, Haridwar.
Declaration

This is to certify that the programs done in this manual has been developed by me and I have
not copied this file from anywhere.

Signature of Student

Certificate

This is to certify that Mr. Gautam Singh Kushwaha of B.Tech VI semester has
satisfactorily completed his experiments for Java programming and
Introduction of python lab in requirement for partial fulfillment of bachelor
degree in Electronics & Communication Engineering prescribed by Faculty of
Engineering & Technology, Gurukula Kangri Deemed to be University,
Haridwar during the year 2022 -2023.

Signature Signature
Internal Examiner External Examiner
Index
S.No Program / Problem Name

1. CEL TO FARENHEIT

2. FARENHEIT TO CEL

3. NESTED CLASSES

4. STACK CLASS WITH EXCPETION

5. STRING SLICING

6. LIST COMPREHENSION

7. DICTIONARY COMPREHENSION

8. BMI CALCULATION

9. DAWOOD ABRAHIM

10. PACKAGE DELIVARY


Q1. Write a program to convert Celsius to Fahrenheit .

/**

* Java program to convert temperature from Celsius to Fahrenheit.

*/ import

java.util.Scanner;

public class TemperatureConverter {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

/* Input temperature in Celsius from user */

System.out.print("Enter temperature in Celsius: ");

float C = in.nextFloat();

/* Convert Celsius to Fahrenheit */

float F = C * (9f / 5) + 32;

/* Print result */

System.out.println(C + " degree Celsius is equal to " + F +" degree Fahrenheit.");

Q.2) Write a program to convert a given Fahrenheit to Celsius.


import java.util.Scanner;

class FahrenheittoCelsius

{ public static void main(String arg[])

{ double

a,c;

Scanner sc=new Scanner(System.in);

System.out.println("Enter Fahrenheit temperature");

a=sc.nextDouble();

System.out.println("Celsius temperature is = "+celsius(a));

static double celsius(double f)

{ return (f-

32)*5/9;

Q.3) write four program explaining the nested class of each type.
:1. Java static nested class class TestOuter1{

static int data=30;


static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
2. Non-Static Nested Class (Inner Class)

class CPU {

double price; //

nested class

class Processor{

// members of nested class

double cores; String

manufacturer;

double getCache(){

return 4.3;

// nested protected class

protected class RAM{

// members of protected nested

class double memory; String

manufacturer;

double getClockSpeed(){
return 5.5;

}
}

public class Main { public static void

main(String[] args) {

// create object of Outer class CPU

CPU cpu = new CPU();

// create an object of inner class Processor using outer class

CPU.Processor processor = cpu.new Processor();

// create an object of inner class RAM using outer class CPU

CPU.RAM ram = cpu.new RAM();

System.out.println("Processor Cache = " + processor.getCache());

System.out.println("Ram Clock speed = " + ram.getClockSpeed());

3. Local inner class


// Java program to illustrate
// working of local inner classes

public class Outer


{
private void getValue()
{
// Note that local variable(sum) must be final till JDK 7
// hence this code will work only in JDK 8
int sum = 20;
// Local inner Class inside method
class Inner
{
public int divisor;
public int remainder;

public Inner()
{
divisor = 4;
remainder = sum%divisor;
}
private int getDivisor()
{
return divisor;
}
private int getRemainder()
{
return sum%divisor;
}
private int getQuotient()
{
System.out.println("Inside inner class");
return sum / divisor;
}
}

Inner inner = new Inner();


System.out.println("Divisor = "+ inner.getDivisor());
System.out.println("Remainder = " + inner.getRemainder());
System.out.println("Quotient = " + inner.getQuotient());
}

public static void main(String[] args)


{
Outer outer = new Outer();
outer.getValue();
}
}
4. Anonymous inner class
// Java program to demonstrate Need for
// Anonymous Inner class

// Interface
interface Age {

// Defining variables and methods


int x = 21;
void getAge();
}

// Class 1
// Helper class implementing methods of Age Interface class
MyClass implements Age {

// Overriding getAge() method


@Override public void getAge()
{
// Print statement
System.out.print("Age is " + x);
}
}

// Class 2
// Main class
// AnonymousDemo
class GFG { // Main driver method
public static void main(String[] args)
{
// Class 1 is implementation class of Age interface
MyClass obj = new MyClass();

// calling getage() method implemented at Class1


// inside main() method
obj.getAge();
}
}
Q.4) Write a program to imitate the Stack Data structure, it should be a menu
driven program to insert, remove, peek and display the contents of the Stack.
Name the class as Stack, have proper constructors to initialize its data members,
the user should be prompted to input the size of stack at the startup of the
program. The program should have the functionality to check the overflow and
underflow exceptions and to display appropriate messages once the exceptions
occur. Also demonstrate the program using a Driver code
// Stack implementation in Java

class Stack {

// store elements of

stack private int arr[]; //

represent top of stack

private int top;

// total capacity of the stack

private int capacity;

// Creating a stack

Stack(int size) {

// initialize the array

// initialize the stack variables

arr = new int[size];

capacity = size;

top = -1;

// push elements to the top of stack

public void push(int x) {

if (isFull()) {

System.out.println("Stack OverFlow");
// terminates the program

System.exit(1);

// insert element on top of stack

System.out.println("Inserting " + x);

arr[++top] = x;

// pop elements from top of stack

public int pop() {

// if stack is empty

// no element to pop

if (isEmpty()) {

System.out.println("STACK EMPTY");

// terminates the program

System.exit(1);

// pop element from top of stack

return arr[top--];

// return size of the stack

public int getSize() {

return top + 1;

}
// check if the stack is empty

public Boolean isEmpty() {

return top == -1;

// check if the stack is full

public Boolean isFull() {

return top == capacity - 1;

// display elements of stack

public void printStack() {

for (int i = 0; i <= top; i++) {

System.out.print(arr[i] + ", ");

public static void main(String[] args) {

Stack stack = new Stack(5);

stack.push(1);

stack.push(2);

stack.push(3);

System.out.print("Stack: ");

stack.printStack();

// remove element from stack

stack.pop();

System.out.println("\nAfter popping out");

stack.printStack();
}

Q.5 Write a program to demonstrate string slicing in python for negative and
positive slicing.

# Python program to demonstrate


# string slicing

# String slicing
String = 'ASTRING'

# Using slice constructor


s1 = slice(3) s2 =
slice(1, 5, 2)
s3 = slice(-1, -12, -2)

print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])

Q.6) Write a program in python to demonstrate different ways to create list and list
comprehension.

Creating a list in python


1:
#python program to create a list
# A list with 3 integers numbers
= [1, 2, 5] print(numbers) #
Output: [1, 2, 5]
2:
h_letters = [ letter for letter in 'human' ] print(
h_letters)

Example 1: Iteration with List comprehension

# Using list comprehension to iterate through loop

List = [character for character in [1, 2, 3]]

# Displaying list print(List)

Example 2: Even list using list comprehension

list = [i for i in range(11) if i % 2 == 0] print(list)

Example 3: Matrix using List comprehension

matrix = [[j for j in range(3)] for i in range(3)]

print(matrix)
Example 4: List Comprehensions vs For Loop
# Empty list
List = []

# Traditional approach of iterating


for character in 'Geeks 4 Geeks!':
List.append(character)

# Display list print(List)

Q.7 Write a program in python to demonstrate different ways to create Dictionary


and Dictionary comprehension.

Here's how we can create a dictionary in Python.


capital_city = {"Nepal": "Kathmandu", "Italy": "Rome", "England": "London"} print(capital_city)

Example 1: Python Dictionary


# dictionary with keys and values of different data types

numbers = {1: "One", 2: "Two", 3: "Three"}

print(numbers)

Using dictionary comprehension make dictionary Example 1:


# Python code to demonstrate dictionary
# creation using list comprehension
myDict = {x: x**2 for x in [1,2,3,4,5]} print
(myDict)

Example 2:
sDict = {x.upper(): x*3 for x in 'coding '}
print (sDict)

Example 3:Using nested dictionary comprehension


# given string
l="GFG"

# using dictionary comprehension dic


={
x: {y: x + y for y in l} for x in l
}
print(dic)

Q.8 Create a BMI calculation application that reads the user's weight in pounds or
kg and height in inches or meter. Calculate and display the user's BMI . the should
also display the catagory like :
1> underweight if the BMI is less than 18.5
2> normal if the BMI is in between 18.5 to 24.9
3> overweight if the BMI is greater than 30
formula use for the BMI calculation is : : BMI=
(weight(pounds)*703)/height(inches) and BMI=(weight(kg))/height(m)

import java.util.Scanner; public

class BMICalculator {

// method to check bmi category


public static String bmiCategory(double weight,
double height) {

// calculate bmi double bmi = weight


/ ( height * height) ;

// check range
if(bmi < 18.5)
return "Thinness";
else if(bmi < 25)
return "Normal";
else if(bmi < 30)
return "Overweight";
else return "Obese";
}

public static void main(String[] args) {

// declare variables
double weightInKg = 0.0f;
double heightInMeters = 0.0f;
String result = null;

// create Scanner class object to


// take input
Scanner scan = new Scanner(System.in);
System.out.print("Enter weight in Kg: "); weightInKg
= scan.nextDouble(); System.out.print("Enter height
in meters: "); heightInMeters = scan.nextDouble();

// calculate BMI index result =


bmiCategory( weightInKg,
heightInMeters );

// display result
System.out.println(result);

// close Scanner class object


scan.close();
}
}

Q.9) The famous gangster Dawood Abrahim is moving to Islamabad. He has a very
big family there, all of them living on khan Avenue. Since he will visit all his
relatives very often, he wants to find a house close to them. Indeed, Dawood
wants to minimize the total distance to all of his relatives and has blackmailed you
to write a program that solves his problem.
Input
The input consists of several test cases. The first line contains the number
of test cases. For each test case you will be given the integer number of
relatives r (0 < r < 500) and the street numbers (also integers) s1, s2, . . . , si,
. . . , sr where they live (0 < si < 30, 000). Note that several relatives might
live at the same street number.
Output
For each test case, your program must write the minimal sum of distances
from the optimal Dawood’s house to each one of his relatives. The
distance between two street numbers si and sj is dij = |si − sj |.
Sample Input 2
224
3246
Sample Output
2
4

# import sys module for reading input


import sys

# read the number of test cases


t = int(sys.stdin.readline())

# loop through each test case


for _ in range(t):
# read the number of relatives and the street numbers
r, *s = map(int, sys.stdin.readline().split()) # sort the
street numbers in ascending order s.sort()
# find the median of the street numbers if r % 2 == 0: # if even
number of elements m = (s[r//2] + s[r//2 - 1]) / 2 # average of
middle two elements else: # if odd number of elements m =
s[r//2] # middle element
# calculate the total distance to all relatives
d = 0 # initialize distance to zero for i in s: #
loop through each street number d +=
abs(m - i) # add absolute difference to
distance
# write the distance as output
print(int(d))

input:
2
2 2 4
3 2 4 6

Output:
2
4

Q.10 javapratical1.docxPackage-delivery services, such as FedEx®, DHL® and UPS®,


offer a number of different shipping options, each with specific costs associated.
Create an inheritance hierarchy to represent various types of packages. Use class
Package as the base class of the hierarchy, then include classes TwoDayPackage and
OvernightPackage that derive from Package. Base class Package should include data
members representing the name, address, city, state and ZIP code for both the
sender and the recipient of the package, in addition to data members that store the
weight (in ounces) and cost per ounce to ship the package. Package’s constructor
should initialize these data members. Ensure that the weight and cost per ounce
contain positive values. Package should provide a public member function
calculateCost that returns a double indicating the cost associated with shipping the
package. Package’s calculateCost function should determine the cost by multiplying
the weight by the cost per ounce. Derived class TwoDayPackage should inherit the
functionality of base class Package, but also include a data member that represents
a flat fee that the shipping company charges for two-day-delivery service.
TwoDayPackage’s constructor should receive a value to initialize this data member.
TwoDayPackage should redefine member function calculateCost so that it computes
the shipping cost by adding the flat fee to the weight-based cost calculated by base
class Package’s calculateCost function. Class OvernightPackage should inherit
directly from class Package and contain an additional data member representing an
additional fee per ounce charged for overnightdelivery service. OvernightPackage
should redefine member function calculateCost so that it adds the additional fee per
ounce to the standard cost per ounce before calculating the shipping cost. Write a
test program that creates objects of each type of Package and tests member function
calculateCost.

# base class Package


class Package:
# constructor that initializes data members and validates weight and cost
def __init__(self, sName, sAddress, sCity, sState, sZIP,
rName, rAddress, rCity, rState, rZIP, w, c):
self.senderName = sName
self.senderAddress = sAddress
self.senderCity = sCity
self.senderState = sState
self.senderZIP = sZIP
self.recipientName = rName
self.recipientAddress = rAddress
self.recipientCity = rCity
self.recipientState = rState
self.recipientZIP = rZIP if w > 0:
# validate weight self.weight =
w else:
self.weight = 0 # set weight to 0 if negative
print("Invalid weight. Weight set to 0.") if c
> 0: # validate cost self.costPerOunce = c
else:
self.costPerOunce = 0 # set cost to 0 if negative
print("Invalid cost. Cost set to 0.")
# calculateCost function that returns the base cost of shipping the package
def calculateCost(self): return self.weight * self.costPerOunce # multiply
weight by cost per ounce

# derived class TwoDayPackage that inherits from Package


class TwoDayPackage(Package):
# constructor that initializes data members and calls base class
constructor def __init__(self, sName, sAddress, sCity, sState, sZIP,
rName, rAddress, rCity, rState, rZIP, w, c, f):
super().__init__(sName,sAddress,sCity,sState,sZIP,
rName,rAddress,rCity,rState,rZIP, w,c) #
call base class constructor if f > 0: # validate flat
fee self.flatFee = f else:
self.flatFee = 0 # set flat fee to 0 if negative
print("Invalid flat fee. Flat fee set to 0.")
# override calculateCost function to add flat fee to base cost def
calculateCost(self): return super().calculateCost() + self.flatFee # add
flat fee to base cost

# derived class OvernightPackage that inherits from Package


class OvernightPackage(Package):
# constructor that initializes data members and calls base class
constructor def __init__(self,sName,sAddress,sCity,sState,sZIP,
rName,rAddress,rCity,rState,rZIP, w,c,a):
super().__init__(sName,sAddress,sCity,sState,sZIP,
rName,rAddress,rCity,rState,rZIP, w,c) #
call base class constructor if a > 0: # validate
additional fee per ounce
self.additionalFeePerOunce = a else:
self.additionalFeePerOunce = 0 # set additional fee to 0 if negative
print("Invalid additional fee. Additional fee set to 0.")

# override calculateCost function to add additional fee per ounce to base cost per ounce

Input:
2
John Smith
123 Main Street
New York
NY
10001
Jane Doe
456 Elm Street
Los Angeles
CA
90001
10
0.5
2
Mary Jones
789 Pine Avenue
Chicago
IL
60606
Bob Lee
321 Maple Road
Houston
TX
77002
15
0.4
3
0.1

Output:
7.0
9.5

Program no. 2
Create an Account class that a bank might use to represent customers’ bank
accounts. Include a data member of type float to represent the account balance.
Provide a constructor that receives an initial balance and uses it to initialize the
data member. The constructor should validate the initial balance to ensure that it’s
greater than or equal to zero. If not, set the balance to zero and display an error
message indicating that the initial balance was invalid. Provide three member
functions. Member function credit should add an amount to the current balance.
Member function debit should withdraw money from the Account and ensure that
the debit amount does not exceed the Account’s balance. If it does, the balance
should be left unchanged and the function should print a message indicating “Debit
amount exceeded account balance”. Member function getBalance should return
the current balance. Create a program that creates two Account objects and tests
the member functions of class Account

import java.util.Scanner;

class BankDetails {
private String accno;

private String name;

private String acc_type;

private long balance;

Scanner sc = new

Scanner(System.in); //method to

open new account public void

openAccount() {

System.out.print("Enter Account No: ");

accno = sc.next();

System.out.print("Enter Account type:

"); acc_type = sc.next();

System.out.print("Enter Name: "); name

= sc.next();

System.out.print("Enter Balance: ");

balance = sc.nextLong();

//method to display account details

public void showAccount() {

System.out.println("Name of account holder: " + name);

System.out.println("Account no.: " + accno);

System.out.println("Account type: " + acc_type);

System.out.println("Balance: " + balance);

//method to deposit money

public void deposit() {

long amt;

System.out.println("Enter the amount you want to deposit:

"); amt = sc.nextLong(); balance = balance + amt;

}
//method to withdraw

money public void

withdrawal() { long amt;

System.out.println("Enter the amount you want to withdraw:

"); amt = sc.nextLong(); if (balance >= amt) { balance

= balance - amt;

System.out.println("Balance after withdrawal: " + balance);


} else {

System.out.println("Your balance is less than " + amt + "\tTransaction failed...!!" );

//method to search an account

number public boolean search(String

ac_no) { if (accno.equals(ac_no)) {

showAccount(); return (true);

return (false);

public class BankingApp { public

static void main(String arg[]) {

Scanner sc = new Scanner(System.in);

//create initial accounts

System.out.print("How many number of customers do you want to input? ");

int n = sc.nextInt();

BankDetails C[] = new BankDetails[n];

for (int i = 0; i < C.length; i++) {

C[i] = new BankDetails();

C[i].openAccount();

// loop runs until number 5 is not pressed to exit


int ch;

do {

System.out.println("\n ***Banking System Application***");

System.out.println("1. Display all account details \n 2. Search by Account number\n 3. Deposit


the amount \n 4. Withdraw the amount \n 5.Exit ");

System.out.println("Enter your choice: ");


ch = sc.nextInt();

switch (ch) {

case 1:

for (int i = 0; i < C.length; i++) {

C[i].showAccount();

break;

case 2:

System.out.print("Enter account no. you want to search:

"); String ac_no = sc.next(); boolean found =

false; for (int i = 0; i < C.length; i++) { found =

C[i].search(ac_no); if (found) { break;

} if

(!found) {

System.out.println("Search failed! Account doesn't exist..!!");

break;

case 3:

System.out.print("Enter Account no. :

"); ac_no = sc.next(); found =

false; for (int i = 0; i < C.length; i++) {

found = C[i].search(ac_no); if (found)

{ C[i].deposit();

break;

}
}

if (!found) {

System.out.println("Search failed! Account doesn't exist..!!");

break;

case 4:

System.out.print("Enter Account No :

"); ac_no = sc.next(); found =

false; for (int i = 0; i < C.length; i++) {

found = C[i].search(ac_no); if (found)

{ C[i].withdrawal();

break;

} if

(!found) {

System.out.println("Search failed! Account doesn't exist..!!");

break;

case 5:

System.out.println("See you soon...");

break;

while (ch != 5);

You might also like