Java Practical Exam Programs
Java Practical Exam Programs
Slip 1
Write a Program to print all Prime numbers in an array of ‘n’ elements. (use command line arguments)
/*
Write a Program to print all Prime numbers in an array of ‘n’
elements. (use command line arguments)
*/
public class PrimeNumber {
static boolean IsPrime(int n) // here we write static because now we not need to create object...
{
boolean Flag = true;
if(n<=1)
return false;
else
for(int i=2; i<n; i++) // for(int i=2; i<n/2; i++) This is also true...
{
if(n%i == 0)
{
Flag = false;
break;
}
}
return Flag;
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
System.out.println("Prime Numbers from 0 to "+n);
for(int i=0; i<=n; i++)
{
if(IsPrime(i))
{
System.out.print(i+", ");
}
}
}
}
/*
OUTPUT:
PS C:\Users\swapniljamble\IdeaProjects\MyProject\src> javac PrimeNumber.java
PS C:\Users\swapniljamble\IdeaProjects\MyProject\src> java PrimeNumber 100
Prime Numbers from 0 to 100
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
*/
OR
/*
Write a Program to print all Prime numbers in an array of ‘n’
elements. (use command line arguments)
*/
public class Prime_no {
static boolean IsPrime(int n) // here we write static because now we not need to create object...
{
boolean Flag = true;
if(n<=1)
return false;
else
for(int i=2; i<n; i++) // for(int i=2; i<n/2; i++) This is also true...
{
if(n%i == 0)
{
Flag = false;
break;
}
}
return Flag;
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
// Prime_no obj = new Prime_no();
if(IsPrime(n)) // if(obj.IsPrime(n))
{
System.out.println(n+ " is a Prime numebr..");
}
else
System.out.println(n+ " is not a prime numebr!!");
}
}
Define an abstract class Staff with protected members id and name. Define a parameterized constructor. Define one subclass OfficeStaff with member department. Create n objects ofOfficeStaff and display all details.
/*
Define an abstract class Staff with protected members id and name.
Define a parameterized constructor. Define one subclass OfficeStaff
with member department. Create n objects of OfficeStaff and display all
details
*/
import java.util.Scanner;
abstract class Staff
{
protected int id;
protected String name;
Staff(int id, String name)
{
this.id = id;
this.name = name;
}
abstract void display();
}
public class Abstract_Staff extends Staff // class OfficeStaff
{
String dep;
Abstract_Staff(int id, String name, String dep) {
super(id, name);
this.dep = dep;
}
void display()
{
System.out.println("\n id :"+id+" \tName :"+name+" \tDepartment :"+dep);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the how many object u want to created:");
int n = sc.nextInt();
Abstract_Staff obj[] = new Abstract_Staff[n];
System.out.println("Enter the Office staff detail:");
for(int i=0; i<n; i++)
{
System.out.println("Enter the id of Employee :"+(i+1));
int id = sc.nextInt();
System.out.println("Enter the name of the Employee :"+(i+1));
String name = sc.next();
System.out.println("Enter the name of the Department of Employee:"+(i+1));
String dep = sc.next();
obj[i] = new Abstract_Staff(id, name, dep);
}
System.out.println("Displaying all detail of Employee:");
for(int i=0; i<n; i++)
{
obj[i].display();
}
}
}
/* Output:
Enter the how many object u want to created:
3
Enter the Office staff detail:
Enter the id of Employee :1
1
Enter the name of the Employee :1
Swapnil
Enter the name of the Department of Employee:1
CodingWallah
Enter the id of Employee :2
2
Enter the name of the Employee :2
Saurabh
Enter the name of the Department of Employee:2
MathsWallah
Enter the id of Employee :3
3
Enter the name of the Employee :3
Abhi
Enter the name of the Department of Employee:3
ChemistryWallah
Displaying all detail of Employee:
id :1 Name :Swapnil Department :CodingWallah
id :2 Name :Saurabh Department :MathsWallah
id :3 Name :Abhi Department :ChemistryWallah
*/
Slip 2
Write a program to read the First Name and Last Name of a person, his weight and height using command line arguments. Calculate the BMI Index which is defined as the individual's body mass divided by the square of their height. (Hint : BMI = Wts. In kgs / (ht) 2 )
/*
Write a program to read the First Name and Last Name of a person,
his weight and height using command line arguments. Calculate the BMI
Index which is defined as the individual's body mass divided by the
square of their height.
(Hint : BMI = Wts. In kgs / (ht) 2
*/
import java.util.Scanner;
public class PersonDetail {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the First Name & Last Name of Person:");
String fname = sc.next();
String lname = sc.next();
float weight = Float.parseFloat(args[0]);
float height = Float.parseFloat(args[1]);
double BMI = weight / Math.pow(height,2); // float BMI = float(weight / Math.pow(height,2));
System.out.println("The BMI of person :"+fname+" "+lname+" is :"+BMI);
}
}
/*
OUTPUT:
PS C:\Users\swapniljamble\IdeaProjects\MyProject\src> javac PersonDetail.java
PS C:\Users\swapniljamble\IdeaProjects\MyProject\src> java PersonDetail 30 5
Enter the First Name & Last Name of Person:
saurabh
ladkat
The BMI of person :saurabh ladkat is :1.2
*/
Define a class CricketPlayer (name,no_of_innings,no_of_times_notout, totatruns, bat_avg). Create an array of n player objects .Calculate the batting average for each player using static method avg(). Define a static sort method which sorts the array on the basis of average. Display the player details in sorted order.
/*
Define a class CricketPlayer (name,no_of_innings,no_of_times_notout, totatruns, bat_avg).
Create an array of n player objects .
Calculate the batting average for each player using static method avg().
Define a static sort method which sorts the array on the basis of average.
Display the player details in sorted order.
*/
import java.util.Scanner;
public class CricketPlayer {
String name;
int no_of_innings, no_of_times_notout, totalruns;
float bat_avg;
CricketPlayer(String name, int no_of_innings, int no_of_times_notout, int totalruns) {
this.name = name;
this.no_of_innings = no_of_innings;
this.no_of_times_notout = no_of_times_notout;
this.totalruns = totalruns;
}
static void average(CricketPlayer player[],int n)
{
try
{
for(int i=0; i<n; i++)
{
player[i].bat_avg = player[i].totalruns/player[i].no_of_innings;
}
}
catch (Exception e)
{
System.out.println(e);
}
}
static void sort(CricketPlayer player[], int n)
{
for(int i=0; i<n; i++)
{
for(int j=i+1;j<n; j++)
{
if(player[i].bat_avg > player[j].bat_avg)
{
CricketPlayer temp = player[i];
player[i] = player[j];
player[j] = temp;
}
}
}
}
void display(CricketPlayer player[], int n)
{
System.out.println("\n Name :"+name+"\tnumber of innings :"+no_of_innings+"\tnumber of times not out :"+no_of_times_notout+"\tTotal runs :"+totalruns+"\tBat average :"+bat_avg);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numebr of Cricketers:");
int n = sc.nextInt();
CricketPlayer player[] = new CricketPlayer[n];
System.out.println("Enter the cricketer Information:");
for(int i=0; i<n; i++)
{
System.out.println("Enter the Name of Cricketer :"+(i+1));
String name = sc.next();
System.out.println("Enter the Number of innings of Cricketer :"+(i+1));
int no_of_innings = sc.nextInt();
System.out.println("Enter the Number of times not out of Cricketer :"+(i+1));
int no_of_times_notout = sc.nextInt();
System.out.println("Enter the Total runs of Cricketer :"+(i+1));
int totalruns = sc.nextInt();
player[i] = new CricketPlayer(name, no_of_innings, no_of_times_notout, totalruns);
}
CricketPlayer.average(player,n);
CricketPlayer.sort(player,n);
System.out.println("Afer Sorting Cricketers on the basis of their Averages:");
for(int i=0; i<n; i++)
{
player[i].display(player,n);
}
}
}
/* OUTPUT:
Enter the numebr of Cricketers:
3
Enter the cricketer Information:
Enter the Name of Cricketer :1
a
Enter the Number of innings of Cricketer :1
13
Enter the Number of times not out of Cricketer :1
10
Enter the Total runs of Cricketer :1
100
Enter the Name of Cricketer :2
b
Enter the Number of innings of Cricketer :2
8
Enter the Number of times not out of Cricketer :2
5
Enter the Total runs of Cricketer :2
20
Enter the Name of Cricketer :3
c
Enter the Number of innings of Cricketer :3
15
Enter the Number of times not out of Cricketer :3
14
Enter the Total runs of Cricketer :3
4000
Afer Sorting Cricketers on the basis of their Averages:
Name :b number of innings :8 number of times not out :5 Total runs :20 Bat average :2.0
Name :a number of innings :13 number of times not out :10 Total runs :100 Bat average :7.0
Name :c number of innings :15 number of times not out :14 Total runs :4000 Bat average :266.0
*/
Slip 3
Write a program to accept ‘n’ name of cities from the user and sort them in ascending order
/*
Write a program to accept ‘n’ name of cities from the user and sort
them in ascending order
*/
import java.util.Scanner;
public class SortCity1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of cities:");
int n = sc.nextInt();
String name[] = new String[n];
for(int i=0; i<n; i++)
{
System.out.println("Enter the name of city :"+(i+1));
name[i] = sc.next();
}
for(int i=0; i<n; i++)
{
for(int j=i+1; j<n; j++)
{
if((name[i].compareTo(name[j])) > 0)
{
String temp;
temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
}
System.out.println("After Sorting cities in Ascending order:");
for(int i=0; i<n; i++)
{
System.out.println(name[i]);
}
}
}
/* output:
Enter the number of cities:
5
Enter the name of city :1
pune
Enter the name of city :2
satara
Enter the name of city :3
koti
Enter the name of city :4
ahamadabad
Enter the name of city :5
ahamadanagar
After Sorting cities in Ascending order:
ahamadabad
ahamadanagar
koti
pune
satara
*/
) Define a class patient (patient_name, patient_age, patient_oxy_level,patient_HRCT_report). Create an object of patient. Handle appropriate exception while patient oxygen level less than 95% and HRCT scan report greater than 10, then throw user defined Exception “Patient is Covid Positive(+) and Need to Hospitalized” otherwise display its information.
/*
a) Define a class patient (patient_name, patient_age,patient_oxy_level,patient_HRCT_report).
Create an object of patient.
Handle appropriate exception while patient oxygen level less than 95% and
HRCT scan report greater than 10,
then throw user defined Exception " Patient is Covid Positive(+) and Need to Hospitalized"
otherwise display its information.
*/
import java.io.*;
import java.util.Scanner;
class LessOxygenException extends Exception
{
public String toString()
{
return "Patient is covid Positive";
}
}
class MoreHRCTException extends Exception
{
public String toString()
{
return "Need to hospitalize";
}
}
class Patient
{
String pname;
int page,olevel,hrct;
void accept() throws LessOxygenException, MoreHRCTException
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of Patient :");
pname = s.next();
System.out.println("Enter the age of Patient :");
page = s.nextInt();
System.out.println("Enter the Oxygen level :");
olevel = s.nextInt();
if (olevel<95)
{
throw new LessOxygenException();
}
System.out.println("Enter the HRCT level :");
hrct = s.nextInt();
if (hrct>10)
{
throw new MoreHRCTException();
}
}
void display()
{
System.out.println("\nPatient infromation:");
System.out.println("Patient Name:" + pname);
System.out.println("Patient Age:" + page);
System.out.println("Patient Oxygen Level:" + olevel);
System.out.println("Patient HRCT:" + hrct);
}
}
public class Ass4_SetA_a
{
public static void main(String[] args)
{
Patient p = new Patient();
try{
p.accept();
p.display();
}
catch (LessOxygenException ol)
{
System.out.println(ol);
}
catch (MoreHRCTException hl)
{
System.out.println(hl);
}
}
}
/* OUTPUT:
PS C:\Users\Swapniljamble\IdeaProjects\demo1\helloj\src> javac Ass4_SetA_a.java
PS C:\Users\Swapniljamble\IdeaProjects\demo1\helloj\src> java Ass4_SetA_a
Enter the name of Patient :
Swapnil
Enter the age of Patient :
23
80
Patient is covid Positive
PS C:\Users\Swapniljamble\IdeaProjects\demo1\helloj\src> java Ass4_SetA_a
Enter the name of Patient :
Saurabh
Enter the age of Patient :
24
Enter the Oxygen level :
100
Enter the HRCT level :
15
Need to hospitalize
PS C:\Users\Swapniljamble\IdeaProjects\demo1\helloj\src> java Ass4_SetA_a
Enter the name of Patient :
Omkar
Enter the age of Patient :
22
Enter the Oxygen level :
100
Enter the HRCT level :
7
Patient infromation:
Patient Name:Omkar
Patient Age:22
Patient Oxygen Level:100
Patient HRCT:7
*/
Slip 4
) Write a program to print an array after changing the rows and columns of a given two-dimensional array.
import java.util.Scanner;
public class ArrayChange {
public static void main(String arg[])
{
Scanner s = new Scanner(System.in);
int i, j;
System.out.println("Enter total rows and columns: ");
int row = s.nextInt();
int column = s.nextInt();
int array[][] = new int[row][column];
System.out.println("Enter matrix Value:");
for(i = 0; i < row; i++)
{
for(j = 0; j < column; j++)
{
array[i][j] = s.nextInt();
}
}
System.out.println("The above matrix value before Changing ");
for(i = 0; i < row; i++)
{
for(j = 0; j < column; j++)
{
System.out.print(array[i][j]+" ");
}
System.out.println(" ");
}
System.out.println("The above matrix value after changing ");
for(i = 0; i < column; i++)
{
for(j = 0; j < row; j++)
{
System.out.print(array[j][i]+" ");
}
System.out.println(" ");
}
}
}
/* OUTPUT:
Enter total rows and columns:
2
3
Enter matrix Value:
2 3 4
5 6 7
The above matrix value before Changing
2 3 4
5 6 7
The above matrix value after changing
2 5
3 6
4 7
*/
Write a program to design a screen using Awt that will take a user name and password. If the user name and password are not same, raise an Exception with appropriate message. User can have 3 login chances only. Use clear button to clear the TextFields.
/* ) Write a Java program to design a screen using Awt that will take a user name and
password. If the user name and password are not same, raise an Exception with
appropriate message. User can have 3 login chances only. Use clear button to clear
the TextFields.
*/
import javax.naming.InvalidNameException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class InvalidPasswordException extends Exception
{
InvalidPasswordException()
{
System.out.println("Invalid Name and Password!!!");
}
}
public class Email extends Frame implements ActionListener {
Label userNameLabel, userPasswordLabel;
Button Login, Clear;
TextField username, password, message;
Panel p;
char ch = '*';
int attempt = 0;
void setMethod() {
p = new Panel();
setTitle("Email");
setSize(350, 300);
setVisible(true);
setResizable(false);
userNameLabel = new Label("Enter the UserName:");
userPasswordLabel = new Label("Enter the UserPassword:");
username = new TextField(20);
password = new TextField(20);
password.setEchoChar(ch);
message = new TextField(20);
message.setEnabled(false);
Login = new Button("Login");
Clear = new Button("Clear");
p.add(userNameLabel);
p.add(username);
p.add(userPasswordLabel);
p.add(password);
p.add(Login);
p.add(Clear);
p.add(message);
add(p);
Login.addActionListener(this);
Clear.addActionListener(this);
}
public static void main(String[] args) {
Email obj = new Email();
obj.setMethod();
}
public void actionPerformed(ActionEvent ae) {
try
{
if(attempt < 3)
{
if (ae.getSource() == Clear)
{
username.setText("");
password.setText("");
username.requestFocus();
}
if (ae.getSource() == Login)
{
String uname = username.getText();
String pname = password.getText();
if (uname.compareTo(pname) == 0)
{
message.setText("Valid");
System.out.println("Email is Valid..");
}
else
{
message.setText("Invalid");
throw new InvalidPasswordException();
}
}
attempt++;
}
else
{
System.out.println("Attempt is greater than 3!!!");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Slip 5
Write a program for multilevel inheritance such that Country is inherited from Continent. State is inherited from Country. Display the place, State, Country and Continent.
/*
Write a program for multilevel inheritance such that country is inherited from continent.
State is inherited from country. Display the place, state, country and continent.
*/
import java.util.Scanner;
class Contient
{
String continent;
Scanner sc = new Scanner(System.in);
public void coninput()
{
System.out.println("Enter the Continent: ");
continent =sc.next();
}
}
class Country extends Contient
{
String country;
public void couinput()
{
System.out.println("Enter the Country: ");
country = sc.next();
}
}
class State extends Country
{
String state;
public void stateinput()
{
System.out.println("Enter the State: ");
state = sc.next();
}
}
class Multilevel_Inheritance extends State
{
String area;
public void AreaInput()
{
System.out.println("Enter the Area: ");
area = sc.next();
}
}
public class Ass3_SetA_a
{
public static void main(String[] args)
{
Multilevel_Inheritance obj = new Multilevel_Inheritance();
obj.coninput();
obj.couinput();
obj.stateinput();
obj.AreaInput();
System.out.println("Continent : "+obj.continent);
System.out.println("Country : "+obj.country);
System.out.println("State : "+obj.state);
System.out.println("Area : "+obj.area);
}
}
/* OUTPUT:
PS C:\Users\Swapniljamble\IdeaProjects\demo1\helloj\src> javac Ass3_SetA_a.java
PS C:\Users\Swapniljamble\IdeaProjects\demo1\helloj\src> java Ass3_SetA_a
Enter the Continent:
Asia
Enter the Country:
India
Enter the State:
Maharashtra
Enter the Area:
Supe
Continent : Asia
Country : India
State : Maharashtra
Area : Supe
*/
Write a menu driven program to perform the following operations on multidimensional array ie matrices :
Addition
Multiplication
Exit
import java.util.Scanner;
class Ass1_SetB_c
{
public static void main(String arr[])
{
int a,b,n,ch;
Scanner sc = new Scanner(System.in);
System.out.println("How many number of rows in matrix:");
a = sc.nextInt();
System.out.println("How many number of columns in matrix:");
b = sc.nextInt();
int m1[][] = new int[a][b];
int m2[][] = new int[a][b];
System.out.println("Enter the 1st matrix:");
for(int i=0; i<m1.length; i++)
{
for(int j=0; j<m1.length; j++)
{
m1[i][j] = sc.nextInt();
}
}
System.out.println("1st matrix is:");
for(int i=0; i<m1.length; i++)
{
for(int j=0; j<m1.length; j++)
{
System.out.print(m1[i][j]+" ");
}
System.out.println();
}
System.out.println("Enter the 2st matrix:");
for(int i=0; i<m2.length; i++)
{
for(int j=0; j<m2.length; j++)
{
m2[i][j] = sc.nextInt();
}
}
System.out.println("2st matrix is:");
for(int i=0; i<m2.length; i++)
{
for(int j=0; j<m2.length; j++)
{
System.out.print(m2[i][j]+" ");
}
System.out.println();
}
do
{
System.out.println("1.Addition:");
System.out.println("2.Multiplication:");
System.out.println("3.Exit:");
System.out.println("Plz Enter ur choice:");
ch = sc.nextInt();
switch(ch)
{
case 1:
int sum[][] = new int[a][b];
for(int i=0; i<m2.length; i++)
{
for(int j=0; j<m2.length; j++)
{
sum[i][j] = m1[i][j] + m2[i][j];
}
}
System.out.println("Addition of m1 and m2:");
for(int i=0; i<m2.length; i++)
{
for(int j=0; j<m2.length; j++)
{
System.out.print(sum[i][j]+" ");
}
System.out.println();
}
break;
case 2:
int mul[][] = new int[a][b];
for(int i=0; i<m2.length; i++)
{
for(int j=0; j<m2.length; j++)
{
mul[i][j] = m1[i][j] * m2[i][j];
}
}
System.out.println("Multiplication of m1 and m2:");
for(int i=0; i<m2.length; i++)
{
for(int j=0; j<m2.length; j++)
{
System.out.print(mul[i][j]+" ");
}
System.out.println();
}
break;
}
}while(ch!=3);
}
}
Slip 6
Write a program to display the Employee(Empid, Empname, Empdesignation, Empsal) information using toString().
/*
Write a program to display the Employee(Empid, Empname,
Empdesignation, Empsal) information using toString().
*/
public class Employee_toString {
int Empid;
String Empname, Empdesignation;
float Empsal;
Employee_toString(int Empid,String Empname,String Empdesignation,float Empsal)
{
this.Empid = Empid;
this.Empname = Empname;
this.Empdesignation = Empdesignation;
this.Empsal = Empsal;
}
public String toString()
{
return "\nEmployee id :"+Empid+" \tEmployee Name :"+Empname+"\t Employee Designation :"+Empdesignation+"\t Employee Salary :"+Empsal;
}
public static void main(String[] args) {
Employee_toString obj = new Employee_toString(100,"Swapnil","London",50000);
Employee_toString obj1 = new Employee_toString(101,"Saurabh","London",55000);
Employee_toString obj2 = new Employee_toString(102,"Omkar","France",10000);
Employee_toString obj3 = new Employee_toString(103,"Abhi","America",44000);
System.out.println(obj);
System.out.println(obj1);
System.out.println(obj2);
System.out.println(obj3);
}
}
/* OUTPUT
Employee id :100 Employee Name :Swapnil Employee Designation :London Employee Salary :50000.0
Employee id :101 Employee Name :Saurabh Employee Designation :London Employee Salary :55000.0
Employee id :102 Employee Name :Omkar Employee Designation :France Employee Salary :10000.0
Employee id :103 Employee Name :Abhi Employee Designation :America Employee Salary :44000.0
*/
Create an abstract class “order” having members id, description. Create two subclasses “Purchase Order” and “Sales Order” having members customer name and Vendor name respectively. Define methods accept and display in all cases. Create 3 objects each of Purchase Order and Sales Order and accept and display details.
/* Set B
Create an abstract class order having members id,description.
Create two subclasses Purchase Order and Sales Order having members customer name and Vendor name respectively.
Define methods accept and display in all cases.
Create 3 objects each of Purchase Order and Sales Order and accept and display details.
*/
import java.util.*;
abstract class order
{
int id;
String descp;
Scanner sc = new Scanner(System.in);
public void setData(int id, String descp)
{
this.id=id;
this.descp=descp;
}
abstract public void accept();
abstract public void display();
}
class purchase_order extends order
{
String cname;
public void accept()
{
System.out.println("Enter Customer Name :");
String n = sc.nextLine();
cname=n;
}
public void display()
{
System.out.println("\t"+id +"\t"+descp+"\t\t"+cname);
}
}
class sales_order extends order
{
String vname;
public void accept()
{
System.out.println("Enter Vendor Name :");
String n = sc.nextLine();
vname=n;
}
public void display(){
System.out.println("\t"+id +"\t"+descp+"\t\t"+vname);
}
}
public class Ass3_SetB_a
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
purchase_order p[] = new purchase_order[3];
for (int i = 0; i < 3; i++)
{
p[i] = new purchase_order();
System.out.println("\nEnter "+(i+1)+" Customer Data :");
System.out.println("Enter ID :");
int cid = sc.nextInt();
sc.nextLine();
System.out.println("Enter Description :");
String desc = sc.nextLine();
p[i].setData(cid, desc);
p[i].accept();
}
System.out.println("\n\t\tPurchased Details.\n");
System.out.println("\tID\tDescription\tCname");
for (int i = 0; i < 3; i++)
{
p[i].display();
}
sales_order s[] = new sales_order[3];
for (int i = 0; i < 3; i++)
{
s[i] = new sales_order();
System.out.println("\nEnter "+(i+1)+" Vendor Data :");
System.out.println("Enter ID :");
int cid = sc.nextInt();
sc.nextLine();
System.out.println("Enter Description :");
String desc = sc.nextLine();
s[i].setData(cid, desc);
s[i].accept();
}
System.out.println("\n\t\tSales Details.\n");
System.out.println("\tID\tDescription\tVname");
for (int i = 0; i < 3; i++)
{
s[i].display();
}
}
}
/* OUTPUT:
PS C:\Users\Swapniljamble\IdeaProjects\demo1\helloj\src> javac Ass3_SetB_a.java
PS C:\Users\Swapniljamble\IdeaProjects\demo1\helloj\src> java Ass3_SetB_a
Enter 1 Customer Data :
Enter ID :
10
Enter Description :
laptop
Enter Customer Name :
Mr.Tony
Enter 2 Customer Data :
Enter ID :
11
Enter Description :
TV
Enter Customer Name :
Mr.Saurabh
Enter 3 Customer Data :
Enter ID :
12
Enter Description :
Mobile
Enter Customer Name :
Mr.Sanket
Purchased Details.
ID Description Cname
10 laptop Mr.Tony
11 TV Mr.Saurabh
12 Mobile Mr.Sanket
Enter 1 Vendor Data :
Enter ID :
1
Enter Description :
Mobile
Enter Vendor Name :
Mr.Rahul
Enter 2 Vendor Data :
Enter ID :
2
Enter Description :
laptop
Enter Vendor Name :
Mr.Virat
Enter 3 Vendor Data :
Enter ID :
3
Enter Description :
TV
Enter Vendor Name :
Mr.Kedar
Sales Details.
ID Description Vname
1 Mobile Mr.Rahul
2 laptop Mr.Virat
3 TV Mr.Kedar
*/
Slip 7
Design a class for Bank. Bank Class should support following operations; a. Deposit a certain amount into an account b. Withdraw a certain amount from an account c. Return a Balance value specifying the amount with details
/*
Design a class for Bank. Bank Class should support following operations;
a. Deposit a certain amount into an account
b. Withdraw a certain amount from an account
c. Return a Balance value specifying the amount with details
*/
import java.util.Scanner;
public class Bank {
String name;
int money;
Scanner sc = new Scanner(System.in);
void createAccount()
{
System.out.println("Enter the name of the new Account Holder:");
name = sc.next();
System.out.println("Enter the money u want to Deposit");
money = sc.nextInt();
}
void deposit()
{
System.out.println("Enter the money u want to deposit:");
int deposit_money = sc.nextInt();
money = money + deposit_money;
System.out.println("Successfully Deposit");
System.out.println("Account Balance is:"+money);
}
void withdraw()
{
System.out.println("Enter the how much money u want to withdraw:");
int withdraw_money = sc.nextInt();
if(money>=withdraw_money)
{
money = money - withdraw_money;
System.out.println("Successfully Withdraw");
System.out.println("Account Balance is:"+money);
}
}
void accountDetail()
{
System.out.println("Account Holder:"+name);
System.out.println("Account Balnce:"+ money);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Create ur Bank Account:");
Bank obj = new Bank();
obj.createAccount();
int ch;
do {
System.out.println("\nPls Sir Enter ur choice:");
System.out.println("1.Deposit\n2.Withdraw\n3.Amount Detail");
System.out.println("Enter ur choice:");
ch = sc.nextInt();
switch(ch)
{
case 1: obj.deposit();
break;
case 2: obj.withdraw();
break;
case 3: obj.accountDetail();
break;
default:
System.out.println("Invalid Case!!!");
}
}while(ch!=0);
}
}
/* OUTPUT:
Create ur Bank Account:
Enter the name of the new Account Holder:
Swapnil
Enter the money u want to Deposit
1000
Pls Sir Enter ur choice:
1.Deposit
2.Withdraw
3.Amount Detail
Enter ur choice:
3
Account Holder:Swapnil
Account Balnce:1000
Pls Sir Enter ur choice:
1.Deposit
2.Withdraw
3.Amount Detail
Enter ur choice:
1
Enter the money u want to deposit:
500
Successfully Deposit
Account Balance is:1500
Pls Sir Enter ur choice:
1.Deposit
2.Withdraw
3.Amount Detail
Enter ur choice:
2
Enter the how much money u want to withdraw:
1000
Successfully Withdraw
Account Balance is:500
Pls Sir Enter ur choice:
1.Deposit
2.Withdraw
3.Amount Detail
Enter ur choice:
3
Account Holder:Swapnil
Account Balnce:500
Pls Sir Enter ur choice:
1.Deposit
2.Withdraw
3.Amount Detail
Enter ur choice:
*/
Write a program to accept a text file from user and display the contents of a file in reverse order and change its case.
import java.io.*;
import java.util.*;
class TextFile
{
public static void main(String args[]) throws IOException
{
FileReader f = new FileReader("myfile.txt");
Scanner sc = new Scanner(f);
String CH,CH2;
while(sc.hasNext())
{
StringBuilder CH1 = new StringBuilder();
CH = sc.nextLine();
CH2=CH.toUpperCase();
CH1.append(CH2);
CH1.reverse();
System.out.println(CH1);
}
f.close();
}
}
/* OUTPUT:
C:\Users\swapniljamble\Documents\javapad programs>javac TextFile.java
C:\Users\swapniljamble\Documents\javapad programs>java TextFile
S'EYUG PU S'TAHW OLLEH
..GINROM DOOG
myfile.txt
hello whats's up guye's
good morning..
*/
Slip 8
Create a class Sphere, to calculate the volume and surface area of sphere. (Hint : Surface area=4*3.14(r*r), Volume=(4/3)3.14(r*r*r))
/*
Create a class Sphere, to calculate the volume and surface area of
sphere.
(Hint : Surface area=4*3.14(r*r), Volume=(4/3)3.14(r*r*r))
*/
import java.util.Scanner;
public class SphereVolume {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the radius of the sphere:");
float r = sc.nextFloat();
double v = (4/3)*3.14*(r*r*r);
double sa = 4*3.14*(r*r);
System.out.println("The volume of the Sphere is: "+v);
System.out.println("The surface area of the Sphere is: "+sa);
}
}
/* OUTPUT:
Enter the radius of the sphere:
5
The volume of the Sphere is: 392.5
The surface area of the Sphere is: 314.0
*/
Design a screen to handle the Mouse Events such as MOUSE_MOVED and MOUSE_CLICKED and display the position of the Mouse_Click in a TextField.
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
TextField t,t1;
Label l,l1;
int x,y;
Panel p;
MyFrame(String title)
{
super(title);
setLayout(new FlowLayout());
p=new Panel();
p.setLayout(new GridLayout(2,2,5,5));
t=new TextField(20);
l= new Label("Co-ordinates of clicking");
l1= new Label("Co-ordinates of movement");
t1=new TextField(20);
p.add(l);
p.add(t);
p.add(l1);
p.add(t1);
add(p);
addMouseListener(new MyClick());
addMouseMotionListener(new MyMove());
setSize(500,500);
setVisible(true);
}
class MyClick extends MouseAdapter
{
public void mouseClicked(MouseEvent me)
{
x=me.getX();
y=me.getY();
t.setText("X="+x+" Y="+y);
}
}
class MyMove extends MouseMotionAdapter
{
public void mouseMoved(MouseEvent me)
{
x=me.getX();
y=me.getY();
t1.setText("X="+ x +" Y="+y);
}
}
}
class mouseclick
{
public static void main(String args[])
{
MyFrame f = new MyFrame("Mouse screen");
}
}
Slip 9
Define a “Clock” class that does the following ; a. Accept Hours, Minutes and Seconds b. Check the validity of numbers c. Set the time to AM/PM mode Use the necessary constructors and methods to do the above task
/*
Define a “Clock” class that does the following ;
a. Accept Hours, Minutes and Seconds
b. Check the validity of numbers
c. Set the time to AM/PM mode
Use the necessary constructors and methods to do the above task
*/
import java.util.Scanner;
public class Clock {
int hour,min,sec;
String mode;
Scanner sc = new Scanner(System.in);
Clock()
{
System.out.println("Enter the Hour, Minutes & Seconds:");
hour = sc.nextInt();
min = sc.nextInt();
sec = sc.nextInt();
}
void checkValid()
{
if(hour>12 && hour<1)
System.out.println("Ur input is wrong..");
if(min>60 && min<0)
System.out.println("Ur input is wrong..");
if(sec>60 && sec<0)
System.out.println("Ur input is wrong..");
}
void setTime()
{
System.out.println("Set the mode of time AM/Pm");
mode = sc.next();
}
void display()
{
System.out.println(hour+":"+min+":"+sec+"|"+mode);
}
public static void main(String[] args) {
Clock obj = new Clock();
obj.checkValid();
obj.setTime();
obj.display();
}
}
/* OUTPUT:
Enter the Hour, Minutes & Seconds:
10
50
30
Set the mode of time AM/Pm
AM
10:50:30|AM
*/
import java.util.*;
interface ProductMarker
{
}
class Product implements ProductMarker
{
int id;
String name;
int cost;
int quantity;
int count;
Product(){
id=0;
name=" ";
cost=0;
quantity=0;
}
Product(int id, String name, int cost, int quantity){
this.id=id;
this.name=name;
this.cost=cost;
this.quantity=quantity;
this.count++;
}
}
public class Products
{
public static void main(String[] args)
{
int count=0;
Scanner a = new Scanner(System.in);
System.out.println("How many product ?");
int number = a.nextInt();
System.out.println("\n");
Product products[] = new Product[number];
System.out.println("Enter Product data");
for(int k=0; k<number; k++)
{
System.out.println("Product Id ");
int id =a.nextInt();
System.out.println("Product name ");
String name = a.next();
System.out.println("Product cost ");
int cost = a.nextInt();
System.out.println("Product qantity ");
int quantity = a.nextInt();
System.out.println("\n");
products[k] = new Product(id, name, cost, quantity);
count++;
}
//Testing for marker interface
if(products[0] instanceof ProductMarker){
System.out.println("Class is using ProductMarker");
}
System.out.println(" Product details\n");
for(Product product:products)
{
System.out.println("Product Id " + product.id);
System.out.println("Product name " + product.name);
System.out.println("Product cost " + product.cost);
System.out.println("Product qantity " + product.quantity);
System.out.println("\n");
}
System.out.println("Total object is "+count);
}
}
/* OUTPUT:
How many product ?
3
Enter Product data
Product Id
1
Product name
soap
Product cost
50
Product qantity
2
Product Id
2
Product name
pen
Product cost
5
Product qantity
5
Product Id
3
Product name
sack
Product cost
500
Product qantity
1
Class is using ProductMarker
Product details
Product Id 1
Product name soap
Product cost 50
Product qantity 2
Product Id 2
Product name pen
Product cost 5
Product qantity 5
Product Id 3
Product name sack
Product cost 500
Product qantity 1
Total object is 3
*/
Write a program to find the cube of given number using functional interface.
/*
Write a program to find the cube of given number using functional interface
my note: functional interface means only single abstract class.
*/
import java.util.Scanner;
interface Cube
{
void funcCube(int num);
}
class Concrete implements Cube
{
public void funcCube(int num)
{
System.out.println("The cube of "+num+" is: "+Math.pow(num,3));
}
}
public class Functional_Interface {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number:");
int num = sc.nextInt();
Concrete obj = new Concrete();
obj.funcCube(num);
}
}
Write a program to create a package name student. Define class StudentInfo with method to display information about student such as rollno, class, and percentage.
Create another class StudentPer with method to find percentage of the student. Accept student details like rollno, name, class and marks of 6 subject from user.
//package student;
import java.util.Scanner;
class StudentInfo
{
int rollno;
String std;
float percentage;
StudentInfo(int rollno,String std)
{
this.rollno = rollno;
this.std = std;
}
void display()
{
System.out.println("Rollno :"+rollno+"\t Class :"+std);
}
}
public class mystud extends StudentInfo // class StudentPer
{
int marks[] = new int[5];
float total;
float percentage;
mystud(int rollno,String std)
{
super(rollno,std);
Scanner sc = new Scanner(System.in);
System.out.println("Enter the marks of 5 subject out of 100:");
for(int i=0;i<5;i++)
marks[i] = sc.nextInt();
}
void findPer()
{
for(int i=0;i<5;i++)
total += marks[i];
percentage = (total/500)*100;
}
void display()
{
super.display();
System.out.println("Percentage:"+percentage);
}
public static void main(String[] args) {
mystud stud = new mystud(50,"nihan");
stud.findPer();
stud.display();
}
}
/* OUTPUT:
Enter the marks of 5 subject out of 100:
88
67
78
98
50
Rollno :50 Class :nihan
Percentage:76.200005
*/
Slip 11
Define an interface “Operation” which has method volume( ).Define a constant PI having a value 3.142 Create a class cylinder which implements this interface (members – radius, height). Create one object and calculate the volume.
/*
Define an interface “Operation” which has method volume(). Define a constant PI having a value 3.142
Create a class cylinder which implements this interface (members – radius, height).
Create one object and calculate the volume.
*/
import java.util.Scanner;
interface Operation
{
final float PI = (float) 3.142;
public void volume();
}
class cylinder implements Operation
{
float r,h;
public void volume()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the radius and volume of cylinder:");
r = sc.nextFloat();
h = sc.nextFloat();
System.out.println("The volume of cylinder is: "+ (PI*r*r*h));
}
}
public class Operation_Interface {
public static void main(String[] args) {
cylinder obj = new cylinder();
obj.volume();
}
}
Write a program to accept the username and password from user if username and password are not same then raise "Invalid Password" with appropriate msg.
/*
Write a program to accept the username and password from user if
username and password are not same then raise "Invalid Password" with
appropriate msg.
*/
import java.util.Scanner;
public class Username_Password {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String userName,password;
System.out.println("Enter the user name :");
userName = sc.next();
System.out.println("Enter the password :");
password = sc.next();
if(userName.equals(password))
System.out.println("username and password are same...");
else
System.out.println("Invalid Password...");
}
}
/*
Enter the user name :
nislihan
Enter the password :
nislihan
username and password are same...
Or
Enter the user name :
nihan
Enter the password :
nihal
Invalid Password...
*/
Slip 12
Write a program to create parent class College(cno, cname, caddr) and derived class Department(dno, dname) from College. Write a necessary methods to display College details.
/*
Write a program to create parent class College(cno, cname, caddr)
and derived class Department(dno, dname) from College. Write a
necessary methods to display College details.
*/
import java.util.Scanner;
class College
{
int cno;
String cname;
String caddr;
College()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the college number:");
cno = sc.nextInt();
System.out.println("Enter the college name:");
cname = sc.next();
System.out.println("Enter the college Address:");
caddr = sc.next();
}
void display()
{
System.out.println("College Number :"+cno+" College Name :"+cname+" College Address :"+caddr);
}
}
public class College_Department extends College // class Department extends College
{
int dno;
String dname;
Scanner sc = new Scanner(System.in);
College_Department()
{
super();
System.out.println("Enter the department number :");
dno = sc.nextInt();
System.out.println("Enter the department name: ");
dname = sc.next();
}
void display()
{
super.display();
System.out.println("Department Number :"+dno+" Department Name :"+dname);
}
public static void main(String[] args)
{
College_Department obj = new College_Department();
obj.display();
}
}
/* output:
Enter the college number:
0
Enter the college name:
LearnWorld
Enter the college Address:
LearnOnline
Enter the department number :
0
Enter the department name:
LearnComputer
College Number :0 College Name :LearnWorld College Address :LearnOnline
Department Number :0 Department Name :LearnComputer
*/
Write a java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits and for the +, -, *, % operations. Add a text field to display the result
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calsi extends JFrame implements ActionListener {
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JTextField txt= new JTextField(10);
JButton b0 = new JButton("0");
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton bsum = new JButton("+");
JButton bsub = new JButton("-");
JButton bmul = new JButton("*");
JButton bdiv = new JButton("/");
JButton bdot = new JButton(".");
JButton bequal = new JButton("=");
JButton bclear = new JButton("Clr");
String Oprt = "",str = "";
Float f1,f2;
Calsi()
{
prepareFrame();
addComponents();
addActionEvents();
}
void prepareFrame()
{
setTitle("Calsi");
setSize(300,300);
setVisible(true);
setLayout(new GridLayout());
addWindowListener(new MyWindow() );
}
void addComponents()
{
p1.add(txt);
p2.add(b0);
p2.add(b1);
p2.add(b2);
p2.add(b3);
p2.add(b4);
p2.add(b5);
p2.add(b6);
p2.add(b7);
p2.add(b8);
p2.add(b9);
p2.add(bsum);
p2.add(bsub);
p2.add(bmul);
p2.add(bdiv);
p2.add(bdot);
p2.add(bequal);
p2.add(bclear);
add(p1);
add(p2);
}
void addActionEvents()
{
b0.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
bsum.addActionListener(this);
bsub.addActionListener(this);
bmul.addActionListener(this);
bdiv.addActionListener(this);
bdot.addActionListener(this);
bequal.addActionListener(this);
bclear.addActionListener(this);
}
public static void main(String[] args)
{
Calsi obj = new Calsi();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == b0)
str = str + b0.getText();
if(e.getSource() == b1)
str = str + b1.getText();
if(e.getSource() == b2)
str = str + b2.getText();
if(e.getSource() == b3)
str = str + b3.getText();
if(e.getSource() == b4)
str = str + b4.getText();
if(e.getSource() == b5)
str = str + b5.getText();
if(e.getSource() == b6)
str = str + b6.getText();
if(e.getSource() == b7)
str = str + b7.getText();
if(e.getSource() == b8)
str = str + b8.getText();
if(e.getSource() == b9)
str = str + b9.getText();
if(e.getSource() == bdot)
str = str + bdot.getText();
txt.setText(str);
if(e.getSource() == bsum)
{
Oprt = "+";
txt.setText(Oprt);
f1 = Float.parseFloat(str);
str = "";
}
if(e.getSource() == bequal)
{
if(Oprt.equals("+"))
{
f2 = Float.parseFloat(str);
txt.setText(( f1+f2 ) + "");
str = "";
}
}
else if(e.getSource() == bsub)
{
Oprt = "-";
txt.setText(Oprt);
f1 = Float.parseFloat(str);
str = "";
}
if(e.getSource() == bequal)
{
if(Oprt.equals("-"))
{
f2 = Float.parseFloat(str);
txt.setText(( f1-f2 ) + "");
str = "";
}
}
else if (e.getSource() == bmul) {
Oprt = "*";
txt.setText("");
f1 = Float.parseFloat(str);
str = "";
}
if (e.getSource() == bequal) {
if (Oprt.equals("*")) {
f2 = Float.parseFloat(str);
txt.setText((f1 * f2) + "");
str = "";
}
}
else if (e.getSource() == bdiv) {
Oprt = "/";
txt.setText("");
f1 = Float.parseFloat(str);
str = "";
}
if (e.getSource() == bequal) {
if (Oprt.equals("/")) {
f2 = Float.parseFloat(str);
txt.setText((f1 / f2) + "");
str = "";
}
}
if (e.getSource() == bclear)
{
txt.setText("");
str = "";
f1 = null;
f2 = null;
}
}
class MyWindow extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
dispose();
System.out.println("Window is closed..");
}
}
}
Slip 13
Write a program to accept a file name from command prompt, if the file exits then display number of words and lines in that file.
/*
Write a program to accept a file name from command prompt, if
the file exits then display number of words and lines in that file.
*/
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class FilesWordsLines {
public static void main(String[] args) throws IOException {
// String words[];
String txt;
int lines = 0;
int len = 0;
File fp = new File(args[0]);
if(fp.exists())
{
BufferedReader br = new BufferedReader(new FileReader(fp));
while((txt = br.readLine()) != null)
{
String words[] = txt.split(" ");
lines ++;
len = len +words.length;
}
System.out.println("No. of words in file :"+len);
System.out.println("No. of lines in file :"+lines);
}
else
System.out.println("ohhh.. file not exist..");
}
}
/*
Filename : Myfiledata.txt
learn with nil
learn world
learn music
OUTPUT:
PS C:\Users\swapnniljamble\IdeaProjects\MyProject\src> javac FilesWordsLines.java
PS C:\Users\swapniljamble\IdeaProjects\MyProject\src> java FilesWordsLines Myfiledata.txt
No. of words in file :7
No. of lines in file :3
*/
Write a program to display the system date and time in various formats shown below: Current date is : 31/08/2021 Current date is : 08-31-2021 Current date is : Tuesday August 31 2021 Current date and time is : Fri August 31 15:25:59 IST 2021 Current date and time is : 31/08/21 15:25:59 PM +0530
/*
) Write a program to display the system date and time in various
formats shown below:
Current date is : 31/08/2021
Current date is : 08-31-2021
Current date is : Tuesday August 31 2021
Current date and time is : Fri August 31 15:25:59 IST 2021
Current date and time is : 31/08/21 15:25:59 PM +0530
*/
import java.text.SimpleDateFormat;
import java.util.Date;
public class Date_Time {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
String str1 = sdf1.format(date);
System.out.println("Current date is :"+str1);
SimpleDateFormat sdf2 = new SimpleDateFormat("MM-dd-yyyy");
String str2 = sdf2.format(date);
System.out.println("Current date is :"+str2);
SimpleDateFormat sdf3 = new SimpleDateFormat("EEEEE MMMM dd yyyy");
String str3 = sdf3.format(date);
System.out.println("Current date is :"+str3);
SimpleDateFormat sdf4 = new SimpleDateFormat("EEE MM dd hh:mm:ss z ");
String str4 = sdf4.format(date);
System.out.println("Current date and time is :"+str4);
SimpleDateFormat sdf5 = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a Z ");
String str5 = sdf5.format(date);
System.out.println("Current date and time is :"+str5);
}
}
/* OUTPUT
Current date is :25/12/2022
Current date is :12-25-2022
Current date is :Sunday December 25 2022
Current date and time is :Sun 12 25 03:19:46 IST
Current date and time is :25/12/2022 03:19:46 pm +0530
*/
Slip 14
Write a program to accept a number from the user, if number is zero then throw user defined exception “Number is 0” otherwise check whether no is prime or not (Use static keyword).
/*
Write a program to accept a number from the user, if number is zero
then throw user defined exception “Number is 0” otherwise check
whether no is prime or not (Use static keyword).
*/
import java.io.IOException;
import java.util.Scanner;
class NumberZeroException extends Exception
{
NumberZeroException()
{
System.out.println("Numebr is zero");
}
}
public class Number_Zero {
static boolean Isprime(int num)
{
boolean flag = true;
if(num<=1)
return false;
for(int i=2; i<num; i++)
{
if(num%2 == 0)
{
flag = false;
break;
}
}
return flag;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int num;
try
{
System.out.println("Enter the number:");
num = sc.nextInt();
if(num == 0)
{
throw new NumberZeroException();
}
System.out.println("Number is :"+num);
if(Isprime(num))
System.out.println(num +" is prime number...");
else
System.out.println(num +" is not prime number...");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
/*
Enter the number:
153
Number is :153
153 is prime number...
Or
Enter the number:
0
Numebr is zero
NumberZeroException
*/
Write a Java program to create a Package “SY” which has a class SYMarks (members – ComputerTotal, MathsTotal, and ElectronicsTotal).
package SYMarks;
import java.util.Scanner;
public class syclass {
public int Computer,Math,Electronics;
public syclass(){}
public void get()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter marks of students for Computer, Maths and Electronics subject out of 200 ");
Computer=sc.nextInt();
Math = sc.nextInt();
Electronics = sc.nextInt();
}
}
package TYMarks;
import java.util.Scanner;
public class tyclass
{
public int TheoryMarks,PracticalMarks;
public tyclass() {}
public void get() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the marks of the Theory out of 400 and Practicals out of 200: ");
TheoryMarks = sc.nextInt();
PracticalMarks = sc.nextInt();
}
}
/*
Write a Java program to create a Package “SY” which has a class SYMarks (members – ComputerTotal, MathsTotal, and ElectronicsTotal).
Create another package TY which has a class TYMarks (members – Theory, Practicals).
Create n objects of Student class (having rollNumber, name, SYMarks and TYMarks).
Add the marks of SY and TY computer subjects and calculate the Grade (‘A’ for >= 70, ‘B’ for >= 60 ‘C’ for >= 50 , Pass Class for > =40 else ‘FAIL’)
and display the result of the student in proper format.
*/
// program for n object of Student-
package sytyclass;
import SYMarks.syclass;
import TYMarks.tyclass;
import java.util.Scanner;
class StudentInfo{
int rollno;
String name,grade;
public float gt,tyt,syt;
public float per;
public void get()
{
System.out.println("Enter roll number and name of the student: ");
Scanner sc = new Scanner(System.in);
rollno=sc.nextInt();
name = sc.next();
}
}
public class mainclass {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of students:");
int n= sc.nextInt();
syclass sy[]=new syclass[n];
tyclass ty[]=new tyclass[n];
StudentInfo si[]=new StudentInfo[n];
for(int i=0;i<n;i++)
{
si[i]=new StudentInfo();
sy[i]=new syclass();
ty[i]=new tyclass();
si[i].get();
sy[i].get();
ty[i].get();
si[i].syt=sy[i].Computer+sy[i].Electronics+sy[i].Math;
si[i].tyt=ty[i].PracticalMarks+ty[i].TheoryMarks;
si[i].gt=si[i].syt+si[i].tyt;
si[i].per=(si[i].gt/1200)*100;
if(si[i].per>=70) si[i].grade="A";
else if(si[i].per>=60) si[i].grade="B";
else if(si[i].per>=50) si[i].grade="C";
else if(si[i].per>=40) si[i].grade="Pass";
else si[i].grade="Fail";
}
System.out.println("Roll No\tName\tSyTotal\tTyTotal\tGrandTotal\tPercentage\tGrade");
for(int i=0;i<n;i++)
{
System.out.println(si[i].rollno+"\t"+si[i].name+"\t"+si[i].syt+"\t"+si[i].tyt+"\t"+si[i].gt+"\t\t"+si[i].per+"\t\t"+si[i].grade);
}
}
}
/* OUTPUT:
C:\Users\Swapniljamble\Documents\javapad programs>javac -d . syclass.java
C:\Users\Swapniljamble\Documents\javapad programs>javac -d . tyclass.java
C:\Users\Swapniljamble\Documents\javapad programs>javac -d . mainclass.java
C:\Users\Swapniljamble\Documents\javapad programs>java sytyclass.mainclass
Enter the number of students:
3
Enter roll number and name of the student:
50
swapnil
Enter marks of students for Computer, Maths and Electronics subject out of 200
155
66
190
Enter the marks of the Theory out of 400 and Practicals out of 200:
350
150
Enter roll number and name of the student:
10
rahul
Enter marks of students for Computer, Maths and Electronics subject out of 200
90
100
150
Enter the marks of the Theory out of 400 and Practicals out of 200:
300
100
Enter roll number and name of the student:
20
viraj
Enter marks of students for Computer, Maths and Electronics subject out of 200
55
22
51
Enter the marks of the Theory out of 400 and Practicals out of 200:
100
120
Roll No Name SyTotal TyTotal GrandTotal Percentage Grade
50 swapnil 411.0 500.0 911.0 75.916664 A
10 rahul 340.0 400.0 740.0 61.666668 B
20 viraj 128.0 220.0 348.0 29.0 Fail
C:\Users\Swapniljamble\Documents\javapad programs>
Slip 15
Accept the names of two files and copy the contents of the first to the second. First file having Book name and Author name in file
/*
Accept the names of two files and copy the contents of the first to
the second. First file having Book name and Author name in file.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFile1 {
public static void main(String[] args) throws IOException
{
FileInputStream in = new FileInputStream(new File("firstfile.txt"));
FileOutputStream out = new FileOutputStream(new File("secondfile.txt"));
int l;
while((l = in.read()) != -1)
{
out.write(l);
}
System.out.println("Successfully copy content from first file to second file...");
}
}
/*
File 1 name : firstfile.txt
yes u can do it...
learn with nil..
123456789
File 2 name : secondfile.txt
OUTPUT:
PS C:\Users\swapniljamble\IdeaProjects\MyProject\src> javac CopyFile1.java
PS C:\Users\swapniljamble\IdeaProjects\MyProject\src> java CopyFile1
Successfully copy content from first file to second file...
File 1 name : firstfile.txt
yes u can do it...
learn with nil..
123456789
File 2 name : secondfile.txt
yes u can do it...
learn with nil..
123456789
*/
Write a program to define a class Account having members custname, accno. Define default and parameterized constructor. Create a subclass called SavingAccount with member savingbal, minbal. Create a derived class AccountDetail that extends the class SavingAccount with members, depositamt and withdrawalamt. Write a appropriate method to display customer details.
/*
Write a program to define a class Account having members custname, accno.
Define default and parameterized constructor.
Create a subclass called SavingAccount with member savingbal, minbal.
Create a derived class AccountDetail that extends the class SavingAccount with
members, depositamt and withdrawalamt.
Write a appropriate method to display customer details.
*/
class Account
{
int accno;
String custname;
Account()
{}
Account(int accno, String custname)
{
this.accno = accno;
this.custname = custname;
}
void display()
{
System.out.println("Account number :"+accno+" Customer Name :"+custname);
}
}
class SavingAccount extends Account
{
float savingbal,minbal;
SavingAccount(int accno, String custname,float savingbal, float minbal)
{
super(accno,custname);
this.savingbal = savingbal;
this.minbal = minbal;
}
void display()
{
super.display();
System.out.println("saving balance :"+savingbal+" minimum balance :"+minbal);
}
}
public class AccountDetail extends SavingAccount
{
float depositamt,withdrawamt;
AccountDetail(int accno, String custname,float savingbal, float minbal,float depositamt, float withdrawamt)
{
super(accno,custname,savingbal,minbal);
this.depositamt = depositamt;
this.withdrawamt = withdrawamt;
}
void display()
{
super.display();
System.out.println("Deposit Amount :"+depositamt+" Withdraw Amount :"+withdrawamt);
}
public static void main(String[] args) {
AccountDetail customer = new AccountDetail(50395388,"kemal soyadare",1000,5000,700,1000);
customer.display();
}
}
/*OUTPUT:
Account number:50395388 Customer Name:kemal soyadare
saving balance :1000.0 minimum balance :5000.0
Deposit Amount :700.0 Withdraw Amount :1000.0
*/
Design a Super class Customer (name, phone-number). Derive a class Depositor(accno , balance) from Customer. Again, derive a class Borrower (loan-no, loan-amt) from Depositor. Write necessary member functions to read and display the details of ‘n’customers.
/*
Design a Super class Customer (name, phone-number).
Derive a class Depositor(accno , balance) from Customer.
Again, derive a class Borrower (loan-no, loan-amt) from Depositor.
Write necessary member functions to read and display the details of ‘n’customers
*/
import java.util.Scanner;
import java.util.zip.DeflaterOutputStream;
class Customer
{
String name;
long phone_no;
Customer(String name , long phone_no)
{
this.name = name;
this.phone_no = phone_no;
}
void display()
{
System.out.println("Name :"+name +" Phone no :"+phone_no);
}
}
class Depositor extends Customer
{
int accno;
float balance;
Depositor(String name, long phone_no, int accno, float balance)
{
super(name,phone_no);
this.accno = accno;
this.balance = balance;
}
void display()
{
super.display();
System.out.println("Account no :"+accno+" Balance :"+balance);
}
}
public class Borrower extends Depositor {
int loanno;
float loanamt;
Borrower(String name, long phone_no, int accno, float balance,int loanno,float loanamt)
{
super(name,phone_no,accno,balance);
this.loanno = loanno;
this.loanamt = loanamt;
}
void display()
{
super.display();
System.out.println("Loan no :"+loanno+"Loan amount :"+loanamt);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
System.out.println("Enter the no. of person:");
n = sc.nextInt();
Borrower per[] = new Borrower[n];
for(int i=0; i<n; i++)
{
System.out.println("Enter the name:");
String name = sc.next();
System.out.println("Enter the Phone no:");
long phone_no = sc.nextInt();
System.out.println("Enter the Account number:");
int accno = sc.nextInt();
System.out.println("Enter the Balance:");
float balance = sc.nextFloat();
System.out.println("Enter the loan number:");
int loanno = sc.nextInt();
System.out.println("Enter the loan amount:");
float loanamt = sc.nextFloat();
per[i] = new Borrower(name,phone_no,accno,balance,loanno,loanamt);
}
System.out.println("Displaying all person Detail:");
for(int i=0; i<n; i++)
{
per[i].display();
}
}
}
/* OUTPUT:
Enter the no. of person:
3
Enter the name:
kemal
Enter the Phone no:
97753342
Enter the Account number:
999
Enter the Balance:
10500
Enter the loan number:
100
Enter the loan amount:
1000
Enter the name:
swapnil
Enter the Phone no:
93566780
Enter the Account number:
888
Enter the Balance:
100000
Enter the loan number:
101
Enter the loan amount:
56890
Enter the name:
nihan
Enter the Phone no:
92373294
Enter the Account number:
777
Enter the Balance:
105000
Enter the loan number:
102
Enter the loan amount:
100000
Displaying all person Detail:
Name :kemal Phone no :97753342
Account no :999 Balance :10500.0
Loan no :100 Loan amount :1000.0
Name :swapnil Phone no :93566780
Account no :888 Balance :100000.0
Loan no :101 Loan amount :56890.0
Name :nihan Phone no :92373294
Account no :777 Balance :105000.0
Loan no :102 Loan amount :100000.0
*/
Write Java program to design three text boxes and two buttons using swing. Enter different strings in first and second textbox. On clicking the First command button, concatenation of two strings should be displayed in third text box and on clicking second command button, reverse of string should display in third text box
/*
Write Java program to design three text boxes and two buttons using swing.
Enter different strings in first and second textbox.
On clicking the First command button, concatenation of two strings should
be displayed in third text box and
on clicking second command button, reverse of string should display in third text box
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Swing_Strings extends JFrame implements ActionListener
{
JTextField text1 = new JTextField(8);
JTextField text2 = new JTextField(8);
JTextField text3 = new JTextField(8);
JButton Bconcat = new JButton("concat");
JButton Breverse = new JButton("reverse");
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
String str;
Swing_Strings()
{
prepareFrame();
addComponents();
addActionEvents();
}
void prepareFrame()
{
setTitle("MYSwing");
setSize(300,300);
setVisible(true);
setLayout(new GridLayout());
addWindowListener(new MyWindow() );
}
void addComponents()
{
p1.add(text1);
p1.add(text2);
p2.add(Bconcat);
p2.add(Breverse);
p3.add(text3);
add(p1);
add(p2);
add(p3);
}
void addActionEvents()
{
Bconcat.addActionListener(this);
Breverse.addActionListener(this);
}
public static void main(String[] args) {
Swing_Strings obj = new Swing_Strings();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == Bconcat)
{
text3.setText(text1.getText()+text2.getText());
}
if(e.getSource() == Breverse)
{
String first = text1.getText();
// StringBuilder string = new StringBuilder();
// string.append(first);
// text3.setText(String.valueOf(string.reverse()));
char ch;
String rstr ="";
for(int i=0; i<first.length(); i++)
{
ch = first.charAt(i);
rstr = ch + rstr;
}
text3.setText(rstr);
}
}
class MyWindow extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
dispose();
System.out.println("window is closed...");
}
}
}
Slip 18
Write a program to implement Border Layout Manager.
//Q1) Write a program to implement Border Layout Manager.
import java.awt.*;
import javax.swing.*;
public class Border_Layout_Manager
{
JFrame f;
Border_Layout_Manager()
{
f = new JFrame("myframe");
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
Border_Layout_Manager obj = new Border_Layout_Manager();
}
}
Define a class CricketPlayer (name,no_of_innings,no_of_times_notout, totatruns, bat_avg). Create an array of n player objects .Calculate the batting average for each player using static method avg(). Define a static sort method which sorts the array on the basis of average. Display the player details in sorted order.
/*
Define a class CricketPlayer (name,no_of_innings,no_of_times_notout, totatruns, bat_avg).
Create an array of n player objects .
Calculate the batting average for each player using static method avg().
Define a static sort method which sorts the array on the basis of average.
Display the player details in sorted order.
*/
import java.util.Scanner;
public class CricketPlayer {
String name;
int no_of_innings, no_of_times_notout, totalruns;
float bat_avg;
CricketPlayer(String name, int no_of_innings, int no_of_times_notout, int totalruns) {
this.name = name;
this.no_of_innings = no_of_innings;
this.no_of_times_notout = no_of_times_notout;
this.totalruns = totalruns;
}
static void average(CricketPlayer player[],int n)
{
try
{
for(int i=0; i<n; i++)
{
player[i].bat_avg = player[i].totalruns/player[i].no_of_innings;
}
}
catch (Exception e)
{
System.out.println(e);
}
}
static void sort(CricketPlayer player[], int n)
{
for(int i=0; i<n; i++)
{
for(int j=i+1;j<n; j++)
{
if(player[i].bat_avg > player[j].bat_avg)
{
CricketPlayer temp = player[i];
player[i] = player[j];
player[j] = temp;
}
}
}
}
void display(CricketPlayer player[], int n)
{
System.out.println("\n Name :"+name+"\tnumber of innings :"+no_of_innings+"\tnumber of times not out :"+no_of_times_notout+"\tTotal runs :"+totalruns+"\tBat average :"+bat_avg);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numebr of Cricketers:");
int n = sc.nextInt();
CricketPlayer player[] = new CricketPlayer[n];
System.out.println("Enter the cricketer Information:");
for(int i=0; i<n; i++)
{
System.out.println("Enter the Name of Cricketer :"+(i+1));
String name = sc.next();
System.out.println("Enter the Number of innings of Cricketer :"+(i+1));
int no_of_innings = sc.nextInt();
System.out.println("Enter the Number of times not out of Cricketer :"+(i+1));
int no_of_times_notout = sc.nextInt();
System.out.println("Enter the Total runs of Cricketer :"+(i+1));
int totalruns = sc.nextInt();
player[i] = new CricketPlayer(name, no_of_innings, no_of_times_notout, totalruns);
}
CricketPlayer.average(player,n);
CricketPlayer.sort(player,n);
System.out.println("Afer Sorting Cricketers on the basis of their Averages:");
for(int i=0; i<n; i++)
{
player[i].display(player,n);
}
}
}
/* OUTPUT:
Enter the numebr of Cricketers:
3
Enter the cricketer Information:
Enter the Name of Cricketer :1
a
Enter the Number of innings of Cricketer :1
13
Enter the Number of times not out of Cricketer :1
10
Enter the Total runs of Cricketer :1
100
Enter the Name of Cricketer :2
b
Enter the Number of innings of Cricketer :2
8
Enter the Number of times not out of Cricketer :2
5
Enter the Total runs of Cricketer :2
20
Enter the Name of Cricketer :3
c
Enter the Number of innings of Cricketer :3
15
Enter the Number of times not out of Cricketer :3
14
Enter the Total runs of Cricketer :3
4000
Afer Sorting Cricketers on the basis of their Averages:
Name :b number of innings :8 number of times not out :5 Total runs :20 Bat average :2.0
Name :a number of innings :13 number of times not out :10 Total runs :100 Bat average :7.0
Name :c number of innings :15 number of times not out :14 Total runs :4000 Bat average :266.0
*/
Slip 19
Write a program to accept the two dimensional array from user and display sum of its diagonal elements.
//Write a program to accept the two dimensional array from user and
//display sum of its diagonal elements.
import java.util.Scanner;
public class SumOfDiagonal {
public static void main(String[] args) {
Scanner sc = new Scanner((System.in));
System.out.println("Enter the number of rows and columns:");
int r = sc.nextInt();
int c = sc.nextInt();
int arr[][] = new int[r][c];
System.out.println("Enter the matrix:");
for(int i=0; i<arr.length; i++)
{
for(int j=0; j<arr.length; j++)
{
arr[i][j] = sc.nextInt();
}
}
int sum = 0;
for(int i=0; i<arr.length; i++)
{
for(int j=0; j<arr.length; j++)
{
if(i==j)
sum = sum + arr[i][j];
}
}
System.out.println("The sum of diagonal element is:"+sum);
}
}
Write a program which shows the combo box which includes list of T.Y.B.Sc.(Comp. Sci) subjects. Display the selected subject in a text field.
/*
Write a program which shows the combo box which includes list of
T.Y.B.Sc.(Comp. Sci) subjects. Display the selected subject in a text
field.
*/
import javax.swing.*;
import java.awt.event.*;
public class JCombo_Box
{
JFrame f;
JCombo_Box()
{
f = new JFrame("ComboBox Example");
JTextField j = new JTextField(50);
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JButton b=new JButton("Show");
b.setBounds(200,100,75,20);
String languages[]={"C","C++","C#","Java","PHP"};
final JComboBox cb=new JComboBox(languages);
cb.setBounds(50, 100,90,20);
f.add(cb); f.add(label); f.add(b);f.add(j);
f.setLayout(null);
f.setSize(350,350);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "
+ cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String[] args) {
new JCombo_Box();
}
}
Write a program for multilevel inheritance such that Country is inherited from Continent. State is inherited from Country. Display the place, State, Country and Continent.
/*
Write a program for multilevel inheritance such that country is inherited from continent.
State is inherited from country. Display the place, state, country and continent.
*/
import java.util.Scanner;
class Contient
{
String continent;
Scanner sc = new Scanner(System.in);
public void coninput()
{
System.out.println("Enter the Continent: ");
continent =sc.next();
}
}
class Country extends Contient
{
String country;
public void couinput()
{
System.out.println("Enter the Country: ");
country = sc.next();
}
}
class State extends Country
{
String state;
public void stateinput()
{
System.out.println("Enter the State: ");
state = sc.next();
}
}
class Multilevel_Inheritance extends State
{
String area;
public void AreaInput()
{
System.out.println("Enter the Area: ");
area = sc.next();
}
}
public class Ass3_SetA_a
{
public static void main(String[] args)
{
Multilevel_Inheritance obj = new Multilevel_Inheritance();
obj.coninput();
obj.couinput();
obj.stateinput();
obj.AreaInput();
System.out.println("Continent : "+obj.continent);
System.out.println("Country : "+obj.country);
System.out.println("State : "+obj.state);
System.out.println("Area : "+obj.area);
}
}
/* OUTPUT:
PS C:\Users\Swapniljamble\IdeaProjects\demo1\helloj\src> javac Ass3_SetA_a.java
PS C:\Users\Swapniljamble\IdeaProjects\demo1\helloj\src> java Ass3_SetA_a
Enter the Continent:
Asia
Enter the Country:
India
Enter the State:
Maharashtra
Enter the Area:
Supe
Continent : Asia
Country : India
State : Maharashtra
Area : Supe
*/
Write a package for Operation, which has two classes, Addition and Maximum. Addition has two methods add () and subtract (), which are used to add two integers and subtract two, float values respectively. Maximum has a method max () to display the maximum of two integers
/*
Write a package for Operation, which has two classes, Addition and
Maximum. Addition has two methods add () and subtract (), which are
used to add two integers and subtract two, float values respectively.
Maximum has a method max () to display the maximum of two integers
*/
package Operation;
import java.util.Scanner;
class Addition
{
float a,b;
Addition(float a, float b)
{
this.a = a;
this.b = b;
}
float add()
{
return a+b;
}
float sub()
{
return a-b;
}
}
public class Addition_Max {
float a,b;
Addition_Max(float a, float b)
{
this.a = a;
this.b = b;
}
float max()
{
if(a>b)
return a;
else
return b;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the two numbers:");
float a = sc.nextFloat();
float b = sc.nextFloat();
Addition obj = new Addition(a,b);
Addition_Max m = new Addition_Max(a,b);
System.out.println("The addition of two numbers are:"+obj.add());
System.out.println("The substraction of two numbers are:"+obj.sub());
System.out.println("The Maximum of two numbers are:"+m.max());
}
}
/*
Enter the two numbers:
50 6
The addition of two numbers are:56.0
The substraction of two numbers are:44.0
The Maximum of two numbers are:50.0
*/
Slip 21
Define a class MyDate(Day, Month, year) with methods to accept and display a MyDateobject. Accept date as dd,mm,yyyy. Throw user defined exception "InvalidDateException" if the date is invalid.
/*
Define a class MyDate(Day, Month, year) with methods to accept
and display a MyDateobject. Accept date as dd,mm,yyyy. Throw user
defined exception "InvalidDateException" if the date is invalid.
*/
import java.util.Scanner;
class InvalidDateException extends Exception
{
}
class MyDate
{
int day,mon,yr;
void accept(int d,int m,int y)
{
day = d;
mon = m;
yr = y;
}
void display()
{
System.out.println("Date is valid : "+day+"/"+mon+"/"+yr);
}
}
class date
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Date : dd mm yyyy ");
int day = sc.nextInt();
int mon = sc.nextInt();
int yr = sc.nextInt();
int flag=0;
try
{
if(mon<=0 || mon>12)
throw new InvalidDateException();
else
{
if(mon==1 || mon==3 || mon==5 || mon==7 || mon==8 || mon==10 || mon == 12)
{
if(day>=1 && day <=31)
flag=1;
else
throw new InvalidDateException();
}
else if (mon==2)
{
if(yr%4==0)
{
if(day>=1 && day<=29)
flag=1;
else
throw new InvalidDateException();
}
else
{
if(day>=1 && day<=28)
flag=1;
else
throw new InvalidDateException();
}
}
else
{
if(mon==4 || mon == 6 || mon== 9 || mon==11)
{
if(day>=1 && day <=30)
flag=1;
else throw new InvalidDateException();
}
}
}
if(flag== 1)
{
MyDate dt = new MyDate();
dt.accept(day,mon,yr);
dt.display();
}
}
catch (InvalidDateException mm)
{
System.out.println("Invalid Date");
}
}
}
/*
Enter Date : dd mm yyyy
30 12 2023
Date is valid : 30/12/2023
Enter Date : dd mm yyyy
23 13 2023
Invalid Date
*/
OR
// This is simple program for checking date ....okay
import java.util.Scanner;
import java.io.IOException;
class Invaliddates extends Exception
{
public String toString()
{
return "date is Invalid ";
}
}
class DateClass
{
int dd,mm,yy;
DateClass(int dd,int mm,int yy)
{
this.dd = dd;
this.mm = mm;
this.yy = yy;
}
void display()
{
System.out.println(dd+"/"+mm+"/"+yy);
}
}
public class MyDates
{
public static void main(String[] args) throws IOException {
boolean flag = false;
Scanner sc = new Scanner(System.in);
try {
System.out.println("Enter the date:");
int dd = sc.nextInt();
int mm = sc.nextInt();
int yy = sc.nextInt();
if (dd >= 1 && dd <= 31)
flag = true;
else
throw new Invaliddates();
if (mm >= 1 && mm <= 12)
flag = true;
else
throw new Invaliddates();
if (yy >= 1 )
flag = true;
else
throw new Invaliddates();
if (flag == true) {
DateClass d = new DateClass(dd, mm, yy);
d.display();
}
}
catch(Invaliddates e)
{
System.out.println(e);
}
}
}
/*
OUTPUT:
Enter the date:
10
5
2025
10/5/2025
OR
Enter the date:
10
13
2023
date is Invalid
*/
Create an employee class(id,name,deptname,salary). Define a default and parameterized constructor. Use ‘this’ keyword to initialize instance variables. Keep a count of objects created. Create objects using parameterized constructor and display the object count after each object is created. (Use static member and method). Also display the contents of each object.
/*
Create an employee class(id,name,deptname,salary). Define a default and parameterized constructor.
Use 'this' keyword to initialize instance variables.Keep a count of objects created.
Create objects using parameterized constructor and display the object count after each object is created.
(Use static member and method). Also display the contents of each object
*/
class Student
{
static int count;
int id;
String name;
String depname;
float salary;
Student()
{
id = 0;
name = null;
depname = null;
salary = 0.0f;
}
Student(int id, String name, String depname, float salary)
{
this.id = id;
this.name = name;
this.depname = depname;
this.salary = salary;
}
void display()
{
count++;
System.out.println("ID : " + id);
System.out.println("Name : " + name);
System.out.println("Department Name : " + depname);
System.out.println("Salary : " + salary);
System.out.println("The Count of object : " + count);
}
}
public class Ass2_SetA_a
{
public static void main(String[] args)
{
Student student1 = new Student();
Student student2 = new Student(50,"Swapnil","Computer Science",95000.0F);
Student student3 = new Student(5,"Hermione","Computer Science",100000.0F);
student1.display();
student2.display();
student3.display();
}
}
/* OUTPUT:
PS C:\Users\Swapniljamble\IdeaProjects\demo1\helloj\src> javac Ass2_SetA_a.java
PS C:\Users\Swapniljamble\IdeaProjects\demo1\helloj\src> java Ass2_SetA_a
ID : 0
Name : null
Department Name : null
Salary : 0.0
The Count of object : 1
ID : 50
Name : Swapnil
Department Name : Computer Science
Salary : 95000.0
The Count of object : 2
ID : 5
Name : Hermione
Department Name : Computer Science
Salary : 100000.0
The Count of object : 3
*/
Slip 22
Write a program to create an abstract class named Shape that contains two integers and an empty method named printArea(). Provide three classes named Rectangle, Triangle and Circle such that each one of the classes extends the class Shape. Each one of the classes contain only the method printArea() that prints the area of the given shape. (use method overriding).
abstract class shape
{
int a=5,b=8;
abstract public void printArea();
}
class rectangle extends shape
{
public int area_rectangle;
public void printArea()
{
area_rectangle = a*b;
System.out.println("The area of rectangle is:"+area_rectangle);
}
}
class triangle extends shape
{
int area_triangle;
public void printArea()
{
area_triangle = (int) (0.5*a*b);
System.out.println("The area of triangle is:"+area_triangle);
}
}
class circle extends shape
{
int area_circle;
public void printArea()
{
area_circle=(int) (3.14*a*a);
System.out.println("The area of circle is:"+area_circle);
}
}
public class Abstract_Shape {
public static void main(String[] args) {
rectangle r = new rectangle();
r.printArea();
triangle t = new triangle();
t.printArea();
circle r1 = new circle();
r1.printArea();
}
}
/*
The area of rectangle is:40
The area of triangle is:20
The area of circle is:78
*/
Write a program that handles all mouse events and shows the event name at the center of the Window, red in color when a mouse event is fired. (Use adapter classes)
/*10.WRITE A JAVA PROGRAM THAT HANDLES ALL MOUSE EVENTS AND SHOWS THE EVENT
NAME AT THE CENTER OF THE WINDOW WHEN A MOUSE EVENT IS FIRED.(USE ADAPTER
CLASSES).*/
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
class MouseEvent extends JFrame implements MouseListener
{
JLabel l1;
public MouseEvent()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
setLayout(new FlowLayout());
l1=new JLabel();
Font f=new Font("Verdana",Font.BOLD,20);
l1.setFont(f);
l1.setForeground(Color.BLUE);
l1.setAlignmentX(Component.CENTER_ALIGNMENT);
l1.setAlignmentY(Component.CENTER_ALIGNMENT);
add(l1);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m)
{
l1.setText("Mouse Exited");
}
public void mouseEntered(MouseEvent m)
{
l1.setText("Mouse Entered");
}
public void mouseReleased(MouseEvent m)
{
l1.setText("Mouse Released");
}
public void mousePressed(MouseEvent m)
{
l1.setText("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
l1.setText("Mouse Clicked");
}
}
public class MouseEvents
{
public static void main(String[] args)
{
MouseEvent a=new MouseEvent();
}
}
OR
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame
{
TextField t,t1;
Label l,l1;
int x,y;
Panel p;
MyFrame(String title)
{
super(title);
setLayout(new FlowLayout());
p=new Panel();
p.setLayout(new GridLayout(2,2,5,5));
t=new TextField(20);
l= new Label("Co-ordinates of clicking");
l1= new Label("Co-ordinates of movement");
t1=new TextField(20);
p.add(l);
p.add(t);
p.add(l1);
p.add(t1);
add(p);
addMouseListener(new MyClick());
addMouseMotionListener(new MyMove());
setSize(500,500);
setVisible(true);
}
class MyClick extends MouseAdapter
{
public void mouseClicked(MouseEvent me)
{
x=me.getX();
y=me.getY();
t.setText("X="+x+" Y="+y);
}
}
class MyMove extends MouseMotionAdapter
{
public void mouseMoved(MouseEvent me)
{
x=me.getX();
y=me.getY();
t1.setText("X="+ x +" Y="+y);
}
}
}
class mouseclick
{
public static void main(String args[])
{
MyFrame f = new MyFrame("Mouse screen");
}
}
Define a class MyNumber having one private int data member. Write a default constructor to initialize it to 0 and another constructor to initialize it to a value (Use this). Write methods isNegative, isPositive, isZero, isOdd, isEven. Create an object in main.Use command line arguments to pass a value to the Object.
public class Ass1_SetB_b
{
private int x;
Ass1_SetB_b()
{
x = 0;
}
Ass1_SetB_b(int x)
{
this.x = x;
}
void isZero()
{
if(x==0)
System.out.println("The number is Zero");
}
void isPositive()
{
if(x>0)
System.out.println("The number is Positive");
}
void isNegative()
{
if(x<0)
System.out.println("The number is Negative");
}
void isOdd()
{
if(x%2!=0)
System.out.println("The number is Odd");
}
void isEven()
{
if(x%2==0)
System.out.println("The number is Even");
}
public static void main(String [] args) throws ArrayIndexOutOfBoundsException
{
int num=Integer.parseInt(args[0]);
Ass1_SetB_b obj=new Ass1_SetB_b(num);
obj.isNegative();
obj.isPositive();
obj.isEven();
obj.isOdd();
obj.isZero();
}
}
Write a simple currency converter, as shown in the figure. User can enter the amount of "Singapore Dollars", "US Dollars", or "Euros", in floating-point number. The converted values shall be displayed to 2 decimal places. Assume that 1 USD = 1.41 SGD, 1 USD = 0.92 Euro, 1 SGD = 0.65 Euro.
Create an abstract class 'Bank' with an abstract method 'getBalance'. Rs.100, Rs.150 and Rs.200 are deposited in banks A, B and C respectively. 'BankA', 'BankB' and 'BankC' are subclasses of class 'Bank', each having a method named 'getBalance'. Call this method by creating an object of each of the three classes.
/*
Create an abstract class 'bank' with an abstract method 'getBalance'.
Rs.100, Rs.150 and Rs.200 are deposited in banks A, B and C respectively.
'bankA', 'bankB' and 'bankC' are subclasses of class bank', each having a method named 'getBalance'.
Call this method by creating an object of each of the three classes.
*/
abstract class bank
{
abstract void getBalance();
}
class A extends bank
{
int rs100;
A()
{
rs100 = 100;
}
void getBalance()
{
System.out.println("Deposited Rupees -bank A "+rs100);
}
}
class B extends bank
{
int rs200;
B()
{
rs200 = 200;
}
void getBalance()
{
System.out.println("Deposited Rupees -bank A "+rs200);
}
}
class C extends bank
{
int rs300;
C()
{
rs300 = 300;
}
void getBalance()
{
System.out.println("Deposited Rupees -bank A "+rs300);
}
}
public class AbstractBank {
public static void main(String[] args) {
A a1 = new A();
a1.getBalance();
B b1 = new B();
b1.getBalance();
C c1 = new C();
c1.getBalance();
}
}
/* OUTPUT:
PS C:\Users\swapniljamble\IdeaProjects\MyProject\src> javac AbstractBank.java
PS C:\Users\swapniljamble\IdeaProjects\MyProject\src> java AbstractBank
Deposited Rupees -bank A 100
Deposited Rupees -bank A 200
Deposited Rupees -bank A 300
*/
Define a Item class (item_number, item_name, item_price). Define a default and parameterized constructor. Keep a count of objects created. Create objects using parameterized constructor and display the object count after each object is created.(Use static member and method). Also display the contents of each object
/*
Define a Item class (item_number, item_name, item_price). Define
a default and parameterized constructor. Keep a count of objects created.
Create objects using parameterized constructor and display the object
count after each object is created.(Use static member and method). Also
display the contents of each object
*/
import java.util.Scanner;
public class ItemClass {
int item_number;
String item_name;
int item_price;
static int numberofobjects=0;
ItemClass()
{
item_number=0;
item_name="";
item_price=0;
}
ItemClass(int item_number,String item_name,int item_price)
{
this.item_number=item_number;
this.item_name=item_name;
this.item_price=item_price;
numberofobjects++;
}
public void display(){
System.out.println("ItemClass item_number :"+item_number);
System.out.println("ItemClass item_name: "+item_name);
System.out.println("ItemClass price: "+item_price);
}
public static void main(String[] args){
int n=0;
Scanner sc=new Scanner(System.in);
System.out.print("How many Items you want to enter :");
n=sc.nextInt();
ItemClass[] ob = new ItemClass[n];
for(int i=0;i<n;i++)
{
sc= new Scanner(System.in);
System.out.println("Enter item_number of item "+(i+1)+" :");
int item_number=sc.nextInt();
System.out.println("Enter item_name of item "+(i+1)+" :");
String item_name= sc.next();
System.out.println("Enter Item price of item "+(i+1)+" :");
int item_price=sc.nextInt();
ob[i] = new ItemClass(item_number,item_name,item_price);
System.out.println("\nNumber of Objects : "+numberofobjects);
}
for(int i=0;i<n;i++)
{
ob[i].display();
}
}
}
/*
PS C:\Users\swapniljamble\IdeaProjects\MyProject\src> javac ItemClass.java
PS C:\Users\swapniljamble\IdeaProjects\MyProject\src> java ItemClass
How many Items you want to enter :3
Enter item_number of item 1 :
1
Enter item_name of item 1 :
soap
Enter Item price of item 1 :
10
Number of Objects : 1
Enter item_number of item 2 :
2
Enter item_name of item 2 :
pen
Enter Item price of item 2 :
5
Number of Objects : 2
Enter item_number of item 3 :
3
Enter item_name of item 3 :
laptop
Enter Item price of item 3 :
50000
Number of Objects : 3
ItemClass item_number :1
ItemClass item_name: soap
ItemClass price: 10
ItemClass item_number :2
ItemClass item_name: pen
ItemClass price: 5
ItemClass item_number :3
ItemClass item_name: laptop
ItemClass price: 50000
*/
Slip25
/*
java program Create Class student(rollno,name,class,per) to read Student information from console
and display them using BufferedReader
*/
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class student
{
int rollno;
String name,std;
float per;
student(int rollno,String name, String std, float per)
{
this.rollno = rollno;
this.name = name;
this.std = std;
this.per = per;
}
void display()
{
System.out.println("Rollno :"+rollno+"\t Name :"+name+"\tclass :"+std+" \tpercentage :"+per);
}
}
public class ConsoleRead {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int rollno = Integer.parseInt(args[0]);
String name = args[1];
String std = args[2];
float per = Float.parseFloat(args[3]);
student obj = new student(rollno,name,std,per);
obj.display();
}
}
/*
OUTPUT:
PS C:\Users\swapniljamble\IdeaProjects\MyProject\src> javac ConsoleRead.java
PS C:\Users\swapniljamble\IdeaProjects\MyProject\src> java ConsoleRead 50 swapnil tybcs 88
Rollno :50 Name :swapnil class :tybcs percentage :88.0
*/
Create the following GUI screen using appropriate layout manager. Accept the name, class, hobbies from the user and display the selected options in a textbox

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Swing2 extends JFrame implements ActionListener
{
JLabel l1,l2,l3;
JButton b;
JRadioButton r1,r2,r3;
JCheckBox c1,c2,c3;
JTextField t1,t2;
ButtonGroup b1;
JPanel p1,p2;
static int cnt;
private StringBuffer s1=new StringBuffer();
Swing2()
{
b1=new ButtonGroup();
p1=new JPanel();
p2=new JPanel();
b=new JButton("Clear");
b.addActionListener(this);
r1=new JRadioButton("FY");
r2=new JRadioButton("SY");
r3=new JRadioButton("TY");
b1.add(r1);
b1.add(r2);
b1.add(r3);
r1.addActionListener(this);
r2.addActionListener(this);
r3.addActionListener(this);
c1=new JCheckBox("Music");
c2=new JCheckBox("Dance");
c3=new JCheckBox("Sports");
c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);
l1=new JLabel("Your Name");
l2=new JLabel("Your Class");
l3=new JLabel("Your Hobbies");
t1=new JTextField(20);
t2=new JTextField(30);
p1.setLayout(new GridLayout(5,2));
p1.add(l1);p1.add(t1);
p1.add(l2);p1.add(l3);
p1.add(r1);p1.add(c1);
p1.add(r2); p1.add(c2);
p1.add(r3);p1.add(c3);
p2.setLayout(new FlowLayout());
p2.add(b);
p2.add(t2);
setLayout(new BorderLayout());
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.EAST);
setSize(400,200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==r1)
{
cnt++;
if(cnt==1)
{
String s =t1.getText();
s1.append("Name = ");
s1.append(s);
}
s1.append(" Class = FY");
}
else if(e.getSource()==r2)
{
cnt++;
if(cnt==1)
{
String s =t1.getText();
s1.append("Name = ");
s1.append(s);
}
s1.append(" Class = SY");
}
else if(e.getSource()==r3)
{
cnt++;
if(cnt==1)
{
String s =t1.getText();
s1.append("Name = ");
s1.append(s);
}
s1.append(" Class = TY");
}
else if(e.getSource()==c1)
{
s1.append(" Hobbies = Music");
}
else if(e.getSource()==c2)
{
s1.append(" Hobbies = Dance");
}
else if(e.getSource()==c3)
{
s1.append(" Hobbies = Sports");
}
t2.setText(new String(s1));
// t2.setText(s2);
if(e.getSource()==b)
{
t2.setText(" ");
t1.setText(" ");
}
}
public static void main(String arg[])
{
Swing2 s=new Swing2();
}
}
s
s
❤️
ReplyDelete