Professional Documents
Culture Documents
FINALFINALJAVA
FINALFINALJAVA
**************10MARKS
PROGRAM*************
***********************************************************************************
****************************************************************
Q1)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)
***********************************************************************************
****************************************************************
Q2) Write a program to accept ‘n’ name of cities from the user and sort them in
ascending order
Ans:
import java.util.Scanner;
class SortStrings
{
public static void main(String args[])
{
String temp;
Scanner SC = new Scanner(System.in);
//sorting strings
***********************************************************************************
****************************************************************
Q3) Write a Program to print all Prime numbers in an array of ‘n’ elements. (use
command line arguments)
import java.util.*;
class Prime{
public static void main(String args []){
int i,j=0;
boolean isPrime;
// int a[]=new int[args.length];
for(i=0;i<args.length;i++){
System.out.println(args[i]);
}
for(i=0;i<args.length;i++){
for(j=2;j<i;j++){
isPrime=true;
if(i%j==0){
isPrime=false;
break;
}
if(isPrime){
System.out.println(i+"are the prime number in array");
}
}
}
}
}
***********************************************************************************
****************************************************************
Q4) Write a program to print an array after changing the rows and columns of a
given two-dimensional array.
import java.util.*;
class TransArr{
public static void main(String args[]){
int r,c,i,j,t=0;
Scanner In=new Scanner(System.in);
System.out.print("Enter no of rows: ");
r=In.nextInt();
System.out.print("Enter no of column: ");
c=In.nextInt();
int a[][]=new int[r][c];
System.out.println("Enter "+r*c+" Elements: ");
for(i=0;i<r;i++){
for(j=0;j<c;j++){
a[i][j]=In.nextInt();
}
}
System.out.println("Array Representation: ");
for(i=0;i<r;i++){
for(j=0;j<c;j++){
System.out.print(a[i][j]+" ");
}
System.out.print("\n");
}
for(i=0;i<r;i++){
for(j=i+1;j<c;j++){
t=a[i][j];
a[i][j]=a[j][i];
a[j][i]=t;
}
}
}
}
}
***********************************************************************************
****************************************************************
Q5) 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.
Ans:
import java.util.Scanner;
class Continent{
public static final Scanner IN=new Scanner(System.in);
String cont;
void con(){
}
}
class Country extends Continent{
String cou;
void cont(){
}
}
class State extends Country{
String st,pl;
void sta(){
}
}
System.out.println("Continent is :"+cont);
System.out.println("Country is :"+cou);
System.out.println("State is :"+st);
System.out.println("Place is:"+pl);
}
}
class JavaPractical{
public static void main(String[] args) {
Display s=new Display();
s.con();
s.cont();
s.sta();
s.display();
}
}
***********************************************************************************
****************************************************************
class Employee
{
int id,salary;
String name;
String city;
Employee(int id,String name,int salary,String city)
{
this.id=id;
this.name=name;
this.salary=salary;
this.city=city;
}
public String toString()
{
return this.id+"\n"+this.name+"\n"+this.salary+"\n"+this.city;
}
public static void main(String args[])
{
Employee e1=new Employee(111,"rakesh",50000,"lucknow");
System.out.println("employee details"+e1);
}
}
***********************************************************************************
****************************************************************
Q7) 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 surfaceareaandvolume {
public static void main(String[] args)
{
double r = 5.0, surfacearea = 0.0, volume = 0.0;
surfacearea = 4 * 3.14 * (r * r);
volume = ((double)4 / 3) * 3.14 * (r * r * r);
***********************************************************************************
****************************************************************
Q8) Write a program to find the cube of given number using functional interface.
//cube
import java.util.Scanner;
public class Main
{
interface operation
{
public int cube();
}
static class number implements operation
{
int num;
number(int num)
{
this.num = num;
}
public int cube()
{
return (num * num * num);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter a number:");
int num = sc.nextInt();
number n1 = new number(num);
System.out.println("cube of " + num + " is " + n1.cube());
}
}
//number
import java.util.*;
public class Main
{
interface operation
{
public int cube();
}
static class number implements operation
{
int num;
number(int num)
{
this.num = num;
}
public int cube()
{
return (num * num * num);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter a number:");
int num = sc.nextInt();
number n1 = new number(num);
System.out.println("cube of " + num + " is " + n1.cube());
}
}
***********************************************************************************
****************************************************************
Q9) 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.io.*;
import java.util.*;
interface Operation
{
float pi = 3.14f;
void area(float r, float h);
void volume(float r, float h);
}
class Cylinder implements Operation
{
public void area(float r, float h)
{
System.out.print("\nArea of the cylinder is: " + (2 * r * pi * (r + h)));
}
public void volume(float r, float h)
{
System.out.println("\n\nVolume of the cylinder is: " + (pi * r * r * h) + "\n");
}
}
class main1
{
public static void main(String args[])
{
int r, h;
Cylinder ob = new Cylinder();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the radius of the cylinder: ");
r = sc.nextInt();
System.out.print("Enter the height of the cylinder: ");
h = sc.nextInt();
ob.area(r, h);
ob.volume(r, h);
}
}
***********************************************************************************
****************************************************************
Q10) 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.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
int lineCount = 0;
try
{
//Creating BufferedReader object
lineCount++;
currentLine = reader.readLine();
}
***********************************************************************************
****************************************************************
Q11) 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.*;
class zerono extends Exception
{
zerono(String msg)
{
super(msg);
}
}
class user1
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter number");
int n=Integer.parseInt(br.readLine());
if(n==0)
throw new zerono("number is zero");
else
{
int i=1,c=0;
while(i<=n)
{
if (n%i==0)
{
c++;
}
i++;
}
if(c==2)
System.out.println("given number is prime");
else
System.out.println("not prime");
}catch(zerono e)
{
System.out.println(e.getMessage());
}
}
}
***********************************************************************************
****************************************************************
import java.awt.*;
import java.awt.event.*;
public class border extends Frame
{
Button b1,b2,b3,b4;
TextField t1;
Frame f;
public border()
{
f=new Frame();
f.setSize(250,250);
f.setVisible(true);
f.setLayout(new BorderLayout());
b1=new Button("B1");
b2=new Button("B2");
b3=new Button("B3");
b4=new Button("B1");
t1=new TextField(30);
f.add("North",b1);
f.add("South",b2);
f.add("East",b3);
f.add("West",b4);
f.add("Center",t1);
}
}
***********************************************************************************
****************************************************************
***********************************************************************************
****************************************************************
***********************************************************************************
****************************************************************
***********************************************************************************
****************************************************************
***********************************************************************************
****************************************************************
***********************************************************************************
****************************************************************
***********************************************************************************
*********************************************************
***********************************************************************************
*********************************************************
***********************************************************************************
*********************************************************
***********************************************************************************
*********************************************************
*************20 MARKS PROGRAM*************
20 marks )
Q1) 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.io.*;
class cricket
{
static String name[]=new String[10],nm;
static int inngs[]=new int[10],notout[]=new int[10],runs[]=new int[10],r,in,n;
static double avg[]=new double[10],p;
}
}
}
}
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
cricket[] c=new cricket[10];
System.out.println("Enter the how many cricket player details you want: ");
n=Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
{
c[i]=new cricket();
c[i].get(i);
}
sort();
show();
}
}
***********************************************************************************
*******************************
Q2) 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
package SY;
import java.io.*;
public class SYMarks
c = Integer.parseInt(br.readLine());
m = Integer.parseInt(br.readLine());
e = Integer.parseInt(br.readLine());
}
//package TY
package TY;
import java.io.*;
public class TYMarks
{
public int t,p;
t = Integer.parseInt(br.readLine());
p=Integer.parseInt(br.readLine());
//MAIN PROGRAM
import SY.*;
import TY.*;
import java.io.*;
class Student
int rno;
String name;
rno = Integer.parseInt(br.readLine());
name = br.readLine();
s.get();
t.get();
System.out.println("Name: "+name);
s.put();
t.put();
int total,per;
System.out.println("Total is:"+total);
per = total/3;
System.out.println("Grade:A");
else
System.out.println("Grade:B");
else
if(per > 50 && per <= 60)
System.out.println("Grade:C");
else
if(per <= 40)
System.out.println("Grade:Fail");
class Slip20_1
int n = Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
s1[i].get();
s1[i].put();
s1[i].cal();
***********************************************************************************
****************************
Q3) 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.*;
public class main2
{
public static void main(String[] args)
{
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String strDate1 = formatter.format(date);
System.out.println("Current date is : " + strDate1);
formatter = new SimpleDateFormat("MM-dd-yyyy");
String strDate2 = formatter.format(date);
System.out.println("Current date is : " + strDate2);
formatter = new SimpleDateFormat("EEEE MMMM dd yyyy");
String strDate3 = formatter.format(date);
System.out.println("Current date is : " + strDate3);
formatter = new SimpleDateFormat("E MMMM dd HH:mm:ss z yyyy");
String strDate4 = formatter.format(date);
System.out.println("Current date and time is : " + strDate4);
formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss a");
String strDate5 = formatter.format(date);
System.out.println("Current date and time is : " + strDate5);
formatter = new SimpleDateFormat("HH:mm:ss");
String strDate6 = formatter.format(date);
System.out.println("Current time is : " + strDate6);
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
System.out.println("current week of year is : " +
calendar.get(Calendar.WEEK_OF_YEAR));
System.out.println("current week of month is : " +
calendar.get(Calendar.WEEK_OF_MONTH));
System.out.println("current day of the year is : " +
calendar.get(Calendar.DAY_OF_YEAR));
}
}
***********************************************************************************
***************************
Q4) 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.*;
invalidpass(String msg) {
super(msg);
}
}
class throw7 {
***********************************************************************************
*******************************
Q5) 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.
Ans:
//Javac -d . Student. Java //package name
//Javac StudentMain.java //program name
//Java StudentMain
package mca;
public Student(int roll, String nm, int m1, int m2, int m3, int m4, int m5, int
m6) {
r_no = roll;
name = nm;
a = m1;
b = m2;
c = m3;
d = m4;
e = m5;
f = m6;
sum = a + b + c + d + e + f;
}
class StudentMain {
public static void main(String[] args) {
String nm;
int roll;
Scanner sc = new Scanner(System.in);
System.out.print("Enter Roll no:= ");
roll = sc.nextInt();
System.out.print("Enter Name:= ");
nm = sc.next();
int m1, m2, m3, m4, m5, m6;
System.out.print("Enter 6 sub mark:= ");
m1 = sc.nextInt();
m2 = sc.nextInt();
m3 = sc.nextInt();
m4 = sc.nextInt();
m5 = sc.nextInt();
m6 = sc.nextInt();
Student s = new Student(roll, nm, m1, m2, m3, m4, m5, m6);
s.display();
}
}
***********************************************************************************
*******************************
Q6) 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.*;
import java.applet.*;
import javax.swing.*;
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.black);
setForeground(Color.red);
}
public void mouseEntered(MouseEvent m)
{
setBackground(Color.magenta);
showStatus("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent m)
{
setBackground(Color.black);
showStatus("Mouse Exited");
repaint();
}
public void mousePressed(MouseEvent m)
{
X=10;
Y=20;
msg="JAVA";
setBackground(Color.green);
repaint();
}
public void mouseReleased(MouseEvent m)
{
X=10;
Y=20;
msg="PHP";
setBackground(Color.blue);
repaint();
}
public void mouseMoved(MouseEvent m)
{
X=m.getX();
Y=m.getY();
msg="TYBCS";
setBackground(Color.white);
showStatus("Mouse Moved");
repaint();
}
public void mouseDragged(MouseEvent m)
{
msg="GRAPHICS";
setBackground(Color.yellow);
repaint();
}
public void mouseClicked(MouseEvent m)
{
msg="NETWORKING";
setBackground(Color.pink);
showStatus("Mouse Clicked"+m.getX()+" "+m.getY());
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
***********************************************************************************
*******************************
Q7) Create an abstract class “order” having members id, description. Create two
subclasses “PurchaseOrder” and “Sales Order” having members customer name and
Vendor name respectively. Definemethods accept and display in all cases. Create 3
objects each of Purchase Order and Sales Order and accept and display details.
import java.io.*;
import java.util.*;
int i;
Scanner s=new Scanner(System.in);
System.out.println("Enter how many objects:");
int n=s.nextInt();
Salesorder[] f=new Salesorder[n];
Purchaseorder[] f1=new Purchaseorder[n];
System.out.println("Enter type of order:");
String ch=s.next();
if(ch.equals("Salesorder"))
{
for(i=0;i<n;i++)
{
System.out.println("Enter id:");
int a=s.nextInt();
System.out.println("Enter desc:");
String b=s.next();
System.out.println("Enter customer name:");
String c=s.next();
System.out.println("Enter vendor name:");
String d=s.next();
f[i]=new Salesorder(a,b,c,d);
}
System.out.println("id \t desc \t cname \t vname ");
for(i=0;i<n;i++)
f[i].display();
}
else
{
for(i=0;i<n;i++)
{
System.out.println("Enter id:");
int a1=s.nextInt();
System.out.println("Enter desc:");
String b1=s.next();
System.out.println("Enter customer name:");
String c1=s.next();
System.out.println("Enter vendor name:");
String d1=s.next();
f1[i]=new Purchaseorder(a1,b1,c1,d1);
}
System.out.println("id \t desc \t cname \t vname ");
for(i=0;i<n;i++)
f1[i].display();
}
}
}
***********************************************************************************
*******************************
Q8) 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.
Ans:
import java.awt.*;
import java.awt.event.*;
class InvalidPasswordException extends Exception
{
InvalidPasswordException()
{
System.out.println(" User name and Password is not same");
}
}
public class PasswordDemo extends Frame implements ActionListener
{
Label uname,upass;
TextField nametext;
TextField passtext,msg;
Button login,Clear;
Panel p;
int attempt=0;
char c='*';
nametext=new TextField(20);
passtext =new TextField(20);
passtext.setEchoChar(c);
msg=new TextField(10);
msg.setEditable(false);
login=new Button("Login");
Clear=new Button("Clear");
login.addActionListener(this);
Clear.addActionListener(this);
p.add(uname);
p.add(nametext);
p.add(upass);
p.add(passtext);
p.add(login);
p.add(Clear);
p.add(msg);
add(p);
setTitle("Login ");
setSize(290,200);
setResizable(false);
setVisible(true);
}
if(user.compareTo(upass)==0)
{
msg.setText("Valid");
System.out.println("Username is valid");
}
else
{
throw new InvalidPasswordException();
}
}
catch(Exception e)
{
msg.setText("Error");
}
attempt++;
}
}
else
{
System.out.println("you are using 3 attempt");
System.exit(0);
}
}
public static void main(String args[])
{
PasswordDemo pd=new PasswordDemo();
pd.login();
}
}
***********************************************************************************
*******************************
Q9) 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.
Ans:import java.io.*;
import java.util.*;
void display() {
System.out.println(id + "\t " + name + "\t\t" + dep);
}
}
class test {
***********************************************************************************
*******************************
Q10)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.
Ans:
import java.util.*;
class Patient1
{
String name;
int age;
int oxylevel;
int HRCTreport;
Patient1(String name, int age, int oxylevel, int HRCTreport)
{
this.name = name;
this.age = age;
this.oxylevel = oxylevel;
this.HRCTreport = HRCTreport;
}
}
public class petient1 extends Exception
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("How many patient you want insert:");
int number = sc.nextInt();
Patient1[] ob = new Patient1[number];
for(int j=0; j<number; j++)
{
System.out.println("Enter Name ");
String name = sc.next();
System.out.println("Enter Age ");
int age = sc.nextInt();
System.out.println("Enter oxygen level");
int oxylevel = sc.nextInt();
System.out.println("Enter HRCT report");
int HRCTreport = sc.nextInt();
ob[j] = new Patient1(name, age, oxylevel, HRCTreport);
}
}
else
{
System.out.println("name: "+ob[j].name);
System.out.println("age " + ob[j].age);
System.out.println("oxygen level " +ob[j].oxylevel);
System.out.println("HRCT report " + ob[j].HRCTreport);
System.out.println("\n");
}
}
}
}
***********************************************************************************
*******************************
Q11)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.
Ans:
import java.io.*;
import java.util.*;
class Cricket {
String name;
int inning, tofnotout, totalruns;
float batavg;
public Cricket(){
name=null;
inning=0;
tofnotout=0;
totalruns=0;
batavg=0;
}
public void get() throws IOException{
Scanner br=new Scanner(System.in);
System.out.println("Enter the name, no of innings, no of times not out,
total runs: ");
name=br.nextLine();
inning=Integer.parseInt(br.nextLine());
tofnotout=Integer.parseInt(br.nextLine());
totalruns=Integer.parseInt(br.nextLine());
}
public void put(){
System.out.println("Name="+name);
System.out.println("no of innings="+inning);
System.out.println("no times notout="+tofnotout);
System.out.println("total runs="+totalruns);
System.out.println("bat avg="+batavg);
}
static void avg(int n, Cricket c[]){
try{
for(int i=0;i<n;i++){
c[i].batavg=c[i].totalruns/c[i].inning;
}
}catch(ArithmeticException e){
System.out.println("Invalid arg");
}
}
static void sort(int n, Cricket c[]){
String temp1;
int temp2,temp3,temp4;
float temp5;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(c[i].batavg<c[j].batavg){
temp1=c[i].name;
c[i].name=c[j].name;
c[j].name=temp1;
temp2=c[i].inning;
c[i].inning=c[j].inning;
c[j].inning=temp2;
temp3=c[i].tofnotout;
c[i].tofnotout=c[j].tofnotout;
c[j].tofnotout=temp3;
temp4=c[i].totalruns;
c[i].totalruns=c[j].totalruns;
c[j].totalruns=temp4;
temp5=c[i].batavg;
c[i].batavg=c[j].batavg;
c[j].batavg=temp5;
}
}
}
}
}
public class a4sa1 {
public static void main(String args[])throws IOException{
Scanner br=new Scanner(System.in);
System.out.println("Enter the limit:");
int n=Integer.parseInt(br.nextLine());
Cricket c[]=new Cricket[n];
for(int i=0;i<n;i++){
c[i]=new Cricket();
c[i].get();
}
Cricket.avg(n,c);
Cricket.sort(n, c);
for(int i=0;i<n;i++){
c[i].put();
}
}
***********************************************************************************
*******************************
Q12) Write a menu driven program to perform the following operations on
multidimensional array ie matrices :
Addition
Multiplication
Exit
import java.util.*;
class Operation {
void addarry() {
Scanner IN = new Scanner(System.in);
int r1, c1, r2, c2;
void multarry() {
Scanner IN = new Scanner(System.in);
int r1, c1, r2, c2, i, j, k;
class ArrayPractical {
public static void main(String[] args) {
do {
System.out.println("Press 1 for addition :");
switch (ch) {
case 1:
a.addarry();
break;
case 2:
a.multarry();
break;
case 3:
System.exit(0);
break;
default:
System.out.println("Invalid choice!!!");
}
System.out.print("Press 1 for continue:");
i = In.nextInt();
} while (i == 1);
}
}
***************************************************END 20 MARKS
PROGRAM*********************************************************