Object Oriented Programming
Object Oriented Programming
Object Oriented Programming
LABORATORY RECORD
2021-2022
Subject Code
20CS2035L
Subject Name
OBJECT ORIENTED PROGRAMMING LAB
ARRAYS IN JAVA
2 20-07-2021
TEXT PROCESSING
3 27-07-2021
DATE 08/7/20201
AIM:
To find Palindrome of a given number
ALGORITHM:
: PROGRAM
packagehellowords;
importjava.util.Scanner;
publicclass palindrome
{
publicstaticvoidmain(String args[])
{
String original, reverse = ""; // Objects of String class
@SuppressWarnings("resource")
Scanner in = newScanner(System.in);
System.out.println("Enter a string/number to check if it is a palindrome");
original = in.nextLine();
intlength = original.length();
for( inti = length - 1; i>= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string/number is a palindrome.");
else
System.out.println("Entered string/number isn't a palindrome.");
}
}
PROGRAMM(INPUT):
REG NO : URK20CS1156
OUTPUT:
RESULT:
The above program for implementing the operation using stack is verified.
REG NO : URK20CS1156
2)
AIM:To find the following pattern
ALGORITHM:
• In the above pattern, the row is denoted by i and the column is denoted by j.
• We see that the first row prints only a star.
• The second-row prints two stars, and so on.
• The colored blocks print the spaces.
• i for rows and j for columns
PROGRAM:
packagehellowords;
publicclassstarpattern {
publicstaticvoidmain(String[] args) {
introws = 3, k = 0;
while (k != 2 * i - 1) {
System.out.print("* ");
++k;
}
System.out.println();
}
}
PROGRAM(INPUT);
REG NO : URK20CS1156
OUTPUT:
RESULT:
The above program for implemented successfully.
REG NO : URK20CS1156
3)
AIM:To find the following pattern
ALGORITHM:
• In the above pattern, the row is denoted by i and the column is denoted by j.
• We see that the first row prints only a number.
• The second-row prints two stars, and so on.
• The colored blocks print the spaces.
• i for rows and j for columns
PROGRAM:
packagehellowords;
importjava.util.Scanner;
publicclass pattern
{
@SuppressWarnings("resource")
publicstaticvoidmain(String[] args)
{
// Create a new Scanner object
Scanner scanner = newScanner(System.in);
introws = scanner.nextInt();
PROGRAM(INPUT):
REG NO : URK20CS1156
OUTPUT:
3)
AIM:To Calculate Electricity bill for the following Tariff,
ALGORITHM:
1. import java. util. *; ...
2. public static void main(String args[]) { long units;
3. units=Long. parseLong(args[0]); double billpay=0;
4. if(units<100) billpay=units*1.20; else if(units<=300)
5. billpay=100*1.20+(units-100)*2; else if(units>300) billpay=100*1.20+200*2+(units-300)*3;
6. System. out. println("Bill to pay : " + billpay);
PROGRAM:
packagehellowords;
importjava.util.Scanner;
publicclass electric {
publicstaticvoidmain(String[] args) {
// TODO Auto-generated method stub
intn;
floats = 0;
Scanner sc = newScanner(System.in);
while (n>0) {
if (n>500) {
s = s + (n-500)*4.2f;
n = 500;
}
elseif (n> 300) {
s = s + (n-300)*3.5f;
n = 300;
}
elseif (n> 100) {
s = s + (n-100)*2.35f;
n = 100;
}
elseif (n> 0) {
s = s + n*1.05f;
n = 0;
}
}
System.out.println("Total cost: " + s);
}
}
REG NO : URK20CS1156
PROGRAM(INPUT):
OUTPUT:
5)
AIM:Develop a Menu driven Calculator with followingoperations. (+,-,?/,*,%)
ALGORITHM:
Take input ‘num1’ and ‘num2’.Let num1=3 and num2=4
We enter do while loop
We choose option 1
switch(option) i.e. switch(1)
case 1: we add and print num1+num2;
then break;
Do you want to continue?1.Yes 2.No
2
So we exit the do while loop.
PROGRAM
packagehellowords;
importjava.util.Scanner;
publicclasscalculater
{
publicstaticvoidmain(String a[])
{
intnum1=0,num2=0,option,ex;
do
{
@SuppressWarnings("resource")
Scanner sc = newScanner(System.in);
System.out.println("Enter your choice from the following menu:");
System.out.println("1.Addition 2.Subtraction 3.Multiplication 4.Division 5.Exit");
option = sc.nextInt();
if(option!=5){
System.out.println("Enter the first number");
num1=sc.nextInt();
System.out.println("Enter the second number");
num2=sc.nextInt();
}
else
break;
switch(option)
{
case1:System.out.println("Addition of "+num1+" and "+num2+" is "+(num1+num2));
break;
case2:System.out.println("Subtraction of "+num1+" and "+num2+" is "+(num1-num2));
break;
case3:System.out.println("Multiplication of "+num1+" and "+num2+" is "+(num1*num2));
break;
case 4: if(num2==0)
System.out.println("Error!!! In Division denominator cannot be 0!");
REG NO : URK20CS1156
else{
System.out.println("In division of "+num1+" by "+num2+" quotient is "+(num1/num2)+" and remainder is
"+(num1%num2));}
break;
case 5: break;
default: System.out.println("Invalid choice");
}
System.out.println("Do you want to continue?1.Yes 2.No");
ex=sc.nextInt();
}while(ex==1);
}
}
PROGRAM(INPUT):
REG NO : URK20CS1156
OUTPUT:
QUESTION NUMBER 2:
AIM:
To generate prime numbers from 1 to 100 using arrays in java.
ALGORITHM:
Step1: Create a public class and inside the class create a function.
Step2: using for loop check the number is prime or not using checkPrime.
Step3: From the second element in the array, set all its multiples to zero.
Step4: proceed to the next non zero number and set its multiples also to zero.
Step5: At last print the nonzero elements in an array.
PROGRAM:
import java.util.Scanner;
public class Ex2_b{
public void main (int n)
{
boolean checkPrime[] = new boolean [n+1]; int
a=2;
for(int i=0; i<n; i++){
checkPrime[i] = true;
}
for(int i=a ; i*i<=n ; i++){
if(checkPrime[i] == true){
for(int j=i*2 ; j<=n ; j=j+i){
checkPrime[j] = false;
}
20CS2035L-Object Oriented Programming | URK20CS1156
}
}
for(int i=2 ; i<=n ; i++){
if(checkPrime[i] == true) {
System.out.println(i+" ");
}
else {
continue;
}
}}
public static void main(String [] args){
System.out.println("Prime numbers from 1 to 100:");
int n=100; qa prime = new qa(); prime.anto(n);
}
}
OUTPUT:
20CS2035L-Object Oriented Programming | URK20CS1156
RESULT:
Hence the prime numbers between 1 to 100 are printed by using arrays in java.
20CS2035L-Object Oriented Programming | URK20CS1156
QUESTION NUMBER 7:
AIM:
To find the first non repeated element in a given string.
ALGORITHM:
Step1: Create a class and void function.
Step2: Create a scanner function to get input from user using keyboard.
Step3: Declare a variable str as string to store the input given by user.
Step4; Declare a variable freq as int[] to store the length of the given string.
Step5: Declare a variable I and j as int.
Step6: Declare the string as char and store the strings as array in string variable.
Step7: Using for loop check and store the count value of each character.
Step8: Using the print statement to print “ The first non repeated element is :”.
Step9: Using for loop to print the first non repeated element.
PROGRAM:
import java.util.Scanner;
}
}
OUTPUT:
RESULT:
Hence the first non repeated element in a string is printed using arrays in java.
20CS2035L-Object Oriented Programming | URK20CS1151
QUESTION NUMBER 5:
AIM:
To Create an array to store a given number by the user and to write a java
program to find out all the search array (another input array) and its positions.
Finally prints out the all search array elements with its positions.
ALGORITHM:
Step1: Create a class and void function.
Step2: Create a scanner function to get input from user using keyboard.
Step3: Declare a variable string as string to store the input given by user.
Step4: Ask the user to enter the character to be searched.
Step5: Initialize the count variable as zero.
Step6: Using for loop calculate the count value of respective character.
Step7: Print the count value using print statement.
PROGRAM:
import java.util.Scanner;
break;
}
}
if (!flag) {
System.out.println("Element "+element+" not
Found");
}
}
OUTPUT:
RESULT:
Hence an array created and finds the search array and its positions are finally
printed.
20CS2035L-Object Oriented Programming | URK20CS1151
20CS2035 L-Object Oriented Programming URK20CS1156 MADHAVAN G
Question 1
Program:
package exercise3;
import java.util.*;
}
System.out.print("The word "+search+" is repeated "+count);
}
1|Page
20CS2035 L-Object Oriented Programming URK20CS1156 MADHAVAN G
Output:
2|Page
20CS2035 L-Object Oriented Programming URK20CS1156 MADHAVAN G
Question 2:
Program:
package exercise3;
import java.util.*;
Output:
Enter the number of customer to be entered :6
Enter the customer number 1:Rachel Green
Enter the customer number 2:Ross Geller
Enter the customer number 3:Monica Geller
Enter the customer number 4:Joey Tribbiani
Enter the customer number 5:Pheobe Buffay
Enter the customer number 6:Chandler Bing
Ascending order:
[Chandler Bing, Joey Tribbiani, Monica Geller, Pheobe Buffay, Rachel Green, Ross
Geller]
3|Page
20CS2035 L-Object Oriented Programming URK20CS1156 MADHAVAN G
Question 3:
10. Write a program to count the number of occurrences of any two vowels in
Program:
package vowles;
import java.util.Scanner;
String str;
str=sc.next();
char [] s = str.toCharArray();
for(int i=0;i<s.length-1;i++) {
if(c=='a'||c=='A'||c=='e'||c=='E'||c=='i'||c=='I'||c=='o'||c=='O'||c=='u'||
c=='U')
4|Page
20CS2035 L-Object Oriented Programming URK20CS1156 MADHAVAN G
return true;
else
return false;
Output:
Result:
The above program is observed and verified the output
5|Page
Ex.No.4 CREATING USED DEFINED DATATYPES USING
CLASSES AND OBJECTS
Date 09/08/2021
Youtube Link https://youtu.be/y23hSFooUQM
QUESTION NUMBER 3:
AIM:
Create a class called distance that contains two members: feet and inches. One
constructor should initialize this data to zero and another should initialize it to fixed
values. Another member function should display the data. The final member
function should take an object as argument, add two distances and return the
resultant object from functions.
A main () program should create two initialized distance objects and one that isn't
initialized. Then it should add the two initialized values, leaving the result in the
third object. Finally it should display the values.
ALGORITHM:
Step 1: Open java eclipse IDE and declare main function.
Step 2: Create a class named distance that contains two members.
Step 3: Use scanner function to read input from the user.
Step 4: Add two distances.
Step 5: Run the program.
PROGRAM:
import java.util.*;
class Distance {
private int feet;
private int inches;
public void getDistance() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter feet: ");
feet = sc.nextInt();
System.out.print("Enter inches: ");
inches = sc.nextInt();
}
public void showDistance() {
}
}
public class Ex4_a {
public static void main(String[] s) {
try {
Distance D1 = new Distance();
Distance D2 = new Distance();
Distance D3 = new Distance();
D3.addDistance(D1, D2);
System.out.println("Total distance is:");
D3.showDistance();
} catch (Exception e) {
System.out.println("Exception occurred :" +
e.toString());
}
}
}
OUTPUT:
Enter first distance:
Enter feet: 5
Enter inches: 50
Enter second distance:
Enter feet: 6
Enter inches: 60
Total distance is:
Feet: 20 Inches: 2
RESULT:
The given program is executed successfully..
20CS2035L-Object Oriented Programming | URK20CS1156
AIM:
Write a menu driven application to perform the ATM operations using JAVA.
Your application must contain the following functionalities. Use constructors, getter
and setter functions.
In the menu give options for Balance Enquiry, Withdrawal and PIN
change
Do not allow to withdraw money if the balance is < = 500
Do not allow to withdraw money if the amount is not a multiple of
100.
ALGORITHM:
Step 1: Open eclipse workspace .& import scanner
Step 2: Create a class pattern with the default package.
Step 3: Using case 1 for withdrawing the money from the initial balance
Step 4: Using case 2 for depositing the money in our account.
Step 5: Using case 3 for displaying the current balance of our account.
Step 6: Run the code..
PROGRAM:
import java.util.Scanner;
public class Ex4_b {
while(true)
{
System.out.println("Automatic Teller Machine");
System.out.println("Choose 1 for Withdraw");
System.out.println("Choose 2 for Deposit ");
System.out.println("Choose 3 for Check Balance");
System.out.println("Choose 4 for exit ");
System.out.print("Choose the operation you want to
perform :");
}
else{
System.out.println("Insufficent Balance");
}
System.out.println("");
break;
case 2:
System.out.println("Enter money to be
Deposited");
deposit = sc.nextInt();
balance = balance+deposit;
System.out.println("Your money has been
successfully deposited");
System.out.println("");
break;
case 3:
System.out.println("Balance : "+balance);
System.out.println("");
break;
case 4:
System.exit(0);
}
}
}
}
OUTPUT:
Automatic Teller Machine
Choose 1 for Withdraw
20CS2035L-Object Oriented Programming | URK20CS1156
RESULT:
The given program is executed successfully.
20CS2035L-Object Oriented Programming | URK20CS1156
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1156
Question number: 3
AIM:
Develop a java application using inheritance for ATM machine transactions.
ALGORITHM:
Step1: Create a super class called ATM.
Step2: Declare the variables and creating the getter , setter functions.
Step3: Create two sub classes SBI_ATM and HDFC_ATM respectively.
Step4: Inside both classes create a proper functions as view balance, deposit, withdraw,
status.
Step5: Create the main class.
Step6: Write the menu driven code for the above super and sub classes with the usage of
while loop, switch cases in the main class.
Step7: Now run and check the output.
PROGRAM: package
exp5; import
java.util.Scanner; class
ATM{
double balance;
String name;
void setbalance(double amt) {
balance = amt;
}
double getbalance() {
return balance;
}
void setname(String Names) {
name = Names;
}
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1151
String getNames() {
return name;
}
void withdraw() {}
void deposit() {} void
view_details() {}
}
case 1:{
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1151
case 2:
System.out.println("Enter the amount to be
withdrawn: ");
double a=sc.nextDouble();
sbi.withdraw(a);
break;
case 3:
System.out.println("Enter the amount to be
deposited: ");
double b=sc.nextDouble();
sbi.deposit(b);
break;
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1151
case 4:
sbi.view_details();
break;
default:
System.out.println("Invalid
option!");
break;
}
System.out.println("Do you want
to continue within
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1151
}
break;
}
case 2:{
HDFC_ATM hdfc = new HDFC_ATM(); ATM
hdfc1= hdfc; int ch=1;
System.out.println("Enter the name of the customer:
"); String n1= sc.next(); hdfc1.setname(n1);
System.out.println("Enter the balance: ");
double n2= sc.nextDouble();
hdfc1.setbalance(n2);
while(ch==1) {
System.out.println("Enter the option you want: ");
System.out.println("1.View
balance\n2.withdraw\n3.deposit\n4.details");
int op =
sc.nextInt(); switch(op) {
case 1:
hdfc.viewbalance();
break;
case 2:
System.out.println("Enter the amount to be
withdrawn: ");
double a=sc.nextDouble();
hdfc.withdraw(a);
break;
case 3:
System.out.println("Enter the amount to be
deposited: ");
double b=sc.nextDouble();
hdfc.deposit(b);
break;
case 4:
hdfc.view_details();
break;
default:
System.out.println("Invalid option!");
break;
}
System.out.println("Do you want to continue
within hdfc?(1.yes/2.no) ");
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1151
ch = sc.nextInt();
if (ch==1){
continue;
}
else {
System.out.println("Comes
out from hdfc!!!");
break;
}
}
break;
}
default:
System.out.println("Invalid option!!");
}
System.out.println("Do you want to continue?(1.yes/2.no) ");
choice = sc.nextInt();
if (choice==1){
continue;
}
else {
System.out.println("Thank you!");
break;
}
}
}
OUTPUT:
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1151
RESULT:
Hence, a java application using inheritance for ATM machine transactions is
created and verified.
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1156
Question number: 4
AIM:
To create a java application using inheritance according to the user's entered details and
bookings, seat avalaibility and implement the elements successfully and conclude by printing
the details of the ticket for the customer.
Algorithm:
Step 1: Create a package and import the syntax for the program.
Step 2: Include all the inputs variables and objects to build up the application.
Step 3: The classes and objects under it should be related to the scenerio, and situate the base
for the application.
Step 4: Specify the datatypes according to the objects, as the application is based on run time
polymorphism we use several blocks to get in the booking details.
Step 5: With the inputs organise the avaliability of seats.
Step 6: Provide the cost for each destination using classes and sub classes.
Step 7: Now with the entire database, provide the customers for booking their tickets, display
the necessary details to the users and get in their credentials accordingly.
Step 8: Also check in their seat avaliability provided with their inputs.
Step 9: Also provided the user that the there's no avaliability if the seats gets full.
Step 10: Display the output statements according to each booking and stop the program.
PROGRAM:
import java.util.Scanner;
class train{
Scanner sc = new Scanner(System.in);
String train_name;
int train_no;
String source;
String destination;
int no_of_tickets;
int cost;
String name;
int age;
String gender;
train()
{
this.train_name= null;
this.train_no = 0;
this.source = null;
this.destination = null;
this.name = null;
this.age = 0;
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1151
this.gender = null;
}
train(String train_name, String name, int age, String gender, String
source, int train_no, String destination)
{
this.train_name= train_name;
this.train_no = train_no;
this.source = source;
this.destination = destination;
this.name = name;
this.age = age;
this.gender = gender;
}
void Add(String c,int a) {
train_name = c;
train_no = a;
System.out.print("Source Station : ");
source = sc.next();
System.out.print("destination Station : ");
destination = sc.next();
System.out.print("Name : ");
name = sc.next();
System.out.print("Age : ");
age = sc.nextInt();
System.out.print("Gender : ");
gender = sc.next();
}
int Check_SeatAvailablity() {
return 0;
}
void sub_SeatAvailablity() {
}
void display() {
System.out.println("Train Name : "+ train_name);
System.out.println("Train No : "+ train_no);
System.out.println("Source Station : "+ source);
System.out.println("destination Station : "+ destination);
System.out.println("Name : "+ name);
System.out.println("Age : "+ age);
System.out.println("Gender : "+ gender);
}
String get_train_name(){
return train_name;
}
}
class ChennaiExpress extends train{
ChennaiExpress()
{
this.no_of_tickets = 285;
this.cost = 425;
}
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1156
int Check_SeatAvailablity(){
return no_of_tickets;
}
void sub_SeatAvailablity(){
if (no_of_tickets != 0) {
no_of_tickets--;
}
}
}
class CoimbatoreExpress extends train{
CoimbatoreExpress()
{
this.no_of_tickets = 385;
this.cost = 365;
}
int Check_SeatAvailablity(){
return no_of_tickets;
}
void sub_SeatAvailablity(){
no_of_tickets--;
}
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.println("1) Check seat availability");
System.out.println("2) Book ticket");
System.out.print("Enter your option : ");
int n = sc.nextInt();
switch(n)
{
case 1:
train t = new train();
System.out.print("Enter the train name : ");
String s1 = sc.next();
if ("ChennaiExpress".equals(s1)){
t = new ChennaiExpress();
System.out.println("Seat Availablity :
"+t.Check_SeatAvailablity());
}
else if ("CoimbatoreExpress".equals(s1)) {
t = new CoimbatoreExpress();
System.out.println("Seat Availablity :
"+t.Check_SeatAvailablity());
}
else {
System.out.println("Entered train name is wrong
!");
}
break;
case 2:
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1151
}
else {
System.out.println("Entered train name is wrong
!");
}
break;
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1156
default:
System.out.println("Please enter correct option !");
break;
}
}
}
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1151
OUTPUT:
RESULT:
The given Program is executed successfully.
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1156
Question number: 10
AIM:
Develop a java application using inheritance for calculating the salary for workers.
ALGORITHM:
Step1: Create a super class called Worker.
Step2: Declare the variables and creating the getter , setter functions.
Step3: Create two sub classes Daily_worker and Salaried_worker respectively.
Step4: Inside both classes create a proper functions as calculate and display the salary details
of the workers.
Step5: Create the main class.
Step6: Write the menu driven code for the above super and sub classes with the usage of
while loop, switch cases in the main class.
Step7: Now run and check the output.
PROGRAM: package
exp5; import
java.util.Scanner; class
Worker{
String name; double
salaryrate; void setname(String
names) {
name = names;
}
String getname() {
return name;
}
void setsalaryrate(double salra) {
salaryrate= salra;
}
double getsalaryrate() {
return salaryrate;
} void display()
{} }
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1151
double s2 = sc.nextDouble();
System.out.println("Enter number
of hours the worker
worked: ");
double s3 =
sc.nextDouble();
ob3.setname(s1);
ob3.setsalaryrate(s2);
ob2.compay(s3);
ob2.display(); break;
}
default:
System.out.println("Invalid option!!");
}
System.out.println("Do you want to continue?(1.yes/2.no) ");
choice = sc.nextInt();
if (choice==1){
continue;
}
else {
System.out.println("Thank you!");
break;
}
}
}
}
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1151
OUTPUT:
RESULT:
Hence, a java application using inheritance for calculating the salary for workers is
created and verified.
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1151
EXP-6 URK20CS1156
Compartmentalizing the
09-SEP-2021 coding
Aim: To create a Book class and MyBook sub class to display title, author and price.
Description:
Step 2: Create abstract class Book and declare string title and author.
Step 3: Use Book constructor to initialize the string title and author.
Step 5: Create MyBook sub class and declare integer price and use constructor to initialize integer price
and create display function to print title, author and price of book.
Code:
import java.util.*;
abstract class Book {
String title;
String author;
Book(String title, String author) {
this.title = title;
this.author = author;
}
abstract void display();
}
class MyBook extends Book{
int price;
MyBook(String title , String author , int price){
super(title,author);
this.price = price;
}
void display(){
System.out.println("Title: "+title);
System.out.println("Author: "+author);
System.out.println("Price: "+price);
}
}
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String title = scanner.nextLine();
String author = scanner.nextLine();
int price = scanner.nextInt();
scanner.close();
Book book = new MyBook(title, author, price);
book.display();
}
}
Aim: To create a Book class and MyBook sub class to display title.
Description:
Step 4: Create MyBook sub class and create setTitle function to set title.
CODE:
import java.util.*;
abstract class Book{
String title;
abstract void setTitle(String s);
String getTitle(){
return title;
}
}
class MyBook extends Book {
void setTitle(String s) {
title = s;
}
}
public class Main{
public static void main(String []args){
Scanner sc=new
Scanner(System.in);
String title=sc.nextLine();
MyBook new_novel=new MyBook();
new_novel.setTitle(title);
System.out.println("The title is: "+new_novel.getTitle());
sc.close();
}
}
Aim: To create an interface AdvancedArithmetic and sub class MyCalculator to get integer from user and
display sum of divisor of integer
Description:
Step 2: Create interface AdvancedArithmetic and create divisor_sum function and display "I
implemented: AdvancedArithmetic".
Step 3: Create MyCalculator sub class and override divisor_sum fuction to use for loop and if statement
to return sum of divisor of integer n.
CODE:
import java.util.*;
interface AdvancedArithmetic{
int divisor_sum(int n);
}
//Write your code here
class MyCalculator implements AdvancedArithmetic {
public int divisor_sum(int n) {
int sum=0;
for(int i=1;i<=n;i++) {
if(n%i==0)
sum+=i;
}
return sum;
}
}
class Solution{
public static void main(String []args){
MyCalculator my_calculator = new MyCalculator();
System.out.print("I implemented: ");
ImplementedInterfaceNames(my_calculator);
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.print(my_calculator.divisor_sum(n) + "\n");
sc.close();
}
static void ImplementedInterfaceNames(Object o){
Class[] theInterfaces = o.getClass().getInterfaces();
for (int i = 0; i < theInterfaces.length; i++){
String interfaceName = theInterfaces[i].getName();
System.out.println(interfaceName);
}
}
}
Demo question:
Develop an interface called “Event” which contains Expenditure (), Prizes () are
unimplemented methods. Also include few specifications given below, A default method
called welcome_msg(), A static method called Thank_you msg(), Create another interface
called invitation that extends Event which contains design_invitation() as private member
and display_invitation() as public method create two customized classes called Birthday
and Symposium utilize the above structure;
Description:
CODE:
package project4;
import java.util.Scanner;
public interface Event {
void Expenditure();
void Prizes();
default void welcome_msg()
{
System.out.println("WELCOME");
}
static void Thank_you_msg()
{
System.out.println("THANK YOU !!!");
}
}
abstract interface invitation extends Event
{
private String design_invitation() {
return null;
}
public static void display_invitation()
{
}
}
class Birthday
{
Scanner sc = new Scanner(System.in);
int act_money;
int party_prize;
int deco_prize;
int exp;
void welcome_msg()
{
System.out.println(" WELCOME ");
}
public void Expenditure()
{
System.out.println("ACTUAL EXPENDITURE: " );
act_money = sc.nextInt();
System.out.println("PARTY PRIZE EXPENSED ON EVENT: " );
party_prize = sc.nextInt();
System.out.println("BEST DECO_PRIZE EXPENSED ON BDAY EVENT : ");
deco_prize = sc.nextInt();
}
void display_invitation()
{
System.out.println("Actual money: "+ act_money );
System.out.println("Amount you wanna expend: " + party_prize);
System.out.println("Amount you wanna expend: " + deco_prize);
}
void Thank_you_msg()
{
System.out.println("THANK YOU !!!");
}
}
class Symposium extends Birthday
{
Scanner sc1 = new Scanner(System.in);
String p_name;
int n_prizes;
int people;
void welcome_msg()
{
System.out.println("WELCOME");
}
public void Prizes()
{
System.out.println("Enter PRIZE TYPE : ");
p_name = sc1.next();
System.out.println("Enter NUMBER OF PRIZE : ");
n_prizes = sc1.nextInt();
System.out.println("Enter PEOPLE ATTENTED : ");
people = sc1.nextInt();
}
void display_invitation()
{
System.out.println("PRIZE TYPE " + p_name );
System.out.println("NUMBER OF PRIZES : " + n_prizes);
System.out.println("PEOPLE ATTENTED : " + people);
}
void Thank_you_msg()
{
System.out.println(" THANK YOU !!! ");
}
}
abstract class Events implements Event
{
public static void main(String[] args)
{
Birthday bd = new Birthday();
Symposium s = new Symposium();
s.welcome_msg();
System.out.println("_ _ _ _ _ _ _ _ _ _");
bd.Expenditure();
bd.display_invitation();
System.out.println("_ _ _ _ _ _ _ _ _ _");
s.Prizes();
s.display_invitation();
s.Thank_you_msg();
}
}
Sample output(snap shot):
OutPut:
Result: The above code executed for creating an interface and implementing them is verified successfully
QUESTIONS BASED:
2) Create two interfaces such as MathsOperable and TrigonometricOperable which contains the
functions to perform the basic arithmetic operations (add, sub, mul, div, mod) and trigonometric
operations (sine, cosine, tan) respectively. Create an abstract class called “Calculator” with details
such as no1, no2 and result. Add necessary constructors. Implement these interfaces and inherit the
class in “Operation” class to perform the specific operations. Demonstrate the operations in a menu
driven fashion from a Main class. Write logics in the corresponding methods.
AIM: To write a java to perform the basic arithmetic and trigonometric operations.
DESCRIPTION:
Step 1: Initially create the lifelines according to the components required to the project.
Step 2: The user send the data the cloud source and the cloud sources redirects to the encryptor to be
encoded.
Step 3: After encoding the data and getting the data. Now the receiver get access to the cloud source to
get the data.
Step 4: The cloud source sends the data to the decryptor for the data to be decoded.
Step 5: Using the key the data gets the decoded and the sends the data to the receiver.
CODE:
package project1;
import java.util.*;
interface MathsOperable{
void add(int a, int b);
void sub(int a, int b);
void mul(int a, int b);
void div(int a,int b);
void mod(int a,int b);
}
interface TrigonometricOperable{
void sine(double degrees);
void cosine(double degrees);
void tan(double degrees);
}
class Calculator implements MathsOperable, TrigonometricOperable{
@Override
public void add(int a, int b) {
System.out.print("Result: "+a+"+"+b+"= ");
System.out.println(a+b+"\n");
@Override
public void sub(int a, int b) {
System.out.print("Result: "+a+"-"+b+"= ");
System.out.println(a-b+"\n");
@Override
public void mul(int a, int b) {
System.out.print("Result: "+a+"*"+b+"= ");
System.out.println(a*b+"\n");
}
@Override
public void div(int a, int b) {
System.out.print("Result: "+a+"/"+b+"= ");
System.out.println(a/b+"\n");
}
@Override
public void mod(int a, int b) {
System.out.print("Result: "+a+"%"+b+"= ");
System.out.println(a%b+"\n");
}
@Override
public void sine(double degrees) {
double sinValue = Math.sin(degrees);
System.out.println("Result: "+"sin(" + degrees + ") = " + sinValue+"\n");
@Override
public void cosine(double degrees) {
double cosValue = Math.cos(degrees);
System.out.println("Result: "+"cos(" + degrees + ") = " + cosValue+"\n");
}
@Override
public void tan(double degrees) {
double tanValue = Math.tan(degrees);
System.out.println("Result: "+"tan(" + degrees + ") = " + tanValue+"\n");
}
}
public class MathOperable {
public static void main(String[] args) {
Calculator calc = new Calculator();
Scanner sc=new Scanner(System.in);
boolean status=true;
int ch;
System.out.println("***CALCULATOR***\n");
do
{
break;
RESULT: The above code executed for implementing interfaces has been verified successfully.
2) Develop an application in Java for automating the Banking Operations using packages. Create
an Account class in pkg1, SavingsAccount class, and CurrentAccount class both of which inherits
the Account class in pkg2. Perform menu-driven operations like Deposit, Withdraw, and Balance
Enquiry from a Test class by importing these two packages.
AIM: Develop an application in Java for automating the Banking Operations using packages.
DESCRIPTION:
Step 2: Create an Account class in pkg1, SavingsAccount class, and CurrentAccount class both of which
inherits the Account class in pkg2.
Step 3: Perform menu-driven operations like Deposit, Withdraw, and Balance Enquiry from a Test class
by importing these two packages.
Step 4: By using some respective cases we can assure the tasks for that cases accordingly.
CODE:
package pkg1;
import pkg2.*;
public class Account {
public void accountSummary()
{
System.out.println("***Account Summary***\nCustomer ID: 254132");
SavingsAccount obj=new SavingsAccount();
obj.AccountDetails();
}
package pkg2;
}
public void AccountBalance() {
System.out.println("Account Number="+Accountnumber);
System.out.println("Account Type="+Accounttype);
System.out.println("Balance= "+Balance);
}
public void Deposit(double amount) {
Balance+=amount;
System.out.println("Deposited Amount= "+amount);
System.out.println("Account Number= "+Accountnumber);
System.out.println("***Amount Deposited Successfully***");
}
public void Withdrawal(double Wamount) {
if (Wamount<=Balance)
{
Balance-=Wamount;
System.out.println("Withdrawal Amount= "+Wamount);
System.out.println("Account Number= "+Accountnumber);
System.out.println("Account Balance= "+Balance);
System.out.println("**Amount Debited Successfully**");
}
else
System.out.println("Insufficient Balance");
}
}
package pkg2;
}
public void AccountBalance() {
System.out.println("Account Number="+Accountnumber);
System.out.println("Account Type="+Accounttype);
System.out.println("Balance= "+Balance);
}
public void Deposit(double amount) {
Balance+=amount;
System.out.println("Deposited Amount= "+amount);
System.out.println("Account Number= "+Accountnumber);
System.out.println("***Amount Deposited Successfully***");
}
public void Withdrawal(double Wamount) {
Balance-=Wamount;
System.out.println("Withdrawal Amount= "+Wamount);
System.out.println("Account Number= "+Accountnumber);
System.out.println("Account Balance= "+Balance);
System.out.println("***Amount Debited Successfully***");
}
}
import pkg1.*;
import pkg2.*;
import java.util.*;
boolean status=true;
int ch;
do
ch=sc.nextInt();
switch(ch) {
case 1:
obj0.accountSummary();
break;
case 2:
int choice;
choice=sc.nextInt();
switch(choice) {
case 1:
double amount=sc.nextDouble();
obj.Deposit(amount);
break;
case 2:{
double amount=sc.nextDouble();
obj2.Deposit(amount);
break;
case 3:
break;
}break;
case 3:
int choice;
switch(choice) {
case 1:{
double Wamount=sc.nextDouble();
obj.Withdrawal(Wamount);
break;
case 2:{
double Wamount=sc.nextDouble();
obj2.Withdrawal(Wamount);
break;
case 3:
break;
break;}
case 4:
int choice;
choice=sc.nextInt();
switch(choice) {
case 1:{
obj.AccountBalance();
break;
case 2:{
obj2.AccountBalance();
break;
case 3:
break;
break;}
case 5:
status=false;
break;
}while(status);
}
}
OUTPUT:
VEDIO:
RESULT: The above code executed for implementing interfaces has been verified successfully
EXP-7 URK20CS1156
Exception handling
13-SEP-2021
Youtube link: https://youtu.be/7NucX_XlGtA
AIM: To compile a java code to display the arithmetic result of a division operator using try and catch
statements.
DESCRIPTION:
Step 1: To import java and the mathematics syntax functions for the program.
Step 3: Include two datatypes for getting the divisor and dividend.
Step 4: Display the output according to the output. If zero display ArithmeticException otherwise display
InputMismatchException.
CODE:
}
}
}
OUTPUT:
AIM: To compile a java program to compute the power of a number by implementing a calculator. Create
a class MyCalculator which consists of a single method long power(int, int).
DESCRIPTION:
Step 2: Create a class MyCalculator to calculate the power. If n is lesser than 0 and p is also lesser than
zero, Display that n or p should not be negative.
Step 3: Otherwise if n = 0 and also p == 0, display that n and p should not be zero.
Step 4 : Else display the power of the integers. Create a class to take in inputs fromthe user and display
the output.
Step 5: After gettings in the integers use try and catch statements to provide the output. Stop the program
CODE:
else {
return ((int)Math.pow(n,p));
}
}
}
try {
System.out.println(my_calculator.power(n, p));
} catch (Exception e) {
System.out.println(e);
}
}
}
}
OUTPUT:
Aim: To compile a java program to read a string, , and print its integer value; if cannot be converted to an
integer, print Bad String.
Algorithm:
Step 1: To import the snytax for the program and to create a class for it.
Step 2: Using try and catch statements to read the inputs and to compile it.
Step 3: Read the input and display the output according to the compilation.
Step 4: Otherwise display the statement Bad String, using format exception function.
Step 5: Stop the program.
CODE:
import java.io.*;
import java.util.*;
OUTPUT:
DEMO QUESTION:
Create an array of characters which will be initialized during run time with vowels. If user enters any
consonant, your code should generate a user-defined checked exception, InvalidVowelException. The
description or message of InvalidVowelException is "character is consonant". Handle the exception by
using try, catch, finally, throw and throws.
Aim: To run a java program to create an array of characters which will be initialized during run time with
vowels. If user enters any consonant, your code should generate a user-defined checked exception,
InvalidVowelException.Handle the exception by using try, catch, finally, throw and throws.
Algorithm:
Step 1: To create the package and import the syntax and also create a class for the program.
Step 2: Using the try function to declare the inputs as separate characters to read the vowels from the
string.
Step 4: From the created array to separated to the vowles, include the scanner to read and analyze the
inputs.
Step 5: Declare a string containing the vowels, to compare the strings and get the output.
CODE:
OUTPUT:
Write a menu driven program in Java to automate the ATM operations by demonstrating the concepts of
interfaces. And create custom exceptions to deal with the following situations
Aim:
To run a java program to create a menu driven program in Java to automate the ATM operations by
demonstrating the concepts of interfaces. And create custom exceptions to deal with specific problems.
Algorithm:
Step 1: To create the package and class and subclasses for the program.
Step 2: Initially setup the ATM according to the program, for setting up the pin, check balance, withdraw
respectively.
Step 3: Following, check the entered pin for vadilation and check the balance if the condition is true.
Otherwise return false.
Step 4: Also update the balance after the withdrawal process. Further we create another package and class
to step on case wise.
Step 5: Including the scanner to read the input elements and check up with the conditions. Display the
output statement to inform the user that the transactions process has begun.
Step-6:Display the menu - driven operation for the user to select the options for the transaction.
Step 7: According to the user's inputs display the options and check with the data already entered for the
validation. Also update the balance respectively.
Step 8: Finally when the user completes by the exit number or wrong pin display the output statements
accordingly and stop the program
CODE:
package exp7;
package exp7;
}
package exp7;
import java.util.Scanner;
System.out.println("1.withdraw\n2.deposit\n3.checkbalance\n4.exit\n");
i = sc.nextInt();
switch(i)
{
case 1:System.out.println("Enter the amount to be withdrawed");
with=sc.nextInt();
if(with>ob.getbalance())
{
try
{
throw new Exception();
}
catch(Exception ob2)
{
System.out.println("The amount withdrawed is
greater than balance");
}
}
else
{
ob.withdraw(with);
}
break;
case 2:System.out.println("Enter amount to be deposited");
dip = sc.nextInt();
ob.deposit(dip); break;
case 3:System.out.println("Your balance is "+ob.checkbal());
break;
case 4:break i;
}
}
}
else
{
if(cnt<4)
{
try
{
throw new Exception();
}
catch(Exception obi)
{
System.out.println("Pin incorrect");
continue;
}
}
else
{
System.out.println("Invalid pin......no more attempts");
break;
}
}
}
OUTPUT:
VEDIO:
RESULT: The above code executed for implementing interfaces has been verified successfully
20CS2035L-Object Oriented Programming Lab [URK20CS1156]
Ex No:8 Multithreading
Date:14-09-2021
1st)
Aim:
To create a thread and print using java code.
Description:
Step 1: Create a class and extend it from main class.
Step 2: Include run method.
Step 3: Using for loop initialize value for i and increment it.
Step 4: Declaring the object and calling them.
Step 5: Run the code.
Code:
package Threads;
public class Reverse_Hello extends Thread
{
public void run()
{
for(int j=49;j>=0;j--)
System.out.println("Hello from Thread <"+(j+1)+">");
try {
sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
Reverse_Hello obj[] = new Reverse_Hello[50]; for(int i=0;i<50;i++)
obj[i]= new Reverse_Hello(); for(int i=49;i>=0;i--) obj[i].start();
}
}
20CS2035L-Object Oriented Programming Lab [URK20CS1156]
Output:
Result:
Thus the above code has been executed and verified.
20CS2035L-Object Oriented Programming Lab [URK20CS1156]
2nd)
Aim:
To write a java code that performs multithreading
Description:
Step 1: Create a public class flower shop.
Step 2: Extend the class and include the data.
Step 3: Use run function.
Step 4: Include menu functions and types of flowers required.
Step 5: Run the code.
Code:
package Threads;
import java.util.Scanner;
}
}
public class Flower_shop{
public static void main(String args[])
{
Scanner sc1 = new Scanner(System.in);
flower obj = new flower();
int ch = -1;
int cnt;
while(ch!=4)
{
System.out.println("1.ROSE");
System.out.println("1.LILY");
System.out.println("3.TULIP");
System.out.println("4.JASMINE");
System.out.println("ENTER FLOWER: ");
ch = sc1.nextInt();
switch(ch)
{
case 1:
obj.dis("ROSE",200,20);
obj.start();
break;
case 2:
obj.dis("LILY",1200,120);
obj.start();
break;
case 3:
obj.dis("TULIP",800,80);
obj.start();
break;
case 4:
obj.dis("JASMINE",900,30);
obj.start();
break;
}
}
}
20CS2035L-Object Oriented Programming Lab [URK20CS1156]
Output:
Result:
Thus the given program has been executed and verified.
URK20CS1156
MADHAVANG FILE HANDLING
DEMO QUESTION:
Perform the following operations on file using menu-driven application,
• Opening a existing file
• Creating a new file
• Renaming a file
• Deleting a file
• Creating a directory
• Finding the absolute path of a file
• Get the file names of a directory
AIM: Perform the following operations on file using menu-driven application
ALGORITHUM:
Step 1: Import required file packages
Step 2: Include public class and static method
Step 3: Declare exception case
Step 4: create menu to select appropriate option
Step5: Each option are done through functions declared
CODE:
package exp9;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
{
res = createFile.createNewFile();
if(res){
System.out.println("File created successfully");
}
else{
System.out.println("File already exist");
}
}
catch(IOException E){
System.out.println("Operation not successful");
}
break;
case 3:
File new_file = new File("Create.txt");
boolean f = new_file.renameTo(new_name);
if (f == true) {
System.out.println("Renamed successfully");
}
else {
System.out.println("Operation Failed");
URK20CS1156
MADHAVANG FILE HANDLING
break;
case 4:
File deleteFile = new File("data.txt");
boolean results = deleteFile.delete();
if(results){
System.out.println("Deleted successfully");
}
else{
System.out.println("Operation Failed");
}
break;
case 5:
name = dire.list();
System.out.println(string);
}
}
} while(x != 0);
System.out.println("Exited successfully");
}
}
URK20CS1156
MADHAVANG FILE HANDLING
Code(snap shot):
URK20CS1156
MADHAVANG FILE HANDLING
OUTPUT:
URK20CS1156
MADHAVANG FILE HANDLING
Create a Java program to find which word has the maximum occurrence and
AIM: Write a program Java program to find which word has the maximum occurrence and
ALGORITHUM:
CODE:
package exp9;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// `key` stores the string, and `count` stores its frequency so far
String key;
int count;
// Constructor
WordNode() {
class Main
current = current.character.get(c);
current.key = str;
current.count += 1;
if (curr == null) {
return maximum_Count;
maximum_Count = entry.getValue().count;
return maximum_Count;
);
insert(head, word);
int count = 0;
//Now replace where there is the word with maximum count with *
CODE(SNAP SHOT):
URK20CS1156
MADHAVANG FILE HANDLING
OUTPUT:
VEDIO: https://youtu.be/t606UGzH3ko
RESULT : The above code executed for implementing interfaces has been verified successfully
URK20CS1156
URK20CS1156
Ex-10 GUI USING SWINGS MADHAVAN G
26-10-2021
Video Link: https://youtu.be/IziMjcMA_xw
AIM: A java code to to create three radio buttons. When any of them is
selected, an appropriate message is displayed.
DESCRIPTION:
Step 1: Start the code
Step 2: import required packages.
Step 3: Import public class main page and string values.
Step 4: Required JFrame shoud be implemented to the
abstract button
Step 5: Run the code.
CODE:
{
message = "The Java option has been " + state;
}
else if (command.equals("ASP"))
{
message = "The ASP.Net option has been " + state;
} else
{
message = "The SQL option has been " + state;
}
// show dialog
JOptionPane.showMessageDialog(frame, message);
}
}
// Frame setting
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
Container cont = frame.getContentPane();
frame.setVisible(true);
}
}
URK20CS1156
OUTPUT:
2.)
AIM: A java swing GUI application for the Login functionality as per the
sample design.
DESCRIPTION:
Step 1: import required GUI Package
Step 2: Now declare the java swing to import action event. Step
3: Here class login frame extends jFrame.
Step 4: print the username and password jlabel.
Step 5: run the code.
CODE:
package GUI; import
javax.swing.*; import
java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class LoginFrame extends JFrame
implements ActionListener
{
Container c = getContentPane();
JLabel u= new
JLabel("USERNAME: "); JLabel
p= new
JLabel("PASSWORD: ");
JTextField tf = new JTextField();
JTextField utf = new JTextField();
JTextField ptf = new JTextField();
JButton lb = new
JButton("LOGIN");
LoginFrame()
{
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
}
public void setLayoutManager() {
c.setLayout(null);
}
public void setLocationAndSize() {
u.setBounds(50, 150, 100, 30);
URK20CS1156
Result:
The above code is created Input / Output Handling has been verified.