Object Oriented Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 121

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

SCHOOL OF ENGINEERING AND TECHNOLOGY

LABORATORY RECORD
2021-2022

Subject Code
20CS2035L

Subject Name
OBJECT ORIENTED PROGRAMMING LAB

Register No: URK20CS1156

This is the record of work done by Mr./Ms.


MADHAVAN G during the odd semester of the academic year 2021-2022
and submitted for the End Semester Practical Examination held on 16th Nov 2021.
URK20YYxxxx TABLE OF CONTENTS

# Date Name of the Experiment

USAGE OF CONTROL STATEMENTS FOR LOGICAL


1 13-07-2021 BUILDING

ARRAYS IN JAVA
2 20-07-2021

TEXT PROCESSING
3 27-07-2021

CREATING USED DEFINED DATATYPE USING CLASSES


4 3-08-2021 AND OBJECTS

CREATING APPLICATION USING INHERITANCE


5 24-08-2021

COMPARTMENTALIZING THE CODING


6 31-08-2021

HANDLING EXCEPTION THROUGH CODING


7 07-09-2021

MULTITHREADING USING JAVA


8 14-09-2021

INPUT / OUTPUT HANDLING USING JAVA


9 05-10-2021
GRAPHICAL USER INTERFACE DESIGNING USING
10 26-10-2021 SWINGS
REG NO : URK20CS1156

EXERCISE NO-2 Usage of control statements for Logical Building

DATE 08/7/20201

YOUTUBE LINK https://youtu.be/dNYbrbJMejc

AIM:
To find Palindrome of a given number
ALGORITHM:

o Get the number to check for palindrome


o Hold the number in temporary variable
o Reverse the number
o Compare the temporary number with reversed number
o If both numbers are same, print "palindrome number"
o Else print "not palindrome number"

: 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;

for (inti = 1; i<= rows; ++i, k = 0) {


for (intspace = 1; space<= rows - i; ++space) {
System.out.print(" ");
}

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);

// Get the number of rows from the user


System.out.println("Enter the number of rows needed in the pattern ");

introws = scanner.nextInt();

System.out.println("* Printing the pattern... *");

for (inti = 1; i<= rows; i++)


{
for (intj = rows; j>i; j--)
{
System.out.print(" ");
}
for (intk = 1; k<= i; k++)
{
System.out.print(k);
}
for (intl = i - 1; l>= 1; l--)
{
System.out.print(l);
}
System.out.println();
}
}
}

PROGRAM(INPUT):
REG NO : URK20CS1156

OUTPUT:

RESULT: The above program for implemented successfully.


REG NO : URK20CS1156

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);

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


n = sc.nextInt();
sc.close();

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:

RESULT:The above program for implemented successfully.


REG NO : URK20CS1156

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:

RESULT: The above program for implemented successfully.


REG NO : URK20CS1156
20CS2035L-Object Oriented Programming | URK20CS1156

Ex.No.2 Arrays in Java


Date 20/07/2021
Youtube Link https://youtu.be/gwLMdkymUQk

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;

public class Ex2_c {


public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string:
"); String str =sc.nextLine(); int[]
freq = new int[str.length()]; int i, j;
char string[] = str.toCharArray();
for(i = 0; i < string.length; i++) {
freq[i] = 1;
20CS2035L-Object Oriented Programming | URK20CS1151

for(j = i+1; j < string.length; j++) {


if(string[i] == string[j] && string[i] != ' ' && string[i] != '0')
{ freq[i]++; string[j] = '0';
}
}
}
System.out.println("The non repeated charectors are:
"); for(i = 0; i <freq.length; i++) {
if(freq[i]==1) { if(string[i]!='0') {
System.out.println(string[i]);
break;
}
break;
20CS2035L-Object Oriented Programming | URK20CS1151

}
}

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;

public class Ex2_a{

public static void main(String[] args) {


Scanner scan=new Scanner(System.in);
int[] fixed,search;
int total_fixed,total_search;

System.out.print("Enter total no. of elements : ");


total_fixed=scan.nextInt();
fixed=new int[total_fixed];
System.out.print("Enter the Elements : ");
for (int i=0; i<total_fixed;i++) {
fixed[i]=scan.nextInt();
}

System.out.print("Enter size of search array : ");


total_search=scan.nextInt();
search=new int[total_search];
System.out.print("Enter the search Elements : ");
for (int i=0; i<total_search;i++) {
search[i]=scan.nextInt();
}

for (int element : search){


boolean flag=false;
for (int j=0;j<total_fixed;j++) {
if (element == fixed[j]){
flag=true;
System.out.println("Element "+element+"
is at index "+j);
20CS2035L-Object Oriented Programming | URK20CS1151

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.*;

public class ques3


{
public static void main(String arg[])
{
int count=0;
Scanner word= new Scanner (System.in);
System.out.println("Enter the paragraph :");
String para=word.nextLine();
System.out.print("Enter the word to search :");
String search=word.nextLine();
String a[]=para.split(" ");
for(int i=0;i<a.length;i++)
{
if(search.equals(a[i]))
{
count++;
}

}
System.out.print("The word "+search+" is repeated "+count);
}

1|Page
20CS2035 L-Object Oriented Programming URK20CS1156 MADHAVAN G

Output:

Enter the paragraph :


The cat (Felis catus) is a domestic species of small carnivorous mammal. It is the
only domesticated species in the family Felidae and is often referred to as the
domestic cat to distinguish it from the wild members of the family.A cat can either
be a house cat, a farm cat or a feral cat; the latter ranges freely and avoids human
contact. Domestic cats are valued by humans for companionship and their ability to
hunt rodents. About 60 cat breeds are recognized by various cat registries.
Enter the word to search :cat
The word cat is repeated 6

2|Page
20CS2035 L-Object Oriented Programming URK20CS1156 MADHAVAN G

Question 2:

Program:

package exercise3;
import java.util.*;

public class ques4


{
public static void main(String args[])
{
Scanner word= new Scanner(System.in);
System.out.print("Enter the number of customer to be entered :");
String a[]= new String[word.nextInt()];
word.nextLine();
for(int i=0;i<a.length;i++)
{
System.out.print("Enter the customer number "+(i+1)+":");
a[i]=word.nextLine();
}
System.out.print("Ascending order:");
Arrays.sort(a, Comparator.naturalOrder());
System.out.print(Arrays.toString(a));

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

succession in a line of text. For example, in the sentence

“Pleases read this application and give me gratuity”

such occurrences are ea, ea, ui

Program:

package vowles;

import java.util.Scanner;

public class vowels {

public static void main(String[] args) {

// TODO Auto-generated method stub

String str;

Scanner sc = new Scanner(System.in);

str=sc.next();

char [] s = str.toCharArray();

for(int i=0;i<s.length-1;i++) {

if(isVowel(s[i]) && isVowel(s[i+1])){

System.out.println("The two consecutive letters are

vowels:"+s[i]+" "+"and"+" "+s[i+1]);

static boolean isVowel(char c) {

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() {

System.out.println("Feet: " + feet + "\tInches: " +


inches);
}
public void addDistance(Distance D1, Distance D2) {
inches = D1.inches + D2.inches;
feet = D1.feet + D2.feet + (inches / 12);
inches = inches % 12;
20CS2035L-Object Oriented Programming | URK20CS1156

}
}
public class Ex4_a {
public static void main(String[] s) {
try {
Distance D1 = new Distance();
Distance D2 = new Distance();
Distance D3 = new Distance();

System.out.println("Enter first distance: ");


D1.getDistance();

System.out.println("Enter second distance: ");


D2.getDistance();

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

QUESTION NUMBER 11:

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 {

public static void main(String[] args) {


int balance = 10000,withdraw,deposit;
Scanner sc = new Scanner(System.in);

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 :");

int choice = sc.nextInt();


switch(choice)
{
case 1:
20CS2035L-Object Oriented Programming | URK20CS1156

System.out.println("Enter money to be withdrawn


: ");
withdraw = sc.nextInt();
if(balance >= withdraw){
balance = balance -withdraw;
System.out.println("Please collect your
money ");

}
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

Choose 2 for Deposit


Choose 3 for Check Balance
Choose 4 for exit
Choose the operation you want to perform :1
Enter money to be withdrawn :
1000
Please collect your money

Automatic Teller Machine


Choose 1 for Withdraw
Choose 2 for Deposit
Choose 3 for Check Balance
Choose 4 for exit
Choose the operation you want to perform :2
Enter money to be Deposited
10000
Your money has been successfully deposited

Automatic Teller Machine


Choose 1 for Withdraw
Choose 2 for Deposit
Choose 3 for Check Balance
Choose 4 for exit
Choose the operation you want to perform :3
Balance : 19000

Automatic Teller Machine


Choose 1 for Withdraw
Choose 2 for Deposit
Choose 3 for Check Balance
Choose 4 for exit
Choose the operation you want to perform :4

RESULT:
The given program is executed successfully.
20CS2035L-Object Oriented Programming | URK20CS1156
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1156

Ex.No.5 Creating application using inheritance


Date of Exercise 24/08/2021
Youtube Link https://youtu.be/2GZTqEjw2jw

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() {}
}

class SBI_ATM extends ATM{


double balance1; double sc=1.05;
void viewbalance() {
balance1=super.balance;
System.out.println("Your current balance is : "+balance1);
}
void withdraw(double amt) {
super.balance = super.balance - (amt + sc);
System.out.println("your current balance is: "+super.balance);
}
void deposit(double amt) {
super.balance = (super.balance+ amt) - sc;
System.out.println("your current balance is: "+super.balance);
}
void view_details() {
System.out.println("Name of the customer: "+super.name);
System.out.println("Account balance: "+super.balance);
System.out.println("Rate of interest in SBI bank: 2.70%");
}

class HDFC_ATM extends ATM{


20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1156

double balance2; double


sc=2.35; void viewbalance() {
balance2=super.balance;
System.out.println("Your current balance is : "+balance2);
}
void withdraw(double amt) {
balance2 = super.balance - (amt + sc);
System.out.println("Your current balance is : "+balance2);
}
void deposit(double amt) {
balance2 = (super.balance + amt) - sc;
System.out.println("Your current balance is : "+balance2);
}
void view_details() {
System.out.println("Name of the customer: "+super.name);
System.out.println("Account balance: "+balance2);
System.out.println("Rate of interest in HDFC bank: 3%");
}

public class qb3 {


public static void main(String[] args) {
Scanner sc = new
Scanner(System.in); int choice = 1;
while(choice==1) {
System.out.println("Enter the bank you want? ");
System.out.println("1.SBI BANK\n2.HDFC BANK");
int option = sc.nextInt(); switch(option) {

case 1:{
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1151

SBI_ATM sbi = new


SBI_ATM(); ATM sbi1 = sbi;
int ch=1;
System.out.println("Enter the name of the customer: ");
String n1= sc.next();
sbi1.setname(n1);
System.out.println("Enter the balance:
"); double n2= sc.nextDouble();
sbi1.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:
sbi.viewbalance();
break;

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

sbi?(1.yes/2.no) "); ch = sc.nextInt();


if (ch==1){
continue;
}
else {

System.out.println("Comes out from sbi!!!");


break;
}

}
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

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--;
}

public class Ex5_b {

@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

System.out.print("Enter the train name : ");


String s2 = sc.next();
System.out.print("Enter no. of tickets : ");
int m = sc.nextInt();
train b[] = new train[m];
for (int j = 0; j<m;j++) {
b[j] = new train();
}
if ("ChennaiExpress".equals(s2))
{
b[i] = new ChennaiExpress();
if (b[i].Check_SeatAvailablity() >= m)
{
for (int j = 0; j<m;j++)
{
b[j].Add(s2,12345);
b[j].sub_SeatAvailablity();
}
System.out.println("Booking Successfull");
for (int j = 0; j<m;j++)
{
System.out.println((j+1)+")");
b[j].display();
}
}
else
{
System.out.println("Booking unsuccessfull
because no availability of seats");
}
}
else if ("CoimbatoreExpress".equals(s2))
{
b[i] = new CoimbatoreExpress();
if (b[i].Check_SeatAvailablity() >= m)
{
for (int j = 0; j<m;j++)
{
b[j].Add(s2,54321);
b[j].sub_SeatAvailablity();
}
System.out.println("Booking Successfull");
for (int j = 0; j<m;j++)
{
System.out.println((j+1)+")");
b[j].display();
}
}
else {
System.out.println("Booking unsuccessfull
because no availability of seats");
}

}
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

class Daily_workers extends Worker{


double salary1; double compay(double
days){ salary1 = super.salaryrate
* days; return salary1;
}
void display() {
System.out.println("Details of the Daliy worker: \n");
System.out.println("Name of the Worker: "+super.name);
System.out.println("Per day salary of the worker: "+super.salaryrate);
System.out.println("Type of the worker: Daily worker");
System.out.println("Per week salary of the worker: "+salary1+"\n");
}
} class Salaried_workers extends Worker{
double salary2; double compay(double
hours){ salary2 = super.salaryrate
* hours; return salary2;
}
void display() {
System.out.println("Details of the Daliy worker: \n");
System.out.println("Name of the Worker: "+super.name);
System.out.println("Per hour salary of the worker: "+super.salaryrate);
System.out.println("Type of the worker: Salaried worker");
System.out.println("Total salary of the worker: "+salary2+"\n");
}
}

public class qa10 {


public static void main(String args[]) {
Scanner sc = new
Scanner(System.in); int choice = 1;
while(choice==1) {
20CS2035L-OBJECT ORIENTED PROGRAMMING LAB | URK20CS1156

System.out.println("Enter the type of the worker to calculate the


salary?");
System.out.println("1.Daily worker\n2.Salaried worker");
int option = sc.nextInt();
switch(option) {
case 1:{
Daily_workers ob = new Daily_workers();
Worker ob1 = ob;
System.out.println("Enter the name of the worker: ");
String s1 = sc.next();
System.out.println("Enter the per day salary of the
worker: ");
double s2 = sc.nextDouble();
System.out.println("Enter number of days the worker
worked: ");
int s3 = sc.nextInt();
ob1.setname(s1);
ob1.setsalaryrate(s2);
ob.compay(s3);
ob.display();
break;
}
case 2:{
Salaried_workers ob2 = new Salaried_workers();
Worker ob3 = ob2;
System.out.println("Enter the name of the worker: ");
String s1 = sc.next();
System.out.println("Enter the per hour salary of the
worker: ");
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 1: Start the program.

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 4: Create display function.

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.

Step 6: Initialize objects to display title, author and price of book.

Step 7: Stop the program

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();
}
}

Sample Output (Snapshot):

2. Java Abstract Class

Aim: To create a Book class and MyBook sub class to display title.

Description:

Step 1: Start the program.


Step 2: Create abstract class Book and declare string title.

Step 3: Create setTitle fuction and getTitle function to return title.

Step 4: Create MyBook sub class and create setTitle function to set title.

Step 5: Initialize objects to display title. Step 6: Stop the program.

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();
}
}

Sample Output (Snapshot):


3. Java Interface

Aim: To create an interface AdvancedArithmetic and sub class MyCalculator to get integer from user and
display sum of divisor of integer

Description:

Step 1: Start the program.

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.

Step 4: Initialize objects for MyCalculator sub class.

Step 5: Use display function to display sum of divisor of integer n.

Step 6: Stop the program.

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);
}
}
}

Sample Output (Snapshot):


Result: The above executed for interfaces at java has been verified successfully

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;

Aim: To create an interface named event and perform the functionalities.

Description:

Step 1: create an interface named Event and include unimplemented methods.

Step 2: Using another interface extend the main interface

Step 3: Include data member and method


Step 4: Creating customized classes and using above structures

Step 5: Declaring objects for classes to display the values

Step 6: Run the code.

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
{

System.out.println("1. Addition\n2. Substraction\n3. Multiplication\n4.


Division\n5. Modulus\n6. Sine()\n7. Cosine()\n8. Tan()\n9. Exit\nEnter your choice: ");
ch=sc.nextInt();
switch(ch) {
case 1:
{
System.out.println("Enter the Number 1: ");
int a=sc.nextInt();
System.out.println("Enter the Number 2: ");
int b=sc.nextInt();
calc.add(a,b);
break;
}
case 2:
{
System.out.println("Enter the Number 1: ");
int a=sc.nextInt();
System.out.println("Enter the Number 2: ");
int b=sc.nextInt();
calc.sub(a,b);
break;
}
case 3:
{
System.out.println("Enter the Number 1: ");
int a=sc.nextInt();
System.out.println("Enter the Number 2: ");
int b=sc.nextInt();
calc.mul(a,b);
break;
}
case 4:
{
System.out.println("Enter the Number 1: ");
int a=sc.nextInt();
System.out.println("Enter the Number 2: ");
int b=sc.nextInt();
calc.div(a,b);
break;
}
case 5:
{
System.out.println("Enter the Number 1: ");
int a=sc.nextInt();
System.out.println("Enter the Number 2: ");
int b=sc.nextInt();
calc.mod(a,b);
break;
}
case 6:
{
System.out.println("Enter degree: ");
double degree=sc.nextDouble();
calc.sine(degree);
break;
}
case 7:
{
System.out.println("Enter degree: ");
double degree=sc.nextDouble();
calc.cosine(degree);
break;
}
case 8:
{
System.out.println("Enter degree: ");
double degree=sc.nextDouble();
calc.tan(degree);
break;
}
case 9:
System.out.println("Thank You");
status=false;

break;

default:System.out.println("Enter a valid choice!!!");


}
}while(status);
}
}

SAMPLE OUTPUT(SNAP SHOT):


OUTPUT:

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 1: Open Eclipse workspace and create package accordingly.

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.

Step 5: Finally print all the terms required to give as an input.

Step 6 : Run the code.

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();

CurrentAccount obj2=new CurrentAccount();


obj2.AccountDetails();
System.out.println("Phone Number: 8106256879");
}

}
package pkg2;

public class SavingsAccount {


double Balance=0;
String accountHolder="Shiphrah sharone";
String Accounttype="Savings";
String Accountnumber="7893474585";
public void AccountDetails() {
System.out.println("Account Holder: "+accountHolder);
System.out.println("Account Number= "+Accountnumber);
System.out.println("Account Type: "+Accounttype);

}
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 class CurrentAccount {


double Balance=500000;
String accountHolder=" Sharone";
String Accounttype="Current Account";
String Accountnumber="9847467385";
public void AccountDetails() {
System.out.println("Account Holder: "+accountHolder);
System.out.println("Account Number= "+Accountnumber);
System.out.println("Account Type: "+Accounttype);

}
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.*;

public class Test{

public static void main(String[] args) {


Account obj0=new Account();

SavingsAccount obj=new SavingsAccount();

CurrentAccount obj2=new CurrentAccount();

Scanner sc=new Scanner(System.in);

boolean status=true;

int ch;

System.out.println("***WELCOME TO BANKING APPLICATION***\n");

do

System.out.println("1. Account Summary\n2. Deposit\n3. Withdrawal\n4.


Balance Enquiry\n5. Exit\nEnter your choice: ");

ch=sc.nextInt();

switch(ch) {

case 1:

obj0.accountSummary();

break;

case 2:

int choice;

System.out.println("1. Savings Account\n2. Current


Account\n3. Go Back\nChoose the Account Type: ");

choice=sc.nextInt();
switch(choice) {

case 1:

System.out.println("Enter the amount to be depostied:


");

double amount=sc.nextDouble();

obj.Deposit(amount);

break;

case 2:{

System.out.println("Enter the amount to be deposited:


");

double amount=sc.nextDouble();

obj2.Deposit(amount);

break;

case 3:

break;

}break;

case 3:

int choice;

System.out.println("1. Savings Account\n2. Current Account\n3. Go


Back\nChoose the Account Type: ");
choice=sc.nextInt();

switch(choice) {

case 1:{

System.out.println("Enter the amount for withdrawal: ");

double Wamount=sc.nextDouble();

obj.Withdrawal(Wamount);

break;

case 2:{

System.out.println("Enter the amount for withdrawal: ");

double Wamount=sc.nextDouble();

obj2.Withdrawal(Wamount);

break;

case 3:

break;

break;}

case 4:

int choice;

System.out.println("1. Savings Account\n2. Current Account\n3. Go


Back\nChoose the Account Type: ");

choice=sc.nextInt();

switch(choice) {
case 1:{

obj.AccountBalance();

break;

case 2:{

obj2.AccountBalance();

break;

case 3:

break;

break;}

case 5:

System.out.println("Thank You for using our service");

status=false;

break;

default:System.out.println("Enter a valid choice!!!"); }

}while(status);

}
}

SAMPLE OUTPUT(SNAP SHORT):

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 2: Declare the scanner to get in inputs from the user.

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.

Step 5: Stop the program.

CODE:

import java.io.*; import


java.util.*; import
java.text.*; import
java.math.*;
import java.util.regex.*;

public class Solution { public static


void main(String[] args) { Scanner
sc=new Scanner(System.in); try{
int x=sc.nextInt(); int
y=sc.nextInt(); int z=x/y;
System.out.println(z);
}catch(InputMismatchException ime){
System.out.println(ime.getClass().getName());
}catch(ArithmeticException ae){
System.out.println(ae.getClass().getName()+": "+ae.getMessage());
}catch(Exception i){
System.out.println(i.getMessage());

}
}
}

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 1: Import the java headerfiles for the program.

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:

import java.util.Scanner; class


MyCalculator {
public static int power(int n, int p) throws Exception{
if(n < 0 || p < 0){
throw new Exception ("n or p should not be negative.");
}else if(n==0 && p ==0){
throw new Exception("n and p should not be zero.");
}

else {
return ((int)Math.pow(n,p));
}
}
}

public class Solution {


public static final MyCalculator my_calculator = new MyCalculator();
public static final Scanner in = new Scanner(System.in);

public static void main(String[] args) {


while (in .hasNextInt()) { int n =
in .nextInt(); int p = in .nextInt();

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.*;

public class Solution {

public static void main(String[] args) {


try(Scanner scan = new Scanner(System.in);){
int input = Integer.parseInt(scan.nextLine());
System.out.println(input);
}
catch(NumberFormatException e){
System.out.println("Bad String");
}
}
}

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 3: End the function by displaying 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.

Step 6: Create a subclass to leave out the consonants.

Step-7:Stop the program.

CODE:

package project3; import


java.util.Scanner;
public class GFG {

public static void main(String[] args) {


try {
char[] vowelArray = createVowelArray();
System.out.println("Array created");
} catch (InvalidVowelException exception) {
System.out.println(exception.getMessage());
} finally {
System.out.println("End of program");
}
}

public static char[] createVowelArray() throws InvalidVowelException {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter size of array: "); int
size = scanner.nextInt(); char[] vowelArray
= new char[size]; String vowels =
"aeiouAEIOU"; for (int i = 0; i < size; i++)
{ System.out.print("Enter vowel: ");
vowelArray[i] = scanner.next().charAt(0);
if (vowels.indexOf(vowelArray[i]) == -1)
throw new InvalidVowelException("character is consonant");
}
return vowelArray;
}

static class InvalidVowelException extends Exception {


public InvalidVowelException(String message) {
super(message);
}
}}

SAMPLE OUTPUT (SNAP SHORT):

OUTPUT:

FORMULA BASED QUESTION

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

a. Invalid PIN number is entered more than 3 times

b. Withdraw operation when balance amount < withdraw amount

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;

public interface ATM { public


void withdraw (int i); public boolean
checkpin (int pin); public int
checkbal();
public void deposit (int i);
}

package exp7;

public class Atmop {


private int pin;
private int balance;

public int getpin() {


return pin;
}
public void setpin(int pin) {
this.pin=pin;
}
public int getbalance() {
return balance;
}
public void setbalance(int balance) {
this.balance=balance;
}

public void withdraw(int i) {


balance = balance-i;
System.out.println("The money withdrawed is"+i);

public boolean checkpin(int pin) {


if(pin==this.pin)
{
return true;
}
return false;
}

public int checkbal() {


return balance;
}

public void deposit(int i) {


this.balance=this.balance+i; }

}
package exp7;

import java.util.Scanner;

public class main {


private static final Scanner sc = null;
static int cnt;

public static void main(String[] args) {


int i,j,with,dip,pi;
Scanner sc = new Scanner(System.in);
Atmop ob = new Atmop();
System.out.println("Enter pin you want to set");
pi = sc.nextInt();
ob.setpin(pi); while(true)
{
System.out.println("Enter the pin");
j = sc.nextInt();
cnt++;
if(ob.checkpin(j))
{
System.out.println("ATM OPERATION");
i:while(true)
{

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;
}
}
}

SAMPLE OUTPUT(SNAP SHORT):

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;

class flower extends Thread


{
Scanner sc = new Scanner(System.in);
String f_name;
int qty;
int price;

public void dis(String x,int y,int z)


{
f_name = x;
qty = y;
price = z;
System.out.println("Flowers available : "+x);
System.out.println("Quantity : "+y);
System.out.println("Cost : "+z);
}
public void run()
{
int cnt;
int remaining;
System.out.println("Enter no.of.flowers to buy: ");
cnt = sc.nextInt();
if (cnt > qty)
{
System.out.println("no.of.flowers to buy: "+cnt+"out of stock");
}
price = cnt * price;
20CS2035L-Object Oriented Programming Lab [URK20CS1156]

System.out.println("amount to pay: "+price);


remaining = qty - cnt;
System.out.println("Flowers remaining : "+remaining);

}
}
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

Exp No 9 Video Link: https://youtu.be/7NucX_XlGtA

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;

public class FileOperations {


URK20CS1156
MADHAVANG FILE HANDLING

Exp No 9 Video Link: https://youtu.be/7NucX_XlGtA

public static void main(String[] args) throws IOException {


int x;
Scanner scan = new Scanner(System.in);
do {
System.out.println("Select an operation\n1. Open a existing file");
System.out.println("2. Create a new file");
System.out.println("3. Rename a file");
System.out.println("4. Delete a file");
System.out.println("5. Create a directory");
System.out.println("6. Find the absolute path of a file");
System.out.println("7. Get the file names of a directory");
System.out.println("0. To exit");
x = scan.nextInt();
switch(x){
case 1:
File file = new File("data.txt");
try (FileInputStream fis = new FileInputStream(file))
{
System.out.println("File is existing");
}
catch (FileNotFoundException exc)
{
System.out.println("File not found");
}
break;
case 2:
File createFile = new File("Create.txt");
boolean res;
try
URK20CS1156
MADHAVANG FILE HANDLING

Exp No 9 Video Link: https://youtu.be/7NucX_XlGtA

{
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");

File new_name = new File("data.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

Exp No 9 Video Link: https://youtu.be/7NucX_XlGtA

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:

File makeDirectory = new File("data.txt");


boolean dir = makeDirectory.mkdir();
if(dir){
System.out.println("Directory created successfully");
}
else{
System.out.println("Directory not created ");
}
break;
case 6:
URK20CS1156
MADHAVANG FILE HANDLING

Exp No 9 Video Link: https://youtu.be/7NucX_XlGtA

File ab = new File("data.txt");


String re = ab.getAbsolutePath();
System.out.println(re);
break;
case 7:
String[] name;

File dire = new File("C:\\Users\\shiph\\Documents");

name = dire.list();

for (String string : name) {

System.out.println(string);
}

}
} while(x != 0);
System.out.println("Exited successfully");
}

}
URK20CS1156
MADHAVANG FILE HANDLING

Exp No 9 Video Link: https://youtu.be/7NucX_XlGtA

Code(snap shot):
URK20CS1156
MADHAVANG FILE HANDLING

Exp No 9 Video Link: https://youtu.be/7NucX_XlGtA


URK20CS1156
MADHAVANG FILE HANDLING

Exp No 9 Video Link: https://youtu.be/7NucX_XlGtA


URK20CS1156
MADHAVANG FILE HANDLING

Exp No 9 Video Link: https://youtu.be/7NucX_XlGtA

SAMPLE INPUT (SNAP SHOT):

OUTPUT:
URK20CS1156
MADHAVANG FILE HANDLING

Exp No 9 Video Link: https://youtu.be/7NucX_XlGtA

FORMULA BASED QUESTION:

Create a Java program to find which word has the maximum occurrence and

replace that word by a special symbol, say *.

AIM: Write a program Java program to find which word has the maximum occurrence and

replace that word by a special symbol, say *.

ALGORITHUM:

Step 1: import java packages

Step 2: use generic methods to declare the type

Step 3: using constructor initialize the value.

Step 4: Giving various methods to be done

Step 5: Return word and count.

CODE:

package exp9;

import java.util.Arrays;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

public class WordNode {


URK20CS1156
MADHAVANG FILE HANDLING

Exp No 9 Video Link: https://youtu.be/7NucX_XlGtA

// `count` and `key` is only set for leaf nodes

// `key` stores the string, and `count` stores its frequency so far

String key;

int count;

// each node stores a map to its child nodes

Map<Character, WordNode> character = null;

// Constructor

WordNode() {

character = new HashMap<>();

class Main

// Iterative function to insert a string into a Trie

public static void insert(WordNode head, String str)

// start from the root node

WordNode current = head;

for (char c: str.toCharArray())

// create a new node if the path doesn't exist

current.character.putIfAbsent(c, new WordNode());


URK20CS1156
MADHAVANG FILE HANDLING

Exp No 9 Video Link: https://youtu.be/7NucX_XlGtA

// go to the next node

current = current.character.get(c);

// store key and its count in leaf nodes

current.key = str;

current.count += 1;

// Function to perform preorder traversal on a Trie and

// find a word with the maximum frequency

public static int preorder(WordNode curr, int maximum_Count, StringBuilder key)

// return false if Trie is empty

if (curr == null) {

return maximum_Count;

for (var entry: curr.character.entrySet())

// leaf nodes have a non-zero count

if (maximum_Count < entry.getValue().count)

key.replace(0, key.length(), entry.getValue().key);

maximum_Count = entry.getValue().count;

// recur for current node's children


URK20CS1156
MADHAVANG FILE HANDLING

Exp No 9 Video Link: https://youtu.be/7NucX_XlGtA

maximum_Count = preorder(entry.getValue(), maximum_Count, key);

return maximum_Count;

public static void main(String[] args)

// given set of keys

List<String> dict = Arrays.asList(

"my love", "programmer", "coding", "we", "pro", "pro", "code",

"nyamai", "codec", "codecs", "my love", "codex", "codify",

"my love", "codes", "code", "kelly", "pro", "pro",

"codeveloper", "pro", "codec", "tree", "my love"

);

// Insert all keys into a Trie

WordNode head = new WordNode();

for (String word: dict) {

insert(head, word);

int count = 0;

StringBuilder key = new StringBuilder();

// perform preorder traversal on a Trie and find the key

// with maximum frequency

count = preorder(head, count, key);


URK20CS1156
MADHAVANG FILE HANDLING

Exp No 9 Video Link: https://youtu.be/7NucX_XlGtA

System.out.println("Word : " + key);

System.out.println("Count: " + count);

//Now replace where there is the word with maximum count with *

CODE(SNAP SHOT):
URK20CS1156
MADHAVANG FILE HANDLING

Exp No 9 Video Link: https://youtu.be/7NucX_XlGtA


URK20CS1156
MADHAVANG FILE HANDLING

Exp No 9 Video Link: https://youtu.be/7NucX_XlGtA

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:

import java.awt.*; import


java.awt.event.*;
import javax.swing.*;

public class MainPage


{
public static void main(String[] args)
{
final JFrame frame = new JFrame("JRadioButton Demo");
// implement ItemListener interface
class MyItemListener implements ItemListener
{
public void itemStateChanged(ItemEvent ev)
{
boolean selected = (ev.getStateChange() == ItemEvent.SELECTED);
AbstractButton button = (AbstractButton) ev.getItemSelectable();
String command = button.getActionCommand();
// build message
String state; if
(selected)
{
state = "selected";
}
else
{
state = "unselected";
}
String message;
if (command.equals("Java"))
URK20CS1156

{
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);
}
}

// creates radio button and set corresponding action


// commands
JRadioButton rdbJava = new JRadioButton("Java");
rdbJava.setActionCommand("Java");

JRadioButton rdbASP = new JRadioButton("ASP.Net");


rdbASP.setActionCommand("ASP");

JRadioButton rdbSQL = new JRadioButton("SQL");


rdbSQL.setActionCommand("SQL");

// add event handler


MyItemListener myItemListener = new MyItemListener();
rdbJava.addItemListener(myItemListener);
rdbASP.addItemListener(myItemListener); rdbSQL.addItemListener(myItemListener);

// add radio buttons to a ButtonGroup


final ButtonGroup group = new ButtonGroup();
group.add(rdbJava);
group.add(rdbASP); group.add(rdbSQL);

// Frame setting
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
Container cont = frame.getContentPane();

cont.setLayout(new GridLayout(0, 1));


cont.add(new JLabel("Please choose your favorite language: "));
cont.add(rdbJava); cont.add(rdbASP); cont.add(rdbSQL);

frame.setVisible(true);
}
}
URK20CS1156

OUTPUT:

Result: The above code executed file is verified.


URK20CS1156

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

p.setBounds(50, 220, 100, 30);


utf.setBounds(150, 150, 150, 30);
ptf.setBounds(150, 220, 150, 30);
lb.setBounds(50, 300, 100, 30);
}
public void
addComponentsToContainer() { c.add(u);
c.add(p);
c.add(utf);
c.add(ptf);
c.add(lb);
}
public void addActionEvent() {
lb.addActionListener(this);
}
public void actionPerformed(ActionEvent
e) {
if(e.getSource()==lb)
{
String userT; String pwst; userT=
utf.getText(); pwst=ptf.getText();
if(userT.equalsIgnoreCase("user")
&&pwst.equalsIgnoreCase("password")
){
JOptionPane.showMessageDialog(this,
"Login Successful");
}
else {
JOptionPane.showMessageDialog(this,
"Login Failed");
}
}
}
}
public class Login { public
static void main(String[] a)
{
LoginFrame f = new
LoginFrame();
f.setTitle("LOGIN FUNCTIONALITY");
f.setBounds(100,150,300,350);
f.setVisible(true);
}
}
OUTPUT:
URK20CS1156

Result:

The above code is created Input / Output Handling has been verified.

You might also like