0% found this document useful (0 votes)
3 views94 pages

Java All Ans

The document contains multiple programming assignments and solutions in Java, covering various topics such as prime number generation, abstract classes, BMI calculation, sorting city names, exception handling, and basic banking operations. Each section provides a brief description of the task followed by code snippets demonstrating the implementation. The assignments also include handling user input, file operations, and graphical user interface elements.

Uploaded by

sawantamruta39
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views94 pages

Java All Ans

The document contains multiple programming assignments and solutions in Java, covering various topics such as prime number generation, abstract classes, BMI calculation, sorting city names, exception handling, and basic banking operations. Each section provides a brief description of the task followed by code snippets demonstrating the implementation. The assignments also include handling user input, file operations, and graphical user interface elements.

Uploaded by

sawantamruta39
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 94

Slip 1_1: Write a Program to print all Prime numbers in an array of ‘n’

elements. (use command line arguments)

Solution: class
PrNo
{
public static void main (String[] args)
{
int size = args.length;
int[] array = new int [size];
for(int i=0; i<size; i++)

System.out.println(array[i] + " are the prime numbers in the array ");

Slip 1_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.
Solution:
import java.util.*;
abstract class Staff
{
protected int id;
protected String name;
public Staff(int id,String name)
{
this.id=id;
this.name=name;
}
}
class OfficeStaff extends Staff
{
String dept;
OfficeStaff(int id,String name,String dept)
{

System.out.println("Enter id,name, department");

for(int i=0;i<n;i++)
{
ob[i].display();
}
}
}

Slip2_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
// body mass index class
BM {
public static void main(String args[]) {
String fname = args[0];
String lname = args[1];
double weight = Double.parseDouble(args[2]);

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


float batavg;

public Cricket(){ name=null; inning=0; tofnotout=0; totalruns=0; batavg=0;

} public void get() throws


IOException{ BufferedReader
br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the name, no of innings, no of times not out, total runs:
"); name=br.readLine(); inning=Integer.parseInt(br.readLine());
tofnotout=Integer.parseInt(br.readLine());
totalruns=Integer.parseInt(br.readLine());
}
public void put(){

static void sort(int n, Cricket c[]){


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;
System.out.println("Enter the limit:");

int n=Integer.parseInt(br.readLine()); Cricket c[]=new Cricket[n]; for(int i=0;i<n;i++){


c[i]=new Cricket();

}
Cricket.avg(n,c);
Cricket.sort(n, c);
for(int i=0;i<n;i++){
c[i].put();
}

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

import java.util.Scanner;

class SortStr
{
public static void main(String args[])
{

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


temp=names[j-1]; names[j-
1]=names[j];
names[j]=temp;
}
}
}
System.out.println("\nSorted names are in Ascending Order: ");
for(int i=0;i<N;i++)
{
System.out.println(names[i]);
}
}}

Slip 3_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.
System.out.println("Patient is Covid Positive and needs to be hospitalized");

String name;

this.age=age;

String name;

}
}

double level,hrct;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter name: "); name=br.readLine();
System.out.println("Enter the age: ");
age=Integer.parseInt(br.readLine()); System.out.println("Oxygen
level: "); level=Double.parseDouble(br.readLine());
System.out.println("HRCT report: ");
hrct=Double.parseDouble(br.readLine()); Patient ob=new
Patient(name,age,level,hrct); try{
if(ob.level<95 && ob.hrct>10)

throw new CovidException();

else
System.out.println("Patient Info: \n"+"Name: "+ob.name+"\nAge: "+ob.age+"\nHRCT
report: "+ob.hrct+"\nOxygen level:"

dimensional array.

{
for(int j=0;j<c;j++)
{
mat[i][j] =
sc.nextInt();
}
}
System.out.println("the matrix is:"); for(int
i=0;i<c;i++)
{
for(int
j=0;j<r;j++)
{
System.out.print(" " +mat[j][i]);
}
System.out.println(" ");
}

User can have 3 login chances only. Use clear button to clear the TextFields.

class PasswordDemo extends Frame implements ActionListener

char c= '*' ;

Label uname,upass;
Panel p; int
attempt=0;

{
p=new Panel();
uname=new Label("Use Name: "
,Label.CENTER); upass=new Label ("Password:
",Label.RIGHT); 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);

Button btn=(Button)(ae.getSource());

passtext.setText("");

setTitle("Login ");
setSize(290,200);
setResizable(false);
setVisible(true);
}

String user=nametext.getText();

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

}
}

InputStreamReader i = new InputStreamReader(System.in); BufferedReader r = new


BufferedReader(i);

void con_input() throws IOException


}
}

class Country extends Continent


{ String
cou;
void cou_input()throws IOException
{
System.out.println("Enter the country name:"); cou
= r.readLine();}
}
class State extends Country
{

String sta;
void sta_input()throws IOException
{
System.out.println("Enter the state name:");
sta = r.readLine();} }
import java.util.*;
class Matrix
{
Scanner sc = new Scanner(System.in); int a =
sc.nextInt(); int b = sc.nextInt(); int M[][] = new
int[a][b];
void accept()
{
int a = this.a; int b = this.b;
System.out.println("enter the "+(a*b)+ " values to matrix:");
for(int i=0;i<a;i++)
{
for(int j=0;j<b;j++)
{
this.M[i][j] = sc.nextInt();
}

}
}

System.out.println("enter size 2*2 or 3*3 or ...");

System.out.println("values to matrix 1:");

System.out.println("enter the size:");


Matrix m2 = new Matrix();

System.out.println("values to matrix 2:");

int choice;
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("Press 1: Addition, 2: Multiplication, 3: Exit");
choice = scanner.nextInt();
switch (choice) { case 1:
System.out.println("Addition is:" );
for(int i=0;i<m1.a;i++)
{
for(int j=0;j<m1.b;j++)
{
System.out.print(" "+ (m1.M[i][j]+m2.M[i][j]));
}
System.out.println(" ");
}
break; case 2:
System.out.println("Multiplication is:"); for(int
i=0;i<m2.a;i++)
{
for(int j=0;j<m2.b;j++)
{
public String toString() // overrides toString() method
{
return id+" "+name+" "+salary+" "+desig;
}
public static void main(String args[])
{
Emp E1=new Emp(111,"Rakesh",50000,"bsc cs");
Emp E2=new Emp(112,"Suresh",25000,"msc cs");
System.out.println("Employee details: "+E1);
System.out.println("Employee details: "+E2);
}
}

Slip6_2: 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.BufferedReader; import java.io.IOException; import
java.io.InputStreamReader; abstract class Order{

}
}

String cnm, vnm;


public void accept()throws IOException{
System.out.println("enter id, description,names of customers and vendors");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in)); id = br.readLine(); des= br.readLine(); cnm =
br.readLine(); vnm = br.readLine();
}
public void display(){
System.out.println("id:"+id);
System.out.println("Description:"+des);
System.out.println("Customer Name:"+cnm);
System.out.println("Vendor Name:"+vnm);
System.out.println("-------------------");
} } class Main{ public static void main(String
args[])throws IOException{ int i;
System.out.println("Select any one:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("1.purchase order:");
System.out.println("2.Sales order:");
System.out.println("3.Exit:");
for(i=0;i<m;i++)

for(i=0;i<m;i++)
{
h[i].display();
System.out.println("Object is created:");
}

case 3:
System.out.println("exit:");
System.exit(0);
}
}
}

Slip7_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 {
private double balance;
balance = balance - amount;
}

public static void main(String[] args)


{
Bank b = new Bank(1000); b.withdraw(250);
System.out.println("the withdraw is:"+ b.balance); b.deposit(400);
System.out.println("the deposit is:"+ b.balance);
System.out.println("the balance is:"+ b.getBalance());
}
}

Slip7_2: Write a program to accept a text file from user and display the contents of a file in
reverse order and change its case.
BufferedInputStream bis = new BufferedInputStream(new

System.out.print(ch);
bis.reset();
}
bis.close();
}
else
System.out.println("file not found");
}
}

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

import java.util.*; class


Sphere
{
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the radius of the sphere: ");
double radius=sc.nextDouble();
double surface_area = (4*3.14*(radius*radius));
double volume = ((double)4/3)*3.14*(radius*radius*radius);
System.out.println("The surface area of the sphere = "+surface_area);
System.out.println("The volume of sphere = "+volume);
}}

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

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 mouse clicking");
l1= new Label("Co-ordinates of mouse
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();

}
Slip9_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
import java.util.*; class
Clock
{
int hours,minutes,seconds;
Clock()
{
System.out.println("enter the time in HH MM SS format");
Scanner sc= new Scanner(System.in);
this.hours = sc.nextInt();
this.minutes = sc.nextInt();
this.seconds = sc.nextInt();
}
void isTimeValid()
{
if(hours>=0 && hours<24 && minutes>0 &&minutes<60
&&seconds>0 && seconds<60)
System.out.println("time is valid");
else
System.out.println("time is not valid");
}
}

count.

import java.util.*;

interface MarkerInt {

class product implements MarkerInt {


int pid, pcost, quantity;
String pname;
static int cnt;
// Default constructor

product() {
pid = 1; pcost =
10; quantity = 1;
pname = "pencil";
cnt++;
quantity = q;

}
Scanner sc = new Scanner(System.in);

System.out.println("Enter Number of Product : ");


int n = sc.nextInt();

product pr[] = new product[n];


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

System.out.println("\nEnter " + (i + 1) + " Product Details :\n");


System.out.println("Enter Product ID: ");
int pid = sc.nextInt();

sc.nextLine();
System.out.println("Enter Product Name: ");
String pn = sc.nextLine();

System.out.println("Enter Product Quantity:");

pr[i] = new product(pid, pn, pc, pq);

Slip10_1: Write a program to find the cube of given number using functional interface.

import java.util.*;

float cube();
}
class Draw implements Cube
{
public float cube()
{
System.out.println("enter the number");
Scanner sc= new Scanner (System.in); float
cu = sc.nextInt();
double cue = cu*cu*cu;
System.out.println("cube of no is:"+cue); return
0;
}
public static void main(String args[])
{
Draw d = new Draw();
d.cube();
}
}

System.out.println("Roll_no : "+r_no);
System.out.println("Name : "+name);
System.out.println("class :"+clas);
System.out.println("-----MARKS-------");
System.out.println("Sub 1 : "+a);
System.out.println("Sub 2 : "+b);
System.out.println("Sub 3 : "+c);
System.out.println("Sub 4 : "+d);
System.out.println("Sub 5 : "+e);
System.out.println("Sub 6 : "+f);
System.out.println("Total : "+sum);
System.out.println("percentage: "+per);
System.out.println("------------------");
}
}

public class StudentPer extends StudentInfo {


public StudentPer(int roll, String nm, String cla,int m1,int m2,int m3,int m4, int
m5,int m6)
{ r_no =
roll;
clas = cla;

public static void main(String[] args)


{

Scanner sc = new Scanner(System.in);


System.out.print("Enter Roll no:= "); roll
= sc.nextInt();
System.out.print("Enter Name:= ");
nm = sc.next();
System.out.print("Enter class:= "); clas=
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();

StudentPer s = new StudentPer(roll,nm,clas,m1,m2,m3,m4,m5,m6);

s.display();
}
}

Slip11_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 –

import java.io.*;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

radius,height). Create one object and calculate the volume.


{
double a=(2*pi*radius*height)+(2*pi*radius*radius);
System.out.println("the area of cylinder is " +a);
}
public void volume()
{
double v=pi*radius*radius*height;
System.out.println("the volume of cylinder is "+v);
}
}
class slipno11a
{
public static void main(String args[]) throws Exception
{
Cylinder C1=new Cylinder();
C1.input();
C1.area();
C1.volume();
}
}

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

import java.awt.*; import


java.awt.event.*; import
javax.swing.*;
class Userpassword extends JFrame implements ActionListener

Userpassword()

name = new JLabel("Name : ");


pass = new JLabel("Password : "); nameText
= new JTextField(20); passText = new
JPasswordField(20); login = new
JButton("Login"); end = new
JButton("End");
login.addActionListener(this);
end.addActionListener(this);
setLayout(new GridLayout(3,2));
add(name); add(nameText); add(pass);
add(passText);
add(login);
add(end);
setTitle("Login Check"); setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true);

}
if(user.compareTo(pass)==0)

System.exit(0);
}
else
{
throw new InvalidPasswordException();
}
}
catch(Exception e1)
{
cnt++;
JOptionPane.showMessageDialog(null, "Login Failed", "Login",
JOptionPane.ERROR_MESSAGE);
nameText.setText("");
passText.setText("");
nameText.requestFocus();
if(cnt==3)

new Userpassword();

class college
{ int
no;
String name;
String addr;

}
class Dept extends college
{ int
dno;
String dname; Scanner sc = new
Scanner(System.in); public void
accept()
{

name=sc.next();

dname=sc.next();

System.out.println("college name"+name);
System.out.println("college address"+addr);

}
public static void main(String a[])
{
Dept ob=new Dept();
ob.accept();
ob.display();
}
}
Slip12_2: 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 java.awt.*; import
java.awt.event.*;
import javax.swing.*;

public class Slip12 extends JFrame implements ActionListener


{
String msg=" "; int
v1,v2,result;
JTextField t;
JButton b[]=new JButton[10]; JButton
add,sub,mul,div,clear,equals;
char choice; JPanel p,p1;
public Slip12()
{
setLayout(new BorderLayout()); p =new
JPanel(); t=new JTextField(20); p.add(t);
p1=new JPanel(); p1.setLayout(new
GridLayout(5,4)); for(int i=0;i<10 i="" span="">
{
b[i]=new JButton(""+i);
} equals=new JButton("=");
add=new JButton("+"); sub=new JButton("-
"); mul=new JButton("*"); div=new
JButton("/");
clear=new JButton("C");

for(int i=0;i<10 i="" span="">


{
p1.add(b[i]);
}

p1.add(equals); p1.add(add);
p1.add(sub); p1.add(mul);
p1.add(div); p1.add(clear);

for(int i=0;i<10 i="" span="">


{
b[i].addActionListener(this);
}
add.addActionListener(this); sub.addActionListener(this);
mul.addActionListener(this); div.addActionListener(this);
clear.addActionListener(this); equals.addActionListener(this);

add(p,BorderLayout.NORTH); add(p1);

public void actionPerformed(ActionEvent ae)


{
String str = ae.getActionCommand(); char ch =
str.charAt(0); if ( Character.isDigit(ch))
t.setText(t.getText()+str); else
if(str.equals("+"))
{
v1=Integer.parseInt(t.getText()); choice='+';
t.setText(""); }
else if(str.equals("-"))
{
v1=Integer.parseInt(t.getText()); choice='-';
t.setText(""); }
else if(str.equals("*"))
{
v1=Integer.parseInt(t.getText()); choice='*';
t.setText(""); }
else if(str.equals("/"))
{ v1=Integer.parseInt(t.getText()); choice='/';
t.setText("");
}
if(str.equals("="))
{
v2=Integer.parseInt(t.getText()); if(choice=='+')
result=v1+v2; else if(choice=='-') result=v1-v2;
else if(choice=='*') result=v1*v2; else
if(choice=='/') result=v1/v2;
String fname=argd[0];

File f=new File(fname);

if(f.isFile())

FileInputStream fis=new FileInputStream(fname);

int ch,cnt=0;

while((ch=fis.read())!=-1)
{

if(ch=='\n')

cnt++;

}
}

System.out.println("Number of line in Given file is "+cnt);

import java.util.Date;

class slip13_2
{
public static void main(String[] args)
{
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String strDate= formatter.format(date);
System.out.println(strDate);

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


String strDate1= formatter1.format(date);
System.out.println(strDate1);

SimpleDateFormat formatter2 = new SimpleDateFormat("EEEEE


MMMMM dd yyyy");
String strDate2= formatter2.format(date);
System.out.println(strDate2);

SimpleDateFormat formatter3 = new SimpleDateFormat("EEEEE


MMMMM dd HH:mm:ss z yyyy");
String strDate3= formatter3.format(date);
System.out.println(strDate3);

SimpleDateFormat formatter4 = new SimpleDateFormat("dd/MM/yyyy


HH:mm:ss a");
String strDate4= formatter4.format(date);
System.out.println(strDate4);
}
}

===============================================================

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

import java.util.Scanner; import


java.util.*;
class Zerono extends Exception
{}

int no,i,j;
Scanner sc=new Scanner(System.in);
try
{
System.out.println("enter no");
no=sc.nextInt();
if(no==0)
throw new Zerono();
if(no>0)
{
for(i=2;i<=no/2;i++)
{
if(no%i==0)
{
count++;
}

}
}
if(count==0)
System.out.println("No is Prime");
else

int ct,mt,et; public SYMarks(int

ct,int mt,int et)

this.ct=ct;

this.mt=mt;

this.et=et;
}
public void display()
{
System.out.println("\nMarks are;");

System.out.println("Computer\tMaths\tElectronics");

System.out.println(ct+"\t"+mt+"\t"+et);

System.out.println("Theory\tPracticals");

System.out.println(Theory+"\t"+Practicals);

}
}
Mainfile import
SY.SYMarks; import
TY.TYMarks;
import java.io.*;
class SYTY
{
int rollno;

int ComputerTotal, MathsTotal, ElecTotal, Theory, Practicals;

String name;

System.out.println("Enter SY marks: ");

while((ComputerTotal<0 || ComputerTotal>100))

System.out.println("\n\tInvalid marks.....");

System.out.println("Please ReEnter the marks: ");

ComputerTotal = Integer.parseInt(br.readLine());
}
System.out.println("\nEnter maths marks");

MathsTotal=Integer.parseInt(br.readLine());

while((MathsTotal<0 || MathsTotal>100))
{

System.out.println("\n\tInvalid marks.....");

SYMarks sy = new SYMarks(ComputerTotal, MathsTotal, ElecTotal);

System.out.print("\nEnter TY marks: ");

System.out.print("\nEnter theory marks ");


Theory = Integer.parseInt(br.readLine());
while((Theory<0 || Theory>100))
{
System.out.println("\n\tInvalid marks.....");

System.out.println("Please Reenter the marks: ");


Theory = Integer.parseInt(br.readLine());

CalculateGrade();

public void getdata() throws Exception


{
System.out.println("\nEnter number of students: ");
int n=Integer.parseInt(br.readLine());
SYTY object[]=new SYTY[n];

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

System.out.println("\nEnter name: ");

public void CalculateGrade()

percentage = (ComputerTotal+ MathsTotal + ElecTotal + Theory +


Practicals)/5;

System.out.println("Result:");

if(percentage >= 70)

System.out.println("Grade:A");
else if(percentage >= 60)

System.out.println("Grade:B");

else if(percentage >= 50)


System.out.println("Grade:C");

else if(percentage >= 40)

Book name and Author name in file.

import java.io.*; import


java.util.*;

class demoFile
{
public static void main(String args[]) throws Exception {
Scanner sc= new Scanner(System.in);

System.out.println("Enter the first file");

String f1=sc.next();

System.out.println("Enter the second file");

String f2=sc.next();

class Slip16_1 {
public static void main(String args[])
{
//you can read value from user
int a = 5;
Square s = (int x) -> x * x;
int ans = s.calculate(a);
System.out.println(ans);
}
}
Slip16_2: Write a program to design a screen using Awt that,
class MeEx

JMenu Edit;
JMenu About;

{
public static void main(String args[])
{
new MeEx();
}
}

Slip17_1: 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.*;
class Customer {
String name;
int Pno;
}
class Depositer extends Customer
{
}

System.out.println("The details are:");


System.out.println("name: " +this.name);
System.out.println("phone number: "+this.Pno);
System.out.println("accout number: " +this.accno);
System.out.println("Balance: " +this.bal);
System.out.println("loan number: "+this.loanno);
System.out.println("loan amount: "+this.loanamt);
System.out.println("------------------------------------");

public static void main(String args[]){


int i;
Scanner sc = new Scanner(System.in);
System.out.println("enter total number:");
int n =sc.nextInt();
Borrower[] l = new Borrower[n];
for(i=0;i<n;i++){ l[i]
= new Borrower();
l[i].read();
}
for(i=0;i<n;i++){
l[i].display();
}
}
}

Slip17_2: 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 java.util.*; import


javax.swing.*; import
java.awt.event.*;
class TextField implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextField(){
JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false); b1=new
JButton("concatenation");
b1.setBounds(30,200,100,50);
b2=new JButton("reverse");
b2.setBounds(150,200,100,50);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
StringBuffer sb = new StringBuffer();
String s1=tf1.getText();
String s2=tf2.getText();
if(e.getSource()==b1){
String s3= s1+s2;
tf3.setText(s3);
}else if(e.getSource()==b2){
String str = s1;
String strArray = "";
for (int i = str.length()-1; i>=0 ; i--){
strArray+=str.charAt(i);
}
tf3.setText(strArray);
}
public static void main(String[] args)
{
FrameDemo ob=new FrameDemo();
}
}

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; class
cricket
{
int inning, tofnotout, totalruns;

}
void put()
{
System.out.println("name: "+name);
System.out.println("no of innings: "+inning);
System.out.println("no of time(s) not out: "+tofnotout);
System.out.println("total runs: "+totalruns);
System.out.println("batting average: "+batavg);
} static void avg(int n, cricket
c[])
{
for(int i=0; i<n; i++)
{
c[i].batavg= c[i].totalruns/c[i].inning;
}
}
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;

public static void main(String args[])


{
Scanner s1= new Scanner(System.in);
System.out.println("Enter The Limit: ");
int n= s1.nextInt(); 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();
}
}
}

Slip19_1: Write a program to accept the two dimensional array from user and display sum
of its diagonal elements.

import java.util.Scanner; class


Array
{
public static void main(String args[])
{
System.out.print(array[i][j] + " ");
if(i==j)

}
}

Slip19_2: 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 java.awt.*; import


javax.swing.*;
import java.awt.event.*; class
ComboBoxExample
{
JFrame f;
JTextField t1;
ComboBoxExample()
{
f=new JFrame("ComboBox Example");
final JLabel label = new JLabel(); t1=new
JTextField(10);
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JButton b=new JButton("Show");
b.setBounds(200,100,75,20);

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

import java.util.*;
class continent
{
String c1;

}
class country extends continent
{
String c2;
}
class state extends country
{
String s1;
String p1;

public void display()


{
System.out.println("Continent name: "+c1+"\n"+"Country name:
"+c2+"\n"+"State Name: "+s1+"\n"+"Place: "+p1);
}

Slip20_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; import


java.util.*;
class Addition
{

public int ans,n1,n2; public


float answer,num1,num2;
public Addition(int n1,int n2,float num1,float num2)
{
this.n1=n1;
this.n2=n2; this.num1=num1;
this.num2=num2;

}
public void add()
{

ans=n1+n2;
System.out.println("addition is="+ans);
}

public void sub()

else
System.out.println(n2+" is greater than "+n1);
import operation.Maximum;

import java.util.*;
class Arithmatic
{
public static void main (String args[])
{
int n1,n2; float num1,num2;
Scanner sc=new Scanner(System.in);
System.out.println("Enter first no="); n1=sc.nextInt();
System.out.println("Enter second no="); n2=sc.nextInt();
System.out.println("Enter third no=");
num1=sc.nextFloat();
System.out.println("Enter fourth no=");
num2=sc.nextFloat();

Maximum ob1=new Maximum(n1,n2,num1,num2);

ob1.add();
ob1.sub();
ob1.max();

{
System.out.println("Enter Date, Month and Year");

day=sc.nextInt(); if(day<1 ||
day>31) throw new
InvalidDateException();
month=sc.nextInt(); if(month>12
||month<1) throw new
InvalidDateException();
year=sc.nextInt();
if(year>10000 ||year<1000) throw
new InvalidDateException();
}
catch(InvalidDateException e)
{
System.out.println("Invalid Date entered");
System.exit(0);
}
catch(Exception e)
{
System.out.println("Enter Valid Date");
System.exit(0);
}
}
public void display()
{
System.out.println("Entered Date is "+day+":"+month+":"+year);

double sal; static int

cnt=0;
Employee()
}
Employee(int id,String name,String deptname,double sal)
{
this.id=id;
this.name=name;
this.deptname=deptname;
this.sal=sal;
cnt++;
displayCount();
}
public static void displayCount()
{
System.out.println("Total Objects created "+cnt);

}
public void displayData()
{

System.out.println(this.id+"\t\t"+this.name+"\t\t\t"+this.deptname+"\t\t"+this. sal);

}
public static void main(String args[])
{
Employee e1=new Employee(101,"Maithili","HR",120020.20);

Employee e2=new Employee(102,"Soham","IT",140020.20);


Employee e3=new Employee(104,"Akshay","Accounts",100020.20);
System.out.println("EID\t\tName\t\t\tDepartment\t\tSalary");
e1.displayData(); e2.displayData();
e3.displayData();
}
}

Slip22_1: 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).
class Rectangle extends Shape
{
Rectangle(int a,int b)
{
n1=a;
n2=b;
}
public void printArea()
{
float area;
area=n1*n2;
System.out.println("area of rectangle="+area);
}
}
class Triangle extends Shape
{
Triangle(int a,int b)
{
n1=a;
n2=b;
}
public void printArea()
{
{

ob.printArea();

Triangle tr=new Triangle(n1,n2);


tr.printArea();

Circle cr=new Circle(n1);


cr.printArea();
}
}

Slip22_2: 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).

import java.awt.*; import


java.awt.event.*; import
javax.swing.*;
class MouseEvents extends JFrame implements MouseListener, MouseMotionListener

int x,y;

public void mouseClicked(MouseEvent me)


{

str+="Clicked Button: Middle";


else if(i==3) str+="Clicked
Button: Right";
this.display();

}
public void mouseEntered(MouseEvent me)
{
str+="Mouse Entered ";
this.display();
}
public void mouseExited(MouseEvent me)
{
str+="MouseExited"; this.display();

}
public void mousePressed(MouseEvent me)
{
x=me.getX();
y=me.getY();
str+="MousePressed at: "+x+"\t"+y; this.display();
}

x=me.getX();
y=me.getY();

x=me.getX();
y=me.getY();

x=me.getX();
y=me.getY();
str+="Mouse Moved at:"+x+"\t"+y;

str="";
}
public static void main(String[] args) {

MouseEvents mes=new MouseEvents();


mes.setSize(400,400); mes.setVisible(true);
mes.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

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

import java.util.*;
class slip23_1
{
private int data;

slip23_1()

{
System.out.println(x+" Number is Negetive");
if(x%2==0)
{
System.out.println(x+" Number is Even");
}
}
public void isOdd(int x)
{
if(x%2!=0)
{
System.out.println(x+" Number is Odd ");
}
}
public void isZero(int x)
{
if(x==0)
{
System.out.println(x+" Number is Zero ");
}
}
public static void main(String args[])
{
int data=Integer.parseInt(args[0]);

1
class slip23_2 extends KeyAdapter

{
JFrame ob=new JFrame();
l1=new JLabel("US Dollars");
l2=new JLabel("Singapore Dollars");
l3=new JLabel("Euros");
t1=new JTextField(10);
t2=new JTextField(10);
t3=new JTextField(10);
ob.add(l1); ob.add(t1);
ob.add(l2); ob.add(t2);
ob.add(l3); ob.add(t3);
ob.setVisible(true);
t1.addKeyListener(this);
ob.setLayout(new FlowLayout());
ob.setSize(400,400);
ob.setDefaultCloseOperation(3);
}

public void keyReleased(KeyEvent ke)


{
try
{
Double USD=Double.parseDouble(t1.getText());
t2.setText(""+SGD);

public static void main(String []args)


{

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


{
public abstract void getBalance();
}
class BankA extends Bank
{
int bal=100;

int bal=200; public


void getBalance()

{
System.out.println("Balance of BankC is "+bal);
}
public static void main(String args[])
{
BankA a=new BankA();
BankB b=new BankB();
BankC c=new BankC();

a.getBalance();
b.getBalance();
c.getBalance();

import java.awt.geom.*;

import javax.swing.JPanel; class Ovals extends JPanel


{
private Graphics g;
private int prevX, prevY;
private String drawtype;
public Ovals()
{
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
selectpaint();
}
});
}
private void selectpaint()
{
g=getGraphics();
Dimension d = getSize();
int x =d.width/2;
int y = d.height/2;
int r1=(int) ((d.width < d.height)? 0.4*d.width: 0.4*d.height);

Slip25_1:Create a class Student(rollno, name ,class, per), to read student information from
the console and display them (Using BufferedReader class)

import java.io.* ;

class Student

public static void main(String args[])throws Exception

{
InputStreamReader r=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(r);


System.out.println("Enter name:");
String name = br.readLine();

System.out.println("Enter roll no.:");

String number=br.readLine();

Slip25_2: Create the following GUI screen using appropriate layout manager.

Accept the name, class, hobbies from the user and display the selected options in

public class HobbiesDemo extends JFrame implements ActionListener,ItemListener


{
JLabel l1,l2,l3,l4,l5;
JTextField tf1;
JRadioButton rb1,rb2,rb3;
ButtonGroup bg;
JCheckBox cb1,cb2,cb3;
JPanel p1,p2,p3,p4;

HobbiesDemo ()
{
l1=new JLabel("Your Name : ");
l2=new JLabel("Your Class :");
l3=new JLabel("Your Hobbies :");
l4=new JLabel(" ");
l5=new JLabel(" ");

tf1=new JTextField();

cb1=new JCheckBox("Music");

p1.setLayout(new GridLayout(1,2));

p2.add(rb1);
p2.add(rb2);
p2.add(rb3);

p3=new JPanel();
p3.setLayout(new GridLayout(4,1));
p3.add(l3);
p3.add(cb1);
p3.add(cb2);
p3.add(cb3); p4=new JPanel();
p4.setLayout(new GridLayout(1,2));
p4.add(l4);
p4.add(l5);

BorderLayout bob=new BorderLayout();


setLayout(bob);

add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.WEST);
add(p3,BorderLayout.EAST);

add(p4,BorderLayout.SOUTH);

setTitle("INFORMATION");
setSize(500,300);
if(cb2.isSelected())
s=s+cb2.getText()+" ";

public static void main(String args[])


{
HobbiesDemo hob=new HobbiesDemo();
}
}

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

class Item
{
int ino;
String iname;
double iprice; static
int count=0;
Item()
{ }
Item(int no,String nm,double d)
{
ino=no;
nm=iname;
iprice=d;
count++;
}
public void display()
{
System.out.println("Total objects created "+count);
System.out.println(ino+" "+iname+" "+iprice);
}
public static void main(String args[])
{
Item ob1=new Item(1,"Laptop",20000.00);
ob1.display();
Item ob2=new Item(1,"Laptop",20000.00);
ob2.display();
}
}
Slip26_2: Define a class ‘Donor’ to store the below mentioned details of a blood donor.
name, age, address, contactnumber, bloodgroup, date of last donation. Create ‘n’ objects of
this class for all the regular donors at Pune. Write these objects to a file. Read these objects
from the file and display only those donors’ details whose blood group is ‘A+ve’ and had
not donated for the recent six months.

class Donor
{
String name, address,group;
int age, contact, lod;

public Donor(String Name,String address, String group,int age,int contact,int lod)


{
this.name=name;
this.address=address; this.group=group;
this.age=age;
this .contact=contact;
this.lod=lod;
}

public static void main(String args[])


{
Scanner s=new Scanner(System.in);
System.out.println("Enter how many records you want");
int n=s.nextInt(); try {
ObjectOutputStream o=new ObjectOutputStream(new FileOutputStream("save.txt"));

catch(IOException e)
{

for(int i=0;i<n;i++)
{
Donor d=(Donor)z.readObject(); if(d.group.equals("A+ve")&&d.lod>=6)
System.out.println(d);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Slip27_1: Define an Employee class with suitable attributes having getSalary() method,
which returns salary withdrawn by a particular employee. Write a class Manager which
extends a class Employee, override the getSalary() method, which will return salary of
manager by adding traveling allowance, house rent allowance etc.

import java.util.*;
class Employee
{
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Press 1 for Employee Salary and 0 for Manager");
int ch=sc.nextInt(); if(ch==1)
{
Employee Eob=new Employee();
Eob.getSalary();
}
else if(ch == 0)
{
Manager Mob=new Manager();
Mob.getSalary();
}
else
System.out.println("Entered Wrong Choice");

}
}

Slip27_2: Write a program to accept a string as command line argument and check
whether it is a file or directory. Also perform operations as follows:
i) If it is a directory,delete all text files in that directory. Confirm delete
operation from user before deleting text files. Also, display a count showing
the number of files deleted, if any, from the directory. ii) If it is a file display
various details of that file.

if(n==1)
{
String[] s1=f.list();
String a=".txt";
for(String str: s1)
{
System.out.println(str);
if(str.endsWith(a))
{
File f1=new File(fname, str);
System.out.println(str+"-->Deleted");
f1.delete();
}
}

}
else
System.out.println("OKKKK");
}
}
}

Slip28_1: Write a program that reads on file name from the user, then displays information
about whether the file exists, whether the file is readable, whether the file is writable, the
type of file and the length of the file in bytes.

System.out.println("Name of the File is "+f.getName());

if(f.canRead())

System.out.println("File is Readable ");

else

System.out.println("File is not Readable "); if(f.canWrite())

System.out.println("File is Writeable");

else

System.out.println("File is not Writeable");


System.out.println("Length of the File= "+f.length());

import java.util.*; import


java.text.*; import
java.awt.*;
import java.awt.event.*;

class slip28_2 extends KeyAdapter


{
JLabel l1,l2;
JTextField t1,t2;
slip28_2()
{
JFrame ob=new JFrame("Temperature Converter");
l1=new JLabel("Celsius"); l2=new
JLabel("Fahreheit"); t1=new JTextField(10);
t2=new JTextField(10); ob.add(l1); ob.add(t1);
ob.add(l2); ob.add(t2);
ob.setVisible(true);
t1.addKeyListener(this);

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

import java.util.Scanner;
class Customer
{

int cno;
String cname,cmob,cadd;

public static void main(String [] args)


{
int i=0;
{

Scanner sc = new Scanner(System.in);


Customer ob[]=new Customer[5];

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

import java.io.*; class Vehicle


{
String company; double price;
public void accept() throws
IOException
{
System.out.println("Enter the Company and price of the
Vehicle: ");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
company=br.readLine();
price=Double.parseDouble(br.readLine());

}
public void display()
{

System.out.println("Mileage: "+mileage);
}

public void accept() throws IOException


{
super.accept();
System.out.println("Enter the capacity of vehicle in tons: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
captons=Double.parseDouble(br.readLine());
}
public void display()
{
super.display();
System.out.println("Capacity in tons: "+captons);
}
}
class Sa3
{
public static void main(String [] args) throws IOException
{
int i;
System.out.println("Enter the type of vehicle: ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("1.Light Vehicle");

System.out.println("2.Heavy Vehicle"); int


ch=Integer.parseInt(br.readLine());
switch(ch)
System.out.println("Enter the number of Heavy vehicles: ");
int m=Integer.parseInt(br.readLine());
HeavyMotorVehicle [] h=new HeavyMotorVehicle[m];

}
for(i=0;i<m;i++){
h[i].display();
}
break;
}
}

Slip30_1: Write program to define class Person with data member as


Personname,Aadharno, Panno. Accept information for 5 objects and display appropriate
information (use this keyword).

import java.util.*;
class person
{
String Personname;
int Adharno, Panno;

public void display()


{
{

Slip30_2: Write a program that creates a user interface to perform integer divisions.
The user enters two numbers in the text fields, Number1 and Number2. The division of
Number1 and Number2 is displayed in the Result field when the Divide button is clicked. If
Number1 or Number2 were not an integer, the program would throw a
NumberFormatException. If Number2 were Zero, the program would throw an
Arithmetic Exception Display the exception in a message dialog
box
import javax.swing.*;
import java.awt.*; import
java.awt.event.*;
class Division extends JFrame implements ActionListener
{

JLabel l1,l2,Result;

setLayout(new FlowLayout());
btn1.addActionListener(this);
setVisible(true);
setSize(300,400);
int v1=Integer.parseInt(t1.getText());
int v2=Integer.parseInt(t2.getText());
int ans=v1/v2;

Result.setText(ans+" ");
}
catch(NumberFormatException e)
{
System.out.println("Enter a valid number!");
}

catch(ArithmeticException o)
{
System.out.println("Divided by zero");
}
}
public static void main(String args[])
{
Division ob1=new Division();
}
}
TO JOIN NR CLASSES LLP
WhatsApp on
9730381255
Follow us on Instagram
@logic_overflow

You might also like