Practical Slips Solution

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

File: /home/mangesh/PracticalSlipsSolution.

java
________________________________________________________________________________

import java.util.*;
import java.io.*;

// Slip 1- Que.1

-Write a Program to print all Prime numbers in an array of ‘n’ elements.


(use command line arguments)
==>

class PrimeNumbers
{
public static void main(String []args)
{
int []array=new int[args.length];
System.out.println("Your Entered Array is:");
for(int i=0; i<args.length; i++)
{
array[i]=Integer.parseInt(args[i]);
System.out.print(array[i]+" ");
}
System.out.println();
System.out.println("Prime Numbers from Array:");
for(int i=0; i<args.length; i++)
{
int flag=0;
for(int j=2; j<=array[i]/2; j++)
if(array[i]%j==0)
{
flag=1;
break;
}
if(flag==0)
System.out.print(array[i]+" ");
}
}
}

// Slip 1- Que.2

-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.
==>

abstract class Staff


{
protected int id;
protected String name;
public Staff(int id, String name)
{
this.id= id;
this.name=name;
}
abstract public void displayDetails(int i);
}
class OfficeStaff extends Staff
{
String dept;
public OfficeStaff(int id, String name, String dept)
{
super(id,name);
this.dept=dept;
}
public void displayDetails(int i)
{
System.out.println("\nDtails of Staff Members "+(i+1));
System.out.println(id+" "+name+" "+dept);
}
}
class Slip1Q2
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter How Many Staff: ");
int n=sc.nextInt();
OfficeStaff []os=new OfficeStaff[n];
System.out.println("Enter the Details of Staff member:");
for(int i=0; i<n; i++)
{
System.out.println("\nEnter Id, Name, Department of member "+
(i+1)+":");
int id=sc.nextInt();
String name=sc.next();
String dept=sc.next();
os[i]=new OfficeStaff(id, name, dept);
}
for(int i=0; i<n; i++)
os[i].displayDetails(i);
}
}

// Slip 2- Que.1

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

class BodyMassIndex
{
public static void main(String args[])
{
if(args.length!=4)
{
System.out.println("Please Enter First name, Last Name,
Weight, Height as Commandline arguments");
return;
}
String fname=args[0];
String lname=args[1];
double wt=Double.parseDouble(args[2]);
double ht=Double.parseDouble(args[3]);

double BMI=wt/(ht*ht);

System.out.println("Name: "+fname+" "+lname);


System.out.println("Weight: "+wt+" KG");
System.out.println("Height: "+ht+" meters");
System.out.println("BMI: "+BMI);
}
}

// Slip 2- Que.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.
==>

class CricketPlayer
{
String name;
int no_of_innings, no_of_times_notout, totalruns;
double 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;
}
public static void avg(CricketPlayer cp[])
{
for(int i=0; i<cp.length; i++)
cp[i].bat_avg=cp[i].totalruns/(cp[i].no_of_innings -
cp[i].no_of_times_notout);
}
public static void sort(CricketPlayer cp[])
{
for(int i=0; i<cp.length-1; i++)
for(int j=0; j<cp.length-i-1; j++)
if(cp[j].bat_avg < cp[j+1].bat_avg)
{
CricketPlayer temp=cp[j];
cp[j]=cp[j+1];
cp[j+1]=temp;
}
}
}

class Slip2Q2
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("How Many Players: ");
int n=sc.nextInt();
CricketPlayer cp[]=new CricketPlayer[n];
System.out.println("Enter the Name, no_of_innings,
no_of_times_notout, totalruns of "+n+" Players");
for(int i=0; i<n; i++)
{
String name=sc.next();
int no_of_innings=sc.nextInt();
int no_of_times_notout=sc.nextInt();
int totalruns=sc.nextInt();
cp[i]=new
CricketPlayer(name,no_of_innings,no_of_times_notout,totalruns);
}
CricketPlayer.avg(cp);
CricketPlayer.sort(cp);
System.out.println("List of Cricket Player sorted according to
Bating Avrage");

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


System.out.println((i+1)+") name: "+cp[i].name+" Innings:
"+cp[i].no_of_innings+" Notout: "+cp[i].no_of_times_notout+" TotalRuns:
"+cp[i].totalruns+" Bat_Avg: "+cp[i].bat_avg);
}
}

// Slip 3- Que.1

-Write a program to accept ‘n’ name of cities from the user and sort them in
ascending
order.
==>

class Slip3Q1
{
public static void main(String args[])
{
Scanner sc =new Scanner (System.in);
System.out.println("How Many Cities:");
int n=sc.nextInt();
System.out.println("Enter names of Cities:");
String names[]=new String[n];
for (int i=0; i<n; i++)
names[i]=sc.next();
Arrays.sort(names);
System.out.println("Cities in Ascending order: ");
for(int i=0; i<n; i++)
System.out.println(names[i]+" ");
}
}

// Slip 3- Que.2

-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.
==>

class Patient
{
String name;
int age, HRCT_report;
double oxy_level;

public static void main(String []args)


{
Scanner sc=new Scanner(System.in);
Patient p=new Patient();
System.out.println("Enter the Patient name: ");
p.name=sc.next();
System.out.println("Patient Age: ");
p.age=sc.nextInt();
System.out.println("Oxygen Level: ");
p.oxy_level=sc.nextDouble();
System.out.println("HRCT Score: ");
p.HRCT_report=sc.nextInt();
if(p.oxy_level < 95 && p.HRCT_report > 10)
{
try
{
throw new Exception("Patient is COVID +ve, need to
Hospitalized");
}
catch(Exception e)
{
System.out.println(e);
}
}
else
{
System.out.println("Patient Name: "+p.name);
System.out.println("Patient Age: "+p.age);
System.out.println("Oxygen Level: "+p.oxy_level+"%");
System.out.println("HRCT Score: "+p.HRCT_report);
}
}
}

// Slip 5- Que.1

-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.
==>

class Continent
{
String cont;
public void accept2()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Continent:");
cont=sc.next();
}
}
class Country extends Continent
{
String country;
public void accept1()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Country:");
country=sc.next();
accept2();
}
}
class State extends Country
{
String state,place;
State(String place)
{
this.place=place;
}
public void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter State:");
state=sc.next();
accept1();

}
public void display()
{
System.out.println("\nPlace: "+place);
System.out.println("State: "+state);
System.out.println("Country: "+country);
System.out.println("Continent: "+cont);
}
}

class Slip5Q1
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Place name in State: ");
String place=sc.next();
State s=new State(place);
s.accept();
s.display();
}
}

// Slip 5- Que.2

-Write a menu driven program to perform the following operations on


multidimensional array matrices :
1)Addition
2)Multiplication
3)Exit
==>

class MenuDriven
{
public void acceptMatrix(int a[][], int r, int c)
{
Scanner sc=new Scanner(System.in);
for(int i=0; i<r; i++)
for(int j=0; j<c; j++)
a[i][j]=sc.nextInt();
}

public void display(int a[][])


{
for(int i=0; i<a.length; i++)
{
for(int j=0; j<a[0].length; j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
}

public void add(int a[][],int b[][],int res[][], int r,int c)


{
for(int i=0; i<r; i++)
for(int j=0; j<c; j++)
res[i][j]=a[i][j]+b[i][j];
}

public void multiply(int a[][],int b[][],int res[][],int r1,int c1,int r2,


int c2)
{
for(int k=0; k<r1; k++)
for(int i=0; i<c2; i++)
{
res[k][i]=0;
for(int j=0; j<c1; j++)
res[k][i] += a[k][j]*b[j][i];
}
}

public static void main(String []args)


{
Scanner sc=new Scanner(System.in);
PracticalSlips mat=new PracticalSlips();
int ch;
int a[][];
int b[][];
int res[][];
do{
System.out.println("\n1.Addition\n2.Multiplication\n3.Exit");
System.out.print("Enter any Choice: ");
ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter the Size of Matrices for
Addition:");
int r=sc.nextInt();
int c=sc.nextInt();
a=new int[r][c];
b=new int[r][c];
System.out.println("Enter the 1st Mstrix:");
mat.acceptMatrix(a,r,c);
System.out.println("\nEnter the 2nd Matrix:");
mat.acceptMatrix(b,r,c);
res=new int[r][c];
mat.add(a,b,res,r,c);
System.out.println("\nAfter Addition=>");
mat.display(res);
break;
case 2:
System.out.println("Enter the size of 1st matrix
for multiply:");
int r1=sc.nextInt();
int c1=sc.nextInt();
System.out.println("Enter the size of 2nd matrix
for multiply:");
int r2=sc.nextInt();
int c2=sc.nextInt();
if(c1!=r2)
{
System.out.println("Multiplication can't
Possible\n");
continue;
}
a=new int[r1][c1];
b=new int[r2][c2];
System.out.println("\nEnter 1st matrix of size
"+r1+"X"+c1);
mat.acceptMatrix(a,r1,c1);
System.out.println("\nEnter 2nd matrix of size
"+r2+"X"+c2);
mat.acceptMatrix(b,r2,c2);
res=new int[r1][c2];
mat.multiply(a,b,res,r1,c1,r2,c2);
System.out.println("After Multiplication =>");
mat.display(res);
break;
case 3:
System.exit(0);
}
}while(ch!=0);
}
}

// Slip 6- Que.1

-Write a program to display the Employee(Empid, Empname, Empdesignation, Empsal)


information using toString().
==>

class Slip6Q1
{
int empid;
String ename,dest;
double sal;
// Override the toString() method of Object class by own implemantation.
public String toString()
{
return ("Employee Id: "+empid+"\n"+"Employee Name: "+ename+"\
n"+"Destination: "+dest+"\n"+"Salary: "+sal);
}

public static void main(String []args)


{
Scanner sc=new Scanner(System.in);
PracticalSlips e = new PracticalSlips();
System.out.println("Enter Details of Employee:");
System.out.println("Employee Id, Name, Destination, Salary");
e.empid=sc.nextInt();
e.ename=sc.next();
e.dest=sc.next();
e.sal=sc.nextDouble();
System.out.println(e.toString());
}
}

// Slip 6- Que.2

-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.
==>

abstract class Order


{
int id;
String description;
public abstract void accept();
public abstract void display();
}
class PurchaseOrder extends Order
{
String cust_name;
public void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Purchase Id, purchase Description,
Customer name");
id=sc.nextInt();
description=sc.next();
cust_name=sc.next();
}

public void display()


{
System.out.println("Purchase Id: "+id+"\npurchase Description:
"+description+"\nCustomer name: "+cust_name+"\n\n");
}
}
class SaleOrder extends Order
{
String vendor_name;
public void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Sale Id, Sale Description, Vendor name");
id=sc.nextInt();
description=sc.next();
vendor_name=sc.next();
}
public void display()
{
System.out.println("Sale Id: "+id+"\nSale Description:
"+description+"\nVendor name: "+vendor_name+"\n\n");
}
}

class Slip6Q2
{
public static void main(String []args)
{
PurchaseOrder []po=new PurchaseOrder [3];
//accepting details of Purchase orders
System.out.println("\nEnter details of 3 Purchases: ");
for(int i=0; i<3; i++)
{
System.out.println("\nDetails for Purchase "+(i+1));
po[i]=new PurchaseOrder();
po[i].accept();
}

SaleOrder []so=new SaleOrder [3];


//accepting details of Sale orders
System.out.println("\nEnter details of 3 Sales: ");
for(int i=0; i<3; i++)
{
System.out.println("\nDetails for Sale "+(i+1));
so[i]=new SaleOrder();
so[i].accept();
}

//Displaying Details of Purchase order


System.out.println("\nYour Entered details of 3 Purchases are: ");
for(int i=0; i<3; i++)
{
System.out.println((i+1)")=>");
po[i].display();
}

//Displaying Details of Sale order


System.out.println("\nYour Entered details of 3 Sales are: ");
for(int i=0; i<3; i++)
{
System.out.println((i+1)")=>");
so[i].display();
}
}
}

// Slip 7- Que.1

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

class Bank
{
static double balance=0;
public void deposite()
{
Scanner sc=new Scanner(System.in);
System.out.println("\nEnter Amount to Credit:");
double creditable_amount = sc.nextDouble();
balance += creditable_amount;
System.out.println(creditable_amount+" has been Credited");
System.out.println("Current Balance: "+balance);
}
public void withdraw()
{
Scanner sc=new Scanner(System.in);
System.out.println("\nEnter Amount to be Withdraw:");
double withdrawal_amount=sc.nextDouble();
if(balance < withdrawal_amount)
System.out.println("Insufficiant Balance");
else
{
balance = balance-withdrawal_amount;
System.out.println(withdrawal_amount+" has been Debited");
System.out.println("Current Balance: "+balance);
}
}
public void inquiry()
{
System.out.println("\nTotal Balance: "+balance);
}

}
class Slip7Q1
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
Bank b=new Bank();
int ch;
do
{
System.out.println("\n1.Deposite\n2.Withdraw\n3.Balance
Inquiry\n4.Exit");
System.out.println("Enter Choice:");
ch=sc.nextInt();
switch(ch)
{
case 1: b.deposite();
break;

case 2: b.withdraw();
break;

case 3: b.inquiry();
break;

case 4: System.exit(0);
}
}while(ch!=0);
System.out.println("---Thank You---");
}
}

// Slip 7- Que.2 ----------

// Slip 8- Que.1

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

class Sphere
{
final float PI=3.14f;
public void calculateVolume(double r)
{
double vol=(double)4/3*PI*(r*r*r);
System.out.println("\nVolume of Sphere whose Radius is => "+vol);
}
public void calculateSurfaceArea(double r)
{
double surface_area=(double)4*PI*(r*r);
System.out.println("\nSurface Area of Sphere is => "+surface_area+"\
n");
}
}
class PracticalSlips
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
Sphere sp=new Sphere();
System.out.println("Enter the Radius of Sphere: ");
double r=sc.nextDouble();
sp.calculateVolume(r);
sp.calculateSurfaceArea(r);
}
}

// Slip 8- Que.2 -------------

// Slip 9- Que.1

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

class Clock
{
int hrs,min,sec;
Clock(int h, int m, int s)
{
hrs=h;
min=m;
sec=s;
}

public int checkTimeValidity()


{
if(hrs>0 && hrs<24)
if(min>=0 && min<60)
if(sec>=0 && sec<60)
{
System.out.println("Time is Valid..");
return 1;
}
else
System.out.println("Time is Invalid..");
return 0;
}

public void setMode()


{
if(hrs>12)
{
hrs-=12;
System.out.println("Time: "+hrs+":"+min+":"+sec+" PM");
}
else
System.out.println("Time: "+hrs+":"+min+":"+sec+" AM");
}
}
class Slip9Q1
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the time in a form--> hh mm ss");
int hh=sc.nextInt();
int mm=sc.nextInt();
int ss=sc.nextInt();
Clock c=new Clock(hh,mm,ss);
if(c.checkTimeValidity()==1)
c.setMode();
}
}

// Slip 9- Que.2

-Write a program to using marker interface create a class Product (product_id,


product_name,
product_cost, product_quantity) default and parameterized constructor. Create
objects of class
product and display the contents of each object and Also display the object
count.
==>

interface MarkerInterface
{ }
class Product implements MarkerInterface
{
int prod_id;
String prod_name;
double prod_cost;
int prod_qty;
static int count=0;
public Product()
{count++;}
public Product(int prod_id, String prod_name, double prod_cost, int
prod_qty)
{
this.prod_id=prod_id;
this.prod_name=prod_name;
this.prod_cost=prod_cost;
this.prod_qty=prod_qty;
count++;
}
public void display()
{
System.out.println("\nProduct id: "+prod_id+"\nProduct Name:
"+prod_name+"\nProduct cost: "+prod_cost+"\nQuantity: "+prod_qty);
}
public static void objectCount()
{
System.out.println("\nObject Count: "+count);
}
}

class Slip9Q2
{
public static void main(String []args)
{
Scanner sc=new Scanner (System.in);
Product p1=new Product(1, "Phone", 45000, 3);
Product p2=new Product(2, "Laptop", 50000, 2);
Product p3=new Product(3, "Hard Disk", 1500, 6);
Product p4=new Product(4, "PD", 500, 10);

p1.display();
p2.display();
p3.display();
p4.display();

Product.objectCount();
}
}
// Slip 10- Que.1

-Write a program to find the cube of given number using functional interface.
==>

interface FunInterface
{ void cube(int x);}

class FindCube
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a Number to Calculate cube: ");
int n=sc.nextInt();

FunInterface f=(int x)->System.out.println("Cube of "+n+"= "+x*x*x);

f.cube(n);
}
}

// Slip 10- Que.2

-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;
public class StudentInfo
{
int rollno;
String className;
double percentage;
public StudentInfo(int rollno, String className, double percentage)
{
this.rollno=rollno;
this.className=className;
this.percentage=percentage;
}
public void displayInfo()
{
System.out.println("Roll no.: "+"\nClass: "+className+"\nPercentage:
"+percentage);
}
}
public class StudentPer
{
public double percentage(int marks[])
{
int total=0;
for(int i=0; i<marks.length; i++)
total+=marks[i];
return (double)total/marks.length;
}
}

import student.*;
class Slip10Q2
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Student Details: ");
System.out.println("Enter Roll no.");
int rollno=sc.nextInt();
System.out.println("Enter Class ");
String className=sc.next();
System.out.println("Enter Marks of 6 Subject ");
int marks[]=new int[6];
for(int i=0; i<6; i++)
marks[i]=sc.nextInt();
StudentPer sp=new StudentPer();
double per=sp.percentage(marks);
StudentInfo si=new StudentInfo(rollno,className,per);
si.displayInfo();
}
}

// Slip 11- Que.1

-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.
==>

interface Operation
{
final float PI=3.142f;
public double volume();
}
class Cylinder implements Operation
{
float radius,height;
public Cylinder(float r, float h)
{
radius=r;
height=h;
}
public double volume()
{
double volume=PI*(radius*radius)*height;
return volume;
}
}

class Slip11Q1
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("\nEnter the Radius:");
float r=sc.nextFloat();
System.out.println("Enter the Height:");
float h=sc.nextFloat();
Cylinder c = new Cylinder(r, h);
System.out.println("\nVolume of Cylinder: "+c.volume());
}
}
// Slip 11- Que.2

-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.
==>

class Slip11Q2
{
public static void main(String []args)
{
Scanner sc=new Scanner (System.in);
System.out.println("Enter the Details for Login:");
System.out.println("Username:");
String usn=sc.nextLine();
System.out.println("Password:");
String pwd=sc.nextLine();
try
{
if(usn.equals(pwd))
System.out.println("Login Successfully..");
else
throw new Exception("Invalid Password..");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

// Slip 12- Que.1

-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.
==>

class College
{
int c_no;
String c_name, c_addr;

public void acceptCollege()


{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the College no:");
c_no=sc.nextInt();
System.out.println("Enter the Collage name:");
c_name=sc.nextLine();
System.out.println("Enter the College Address:");
c_addr=sc.nextLine();
}

}
class Department extends College
{
int d_no;
String d_name;
Scanner sc=new Scanner(System.in);
public void acceptDepartment()
{
super.acceptCollege();
Scanner sc=new Scanner(System.in);
System.out.println("Enter Department no:");
d_no=sc.nextInt();
System.out.println("Enter Department name:");
d_name=sc.nextLine();
}
public void desplayDetails()
{
System.out.println("College no: "+c_no+"\nCollage Name: "+c_name+"\
nAddress: "+c_addr);
System.out.println("Department no: "+d_no+"\nDepartment
name:"+d_name);
}
}

class Slip12Q1
{
public static void main(String []args)
{
Department dptm= new Department();
dptm.acceptDepartment();
System.out.println("\nDetails:-->>");
dptm.desplayDetails();
}
}

// Slip 12- Que.2 -----------

// Slip 13- Que.1

-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.
==>

class Slip13Q1
{
public static void main(String []args) throws IOException
{
File f=new File("sample1.txt");
FileInputStream fis=new FileInputStream(f);
InputStreamReader input= new InputStreamReader(fis);
BufferedReader br= new BufferedReader(input);

String line;
int charCount=0;
int wordCount=0;
int lineCount=0;
while((line=br.readLine())!=null)
{
String words[]=line.split("\\s+");
charCount += line.length();
wordCount += words.length;
lineCount++;
}
System.out.println("Charators: "+charCount);
System.out.println("Words: "+wordCount);
System.out.println("Lines: "+lineCount);
}
}

// Slip 13- Que.2

-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;
class Slip13Q2
{
public static void main(String []args)
{
Date date=new Date();
SimpleDateFormat format1=new SimpleDateFormat("dd/MM/yyyy");
System.out.println("Current Date: "+format1.format(date));

SimpleDateFormat format2=new SimpleDateFormat("MM-dd-yyyy");


System.out.println("Current Date: "+format2.format(date));

SimpleDateFormat format3=new SimpleDateFormat("MMMM dd yyyy");


System.out.println("Current Date: "+format3.format(date));

SimpleDateFormat format4=new SimpleDateFormat("E MMMM dd HH:mm:ss z


yyyy");
System.out.println("Current Date: "+format4.format(date));

SimpleDateFormat format5=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss a


Z");
System.out.println("Current Date: "+format5.format(date));
}
}

// Slip 14- Que.1

-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).
==>

class Slip14Q1
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number:");
int num=sc.nextInt();
try
{
int flag=0;
if(num == 0)
throw new Exception("Number is Zero");
else
{
for(int i=2; i<=num/2; i++)
if(num % i==0)
{
flag=1;
break;
}
if(flag==0)
System.out.println(num+" is Prime");
else
System.out.println(num+" is not Prime");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

// Slip 14- Que.2

-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.
==>

package sy;
import java.util.*;
public class SYMarks
{
int comp_total, math_total, elc_total;
public int accept1()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Total marks of Computer Science out of
200:");
comp_total=sc.nextInt();
System.out.println("Enter the total marks of Mathematics out of
200:");
math_total=sc.nextInt();
System.out.println("Enter the total marks of Electronics out of
200:");
elc_total=sc.nextInt();

return (comp_total + math_total + elc_total);


}
}

package ty;
import java.util.*;
public class TYMarks
{
int theory, practicals;
public int accept2()
{
Scanner sc =new Scanner(System.in);
System.out.println("Enter the Marks of Theory Exam out of 300: ");
theory=sc.nextInt();
System.out.println("Enter the Marks of Practical Exam out of 300:
");
practicals=sc.nextInt();

return (theory + practicals);


}
}

import sy.*;
import ty.*;
class Student
{
int rollno;
String name;
double percentage;
String grade;
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
SYMarks sym=new SYMarks();
TYMarks tym=new TYMarks();
System.out.println("How Many Student:");
int n=sc.nextInt();
Student s[]=new Student [n];
for(int i=0; i<n; i++)
{
s[i]=new Student();
System.out.println("\nEnter Details of Student "+(i+1));
System.out.println("Enter Roll no.:");
s[i].rollno=sc.nextInt();
System.out.println("Enter Name:");
s[i].name=sc.next();
int syTotal=sym.accept1();
int tyTotal=tym.accept2();
s[i].percentage= (double) (syTotal+tyTotal)/1200*100;
}

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


{
if(s[i].percentage >= 70)
s[i].grade="A";
else if(s[i].percentage >= 60)
s[i].grade="B";
else if(s[i].percentage >= 50)
s[i].grade="C";
else if(s[i].percentage >= 40)
s[i].grade="Pass";
else
s[i].grade="Fail";

System.out.println("\nRoll no: "+s[i].rollno+"\nName:


"+s[i].name+"\nPercentage: "+s[i].percentage+"\nGrade: "+s[i].grade);
}
}
}

// Slip 15- Que.1 -------------

-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.
// Slip 15- Que.2

-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
{
String cust_name;
long acc_no;
Account()
{ }

Account(String cust_name, long acc_no)


{
this.cust_name=cust_name;
this.acc_no=acc_no;
}
}

class SavingAccount extends Account


{
double saving_bal,min_bal;
}

class AccountDetail extends SavingAccount


{
double deposite_amt, Withdrawal_amt;

void displayDetails()
{
System.out.println("\nCustomer Name: "+cust_name+"\nAccount no:
"+acc_no+"\nSaving Bal:"+saving_bal+"\nMinimum Bal: "+min_bal);
System.out.println("Deposite Amount: "+deposite_amt+"\nWithdrawal
Amoumnt: "+Withdrawal_amt);
}
}

public class Slip15Q2


{
public static void main(String []args)
{
AccountDetail ad=new AccountDetail();
ad.cust_name="Golu";
ad.acc_no=4515667812l;
ad.saving_bal=10580.0;
ad.min_bal=500.0;
ad.deposite_amt=1000.0;
ad.Withdrawal_amt=2000.0;

ad.displayDetails();
}
}

// Slip 18- Que.1 ------------


// Slip 18- Que.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.
==>

class CricketPlayer
{
String name;
int no_of_innings, no_of_times_notout, totalruns;
double 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;
}
public static void avg(CricketPlayer cp[])
{
for(int i=0; i<cp.length; i++)
cp[i].bat_avg=cp[i].totalruns/(cp[i].no_of_innings -
cp[i].no_of_times_notout);
}
public static void sort(CricketPlayer cp[])
{
for(int i=0; i<cp.length-1; i++)
for(int j=0; j<cp.length-i-1; j++)
if(cp[j].bat_avg < cp[j+1].bat_avg)
{
CricketPlayer temp=cp[j];
cp[j]=cp[j+1];
cp[j+1]=temp;
}
}
}

class Slip18Q2
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("How Many Players: ");
int n=sc.nextInt();
CricketPlayer cp[]=new CricketPlayer[n];
System.out.println("Enter the Name, no_of_innings,
no_of_times_notout, totalruns of "+n+" Players");
for(int i=0; i<n; i++)
{
String name=sc.next();
int no_of_innings=sc.nextInt();
int no_of_times_notout=sc.nextInt();
int totalruns=sc.nextInt();
cp[i]=new
CricketPlayer(name,no_of_innings,no_of_times_notout,totalruns);
}
CricketPlayer.avg(cp);
CricketPlayer.sort(cp);
System.out.println("List of Cricket Player sorted according to
Bating Avrage");

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


System.out.println((i+1)+") name: "+cp[i].name+" Innings:
"+cp[i].no_of_innings+" Notout: "+cp[i].no_of_times_notout+" TotalRuns:
"+cp[i].totalruns+" Bat_Avg: "+cp[i].bat_avg);
}
}

// Slip 20- Que.1

-Write a Program to illustrate multilevel Inheritance such that country is


inherited from
continent. State is inherited from country. Display the place, state, country
and continent.
==>

class Continent
{
String cont;
public void accept2()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Continent:");
cont=sc.next();
}
}
class Country extends Continent
{
String country;
public void accept1()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Country:");
country=sc.next();
accept2();
}
}
class State extends Country
{
String state,place;
State(String place)
{
this.place=place;
}
public void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter State:");
state=sc.next();
accept1();

}
public void display()
{
System.out.println("\nPlace: "+place);
System.out.println("State: "+state);
System.out.println("Country: "+country);
System.out.println("Continent: "+cont);
}
}
class Slip20Q1
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Place name in State: ");
String place=sc.next();
State s=new State(place);
s.accept();
s.display();
}
}

// Slip 20- Que.2

-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;
public class Addition
{
public int add(int a, int b)
{
return a+b;
}

public float subtract(float a, float b)


{
return a-b;
}
}

package operation;
public class Maximum
{
public int max(int a, int b)
{
if(a>b)
return a;
else if(b>a)
return b;
else
return 0;
}
}

import operation.*;
class Slip20Q2
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("\nEnter Two Integers for Addition and finding
Maximum of them.");
int a=sc.nextInt();
int b=sc.nextInt();
System.out.println("Enter Two floating point numbers for
Subtraction.");
float x=sc.nextFloat();
float y=sc.nextFloat();

Addition ad=new Addition();


System.out.println("\nAddition: "+a+"+"+b+"= "+ad.add(a,b));

Maximum m=new Maximum();


System.out.println("Maximun from "+a+" & "+b+": "+m.max(a,b));

System.out.println("Subtraction: "+x+"-"+y+"= "+ad.subtract(x,y));


}
}

// Slip 21- Que.1

-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.
==>

class MyDate
{
int day, month;
long year;
MyDate(int day, int month, long year)
{
this.day=day;
this.month=month;
this.year=year;
}

public static boolean isValidDate(int d, int m, long y)


{
if(m>=1 && m<=12)
{
if((d>=1 && d<=31)&&(m==1||m==3||m==5||m==7||m==8||m==10||
m==12))
return true;
else if((d>=1 && d<=30)&&(m==4||m==6||m==9||m==11))
return true;
else if(d>=1 && d<=28)
return true;
else
{
if((d>=1 && d<=28)&&(m==2))
if(y%4==0 && y%100!=0 || y%400==0)
return true;
}
}
return false;
}
}
class InvalidDateException extends Exception
{
public InvalidDateException(String msg)
{
super(msg);
}
}
class Slip21Q1
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("\nEnter Date in form - dd mm yyyy");
int dd=sc.nextInt();
int mm=sc.nextInt();
long yyyy=sc.nextLong();
try
{
if(!MyDate.isValidDate(dd,mm,yyyy))
throw new InvalidDateException("Invalid Date..");
else
{
MyDate md=new MyDate(dd,mm,yyyy);
System.out.println("Date:
"+md.day+"/"+md.month+"/"+md.year+"\nThis is valid Date");
}
}
catch(InvalidDateException e)
{
System.out.println(e);
}
}
}

// Slip 21- Que.2

-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 Employee
{
int id;
String name,dept;
double salary;
static int count;
Employee()
{ }
public Employee(int id, String name, String dept, double salary)
{
this.id=id;
this.name=name;
this.dept=dept;
this.salary=salary;
}
public static void display(Employee []emp)
{
System.out.println("\nEmployees Details:");
for(int =0; i<emp.length; i++)
{
System.out.println("Object count: "+count++);
System.out.println("Employee Id:"+emp[i].id+"\nEmployee
Name"+);
}
}

}
class Slip21Q2
{
public static void main(String []args)
{
Scanner sc=new Sacnner(System.in);
System.out.println("How many Employees?");
int n=sc.nextInt();
Employee emp[]=new Employee[n];
for(int i=0; i<n; i++)
{
System.out.println("Enter id, name, department, salary of
Employee "+(i+1);
int id=sc.nextInt();
String name=sc.next();
String dept=sc.next();
double sal=sc.nextDouble();
emp[i]=new Employee(id, name, dept,sal);
}
}
}

// Slip 29- Que.1

-Write a program to create a class


Customer(custno,custname,contactnumber,custaddr).
Write a method to search the customer name with given contact number and display
the
details.
==>

class Customer
{
int custno;
String custname;
long contactno;
String addr;
Customer(int custno, String custname, long contactno, String addr)
{
this.custno=custno;
this.custname=custname;
this.contactno=contactno;
this.addr=addr;
}
public boolean search(long contact)
{
if(contactno==contact)
{
System.out.println("\nmatched record:->");
System.out.println("Customer no: "+custno);
System.out.println("Customer Name: "+custname);
System.out.println("Contact number: "+contactno);
System.out.println("Address: "+addr);
return true;
}
else
return false;
}
}
class Slip29Q1
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("How many Customers: ");
int n=sc.nextInt();
Customer cust[]=new Customer[n];
for(int i=0; i<n; i++)
{
System.out.println("\nCustomer "+(i+1));
System.out.println("Enter Customer no.");
int custno=sc.nextInt();
System.out.println("Enter Customer name: ");
String name=sc.next();
System.out.println("Enter Contact no.");
long contactno=sc.nextLong();
System.out.println("Enter the Address");
String addr=sc.next();
cust[i]=new Customer(custno, name, contactno, addr);
}
System.out.println("\nEnter Contact no to Search Customer: ");
long contact=sc.nextLong();

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


if(!cust[i].search(contact))
{
System.out.println("match not found..");
return;
}
}
}

// Slip 29- Que.2

-Write a program to create a super class Vehicle having members Company and
price.
Derive two different classes LightMotorVehicle(mileage) and HeavyMotorVehicle
(capacity_in_tons). Accept the information for "n" vehicles and display the
information in
appropriate form. While taking data, ask user about the type of vehicle first.
==>

class Vehicle
{
String company;
double price;
public void accept()
{
Scanner sc=new Scanner (System.in);
System.out.println("\nEnter the Name of Vehicle Company: ");
company=sc.next();
System.out.println("Enter Price:");
price=sc.nextDouble();
}
public void display()
{
System.out.println("\nCompany Name:"+company);
System.out.println("Price: "+price);
}

}
class LightMotorVehicle extends Vehicle
{
int mileage;
public void accept()
{
Scanner sc=new Scanner (System.in);
super.accept();
System.out.println("Enter Mileage:");
mileage=sc.nextInt();
}
public void display()
{
super.display();
System.out.println("Mileage: "+mileage);
}
}
class HeavyMotorVehicle extends Vehicle
{
int capacity_in_tons;
public void accept()
{
Scanner sc=new Scanner (System.in);
super.accept();
System.out.println("Enter Capacity in Tons:");
capacity_in_tons=sc.nextInt();
}
public void display()
{
super.display();
System.out.println("Capacity: "+capacity_in_tons+" tons");
}
}
class Slip29Q2
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("No.of Vehicles");
int n=sc.nextInt();
Vehicle vehicle[]=new Vehicle [n];
for(int i=0; i<n; i++)
{
System.out.println("\nSelect Type of Vehicle");
System.out.println("1.Light Motor Vehicle\n2.Heavy Motor
Vehicle");
int type=sc.nextInt();
if(type==1)
{
vehicle[i]=new LightMotorVehicle();
vehicle[i].accept();
}
else if(type==2)
{
vehicle[i]=new HeavyMotorVehicle();
vehicle[i].accept();
}
else
{
System.out.println("Invalid Type of Vehicle");
i--;
continue;
}
}
System.out.println("\nVehicle details:->");
for(int i=0; i<n; i++)
{
if(vehicle[i] instanceof LightMotorVehicle)
{
System.out.println("Type: Light Motor Vehicle.");
vehicle[i].display();
}
else
{
System.out.println("Type: Heavy Motor Vehicle.");
vehicle[i].display();
}
}
}
}

You might also like