TYBCS Java Slips Solution 2022
TYBCS Java Slips Solution 2022
Java Programming - I
Solved Practical Slips
2022-23
Follow us on Instagram
@logic_overflow
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++)
{
array[i] = Integer.parseInt(args[i]);
}
for(int i=0; i<array.length; i++)
{
boolean isPrime = true;
if(array[i]%j==0)
{
isPrime = false;
break;
}
}
if(isPrime)
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.*;
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 massdivided by the square of their height.
(Hint : BMI = Wts. In kgs / (ht)2
import java.io.*;
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{
}
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;
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;
}
}
}
}
}
class Name {
public static void main(String args[])throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
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();
c[i].get();
}
Cricket.avg(n,c);
Cricket.sort(n, c);
for(int i=0;i<n;i++){
c[i].put();
}
import java.util.Scanner;
class SortStr
{
public static void main(String args[])
{
String temp;
Scanner SC = new Scanner(System.in);
//sorting strings
import java.io.*;
class CovidException extends Exception{
public CovidException(){
System.out.println("Patient is Covid Positive and needs to be hospitalized");
}
}
class Patient{
String name;
int age;
double level,hrct;
public Patient(String name,int age,double level,double hrct)
{
this.name=name;
this.age=age;
this.level=level;
this.hrct=hrct;
}
public static void main(String[] args)throws IOException
{
String name;
int age;
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: ");
else
System.out.println("Patient Info: \n"+"Name: "+ob.name+"\nAge: "+ob.age+"\nHRCT
report: "+ob.hrct+"\nOxygen level:"
+ob.level);
}catch(CovidException e){
}
}
}
Slip4_1: Write a program to print an array after changing the rows and columns of a giventwo-
dimensional array.
import java.util.*;
class ArrTrans
{
public static void main(String args[])
{
System.out.println("enter the row and column");
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
int c = sc.nextInt();
int mat[][] = new int[r][c];
System.out.println("enter the array elts:");
for(int i=0;i<r;i++)
{
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++)
{
import java.awt.*;
import java.awt.event.*;
class InvalidPasswordException extends Exception
{
InvalidPasswordException()
{
System.out.println(" User name and Password is not same");
}
}
class PasswordDemo extends Frame implements ActionListener
{
Label uname,upass;
TextField nametext;
TextField passtext,msg;
Button login,Clear;
Panel p;
int attempt=0;
char c= '*' ;
public void login()
{
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");
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
class Continent{
String con;
InputStreamReader i = new InputStreamReader(System.in);
BufferedReader r = new BufferedReader(i);
void con_input() throws IOException
{
System.out.println("Enter the continent name:");
con = r.readLine();
}
}
String sta;
void sta_input()throws IOException
{
System.out.println("Enter the state name:");
sta = r.readLine();}
}
class Main extends State
{
String pla;
void pla_input()throws IOException
{
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()
{
}
}
void display()
{
for(int i =0;i<a;i++)
{
for(int j =0;j<b;j++)
{
System.out.print(" "+this.M[i][j]);
}
System.out.println(" ");
}
}
public static void main(String a[])
{
System.out.println("enter size 2*2 or 3*3 or ...");
Matrix m1 = new Matrix();
m1.accept();
System.out.println("values to matrix 1:");
m1.display();
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]));
case 3:
System.exit(0);
}
}
}
}
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 id,des;
}
class Porder extends 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("-------------------");
}
}
int ch = Integer.parseInt(br.readLine());
switch(ch){
case 1:
System.out.println("enter the no of purchas order:");
int n = Integer.parseInt(br.readLine());
Porder[] l = new Porder[n];
for(i=0;i<n;i++)
{
l[i] = new Porder();
l[i].accept();
}
for(i=0;i<n;i++)
{
l[i].display();
System.out.println("Object is created:");
}
case 2:
System.out.println("enter the no of sales order:");
int m = Integer.parseInt(br.readLine());
Porder[] h = new Porder[m];
for(i=0;i<m;i++)
{
h[i] = new Porder();
h[i].accept();
}
for(i=0;i<m;i++)
{
h[i].display();
System.out.println("Object is created:");
}
case 3:
System.out.println("exit:");
System.exit(0);
}
}
}
class Bank
{
private double balance;
public Bank()
{
balance = 0;
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.
import java.io.*;
import java.util.*;
class ReverseFile
{
public static void main(String args[])throws IOException
{
Scanner sc = new Scanner(System.in);
System.out.println("enter file name:");
String fnm = sc.next();
File f = new File(fnm);
if(f.isFile())
{
BufferedInputStream bis = new BufferedInputStream(new
FileInputStream(fnm));
int size =bis.available();
for(int i = size-1;i>=0;i--)
{
bis.mark(i);
bis.skip(i);
char ch=((char)bis.read());
if(Character.isLowerCase(ch))
ch=Character.toUpperCase(ch);
else if(Character.isUpperCase(ch))
ch = Character.toLowerCase(ch);
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);
}
}
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();
Slip9_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
objectsof classproduct and display the contents of each object and Also display the object
count.
import java.util.*;
interface MarkerInt {
product() {
pid = 1;
pcost = 10;
quantity = 1;
pname = "pencil";
cnt++;
}
// Parameterized constructor
}
}
class MarkerInterface {
sc.nextLine();
System.out.println("Enter Product Name: ");
String pn = sc.nextLine();
}
System.out.println("\n\t\t Product Details\n");
System.out.println("\tId\tPname\tCost\tQuantity\n");
for (int i = 0; i < n; i++) {
pr[i].display();
}
sc.close();
}
Slip10_1: Write a program to find the cube of given number using functional interface.
import java.util.*;
interface Cube
{
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();
Slip10_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.
PackageFIle
package student;
class StudentInfo
{
public int r_no;
public String name, clas;
public int a,b,c,d,e,f;
int sum=0;
double per;
Main File
import student.StudentPer;
import java.util.*;
import java.lang.*;
import java.io.*;
class StudentMain
{
public static void main(String[] args)
{
String nm, clas;
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();
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();
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 –
radius,height). Createone object and calculate the volume.
import java.io.*;
interface Operation
{
final static float pi=3.142f;
void area();
void volume();
}
class Cylinder implements Operation
{
double radius,height;
void input() throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\n Enter the radius and height=");
radius=Double.parseDouble(br.readLine());
height=Double.parseDouble(br.readLine());
}
public void area()
{
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();
Slip11_2: Write a program to accept the username and password from user if username and
password arenot same then raise "Invalid Password" with appropriate msg.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class InvalidPasswordException extends Exception
{}
class Userpassword extends JFrame implements ActionListener
{
JLabel name, pass;
JTextField nameText;
JPasswordField passText;
JButton login, end;
static int cnt=0;
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);
}
public void actionPerformed (ActionEvent e)
{
if(e.getSource()==end)
{
System.exit(0);
}
if(e.getSource()==login)
{
try
{
String user = nameText.getText();
String pass = new String(passText.getPassword());
if(user.compareTo(pass)==0)
{
JOptionPane.showMessageDialog(null, "Login Successful",
"Login", JOptionPane. INFORMATION_MESSAGE);
System.exit(0);
}
else
{
throw new InvalidPasswordException();
}
}
catch(Exception e1)
}
}
}
public static void main(String args[])
{
new Userpassword();
}
}
Slip12_1: Write a program to create parent class College(cno, cname, caddr) and derived
classDepartment(dno, dname) from College. Write a necessary methods to display College
details.
import java.util.*;
class college
{
int no;
String name;
String addr;
Slip12_2: Write a java program that works as a simple calculator. Use a grid layout to
arrange buttons forthe digits and for the +, -, *, % operations. Add a text field to display
the result.
.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
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");
p1.add(equals);
p1.add(add);
p1.add(sub);
p1.add(mul);
add(p,BorderLayout.NORTH);
add(p1);
if(str.equals("="))
t.setText(""+result);
}
if(str.equals("C"))
{
t.setText("");
}
}
public static void main(String args[])
{
New Slip12();
}
}
Slip13_1: Write a program to accept a file name from command prompt, if the file exits
then displaynumber of words and lines in that file.
import java.io.*;
class slip13_1
{
public static void main(String argd[]) throws Exception
{
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)
Slip 13_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 2021Current date and time is :
31/08/21 15:25:59 PM +0530
import java.text.SimpleDateFormat;
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);
===============================================================
Slip14_1: Write a program to accept a number from the user, if number is zero then throw user
definedexception “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
{}
class Prime
{
static int count=0;
public static void main(String args[])
{
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(count==0)
System.out.println("No is Prime");
else
System.out.println("Not a Prime number");
catch(Zerono ob)
{
System.out.println("no can not be zero");
}
}
}
Slip14_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 subjectsand 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
package SY;
int ct,mt,et;
this.ct=ct;
this.mt=mt;
this.et=et;
System.out.println("\nMarks are;");
System.out.println("Computer\tMaths\tElectronics");
System.out.println(ct+"\t"+mt+"\t"+et);
}
Package 2
package TY;
int Theory,Practicals;
this.Theory=Theory;
this.Practicals=Practicals;
}
System.out.println("\nMarks are:");
System.out.println("Theory\tPracticals");
System.out.println(Theory+"\t"+Practicals);
Mainfile
import SY.SYMarks;
import TY.TYMarks;
class SYTY
int rollno;
public SYTY()
{}
this.rollno = rollno;
this.name = name;
ComputerTotal = Integer.parseInt(br.readLine());
while((ComputerTotal<0 || ComputerTotal>100))
System.out.println("\n\tInvalid marks.....");
ComputerTotal = Integer.parseInt(br.readLine());
MathsTotal=Integer.parseInt(br.readLine());
while((MathsTotal<0 || MathsTotal>100))
{
System.out.println("\n\tInvalid marks.....");
MathsTotal=Integer.parseInt(br.readLine());
}
ElecTotal = Integer.parseInt(br.readLine());
while((ElecTotal<0 || ElecTotal>100))
{
System.out.println("\n\tInvalid marks.....");
ElecTotal = Integer.parseInt(br.readLine());
while((Theory<0 || Theory>100))
System.out.println("\n\tInvalid marks.....");
Practicals = Integer.parseInt(br.readLine());
while((Practicals<0 || Practicals>100))
System.out.println("\n\tInvalid marks.....");
Practicals = Integer.parseInt(br.readLine());
}
CalculateGrade();
{
System.out.println("\nEnter name: ");
System.out.println("----------------------");
double percentage;
System.out.println("Result:");
System.out.println("Grade:A");
System.out.println("Grade:B");
System.out.println("Grade:C");
System.out.println("Grade:PASS");
else
System.out.println("Grade:FAIL\n\tTry Again..........");
st.getdata();
Slip15_1: Accept the names of two files and copy the contents of the first to the second. First file
havingBook name and Author name in file.
import java.io.*;
import java.util.*;
class demoFile
String f1=sc.next();
String f2=sc.next();
int ch;
while((ch=fis.read())!=-1)
{
fos.write(ch);
System.out.println("file copied...");
fis.close();
fos.close();
}
}
Slip16_1: Write a program to find the Square of given number using function interface.
interface Square {
int calculate(int x);
}
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);
}
}
import javax.swing.*;
import java.awt.*;
class MeEx
{
JMenu File;
JMenu Edit;
JMenu About;
JMenuItem i1, i2, i3, i4, i5;
MeEx(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
File=new JMenu("File");
Edit=new JMenu("Edit");
About=new JMenu("About");
i1=new JMenuItem("New Ctrl+N");
i2=new JMenuItem("Open");
i3=new JMenuItem("Save");
i4=new JMenuItem("Show About");
i5=new JMenuItem("Exit");
File.add(i1); File.add(i2);
File.add(i3);File.addSeparator();File.add(i4);File.addSeparator();File.add(i5);
mb.add(File);
mb.add(Edit);
mb.add(About);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MeEx();
}
}
import java.util.*;
class Customer {
String name;
int Pno;
}
class Depositer extends Customer
{
int accno;
double bal;
}
class Borrower extends Depositer
{
int loanno;
double loanamt;
void read()
{
System.out.println("enter name, Phone number, accno, bal, loanno,
loanamt");
Scanner sc = new Scanner(System.in);
this.name = sc.next();
this.Pno = sc.nextInt();
this.accno = sc.nextInt();
this.bal = sc.nextDouble();
this.loanno = sc.nextInt();
this.loanamt = sc.nextDouble();
}
void display()
{
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("------------------------------------");
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();
import java.awt.*;
import javax.swing.*;
class FrameDemo extends JFrame
{
FrameDemo()
{
JButton b1=new JButton("North");
JButton b2=new JButton("South");
JButton b3=new JButton("East");
JButton b4=new JButton("West");
JButton b5=new JButton("Center");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(b1,BorderLayout.NORTH);
add(b2,BorderLayout.SOUTH);
add(b3,BorderLayout.EAST);
add(b4,BorderLayout.WEST);
add(b5,BorderLayout.CENTER);
setSize(300,300);
setVisible(true);
}
public static void main(String[] args)
{
FrameDemo ob=new FrameDemo();
}
}
Slip18_2:
import java.util.Scanner;
class cricket
{
int inning, tofnotout, totalruns;
String name;
float batavg;
int i;
cricket()
{
name= null;
inning= 0;
tofnotout= 0;
totalruns=0;
batavg= 0;
}
void get()
{
Scanner s1= new Scanner(System.in);
System.out.println("name, no of innings, no of time(s) not out, total runs");
name= s1.nextLine();
inning= s1.nextInt();
tofnotout= s1.nextInt();
totalruns= s1.nextInt();
}
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;
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[])
{
int m, n, i, j,sum=0;
Scanner sc=new Scanner(System.in);
}
}
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
{
import java.util.*;
class continent
{
String c1;
}
class country extends continent
{
String c2;
}
}
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
package operation;
import java.util.*;
class Addition
{
}
public void add()
{
ans=n1+n2;
System.out.println("addition is="+ans);
}
answer=num1-num2;
System.out.println("subtraction is="+answer);
}
}
public class Maximum extends Addition
{
MainFile
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();
ob1.add();
ob1.sub();
ob1.max();
}
}
Slip21_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.
import java.util.*;
}
class MyDate
{
int day,month,year;
public void accept()
{
System.out.println("Enter Date, Month and Year");
try
{
Scanner sc=new Scanner(System.in);
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)
{
}
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);
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).
import java.util.*;
abstract class Shape
{ int n1,n2;
public abstract void printArea();
}
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);
ob.printArea();
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
{
String str="";
JTextArea ta;
Container c;
int x,y;
MouseEvents()
{
c=getContentPane();
c.setLayout(new FlowLayout());;
}
public void mouseClicked(MouseEvent me)
{
int i=me.getButton();
if(i==1)
str+="Clicked Button: Left";
else if(i==2)
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)
}
public void mousePressed(MouseEvent me)
{
x=me.getX();
y=me.getY();
str+="MousePressed at: "+x+"\t"+y;
this.display();
}
public void mouseReleased(MouseEvent me)
{
x=me.getX();
y=me.getY();
str+="Mouse Released at:"+x+"\t"+y;
this.display();
}
public void mouseDragged(MouseEvent me)
{
x=me.getX();
y=me.getY();
str+="MouseDragged at:"+x+"\t"+y;
this.display();
}
public void mouseMoved(MouseEvent me)
{
x=me.getX();
y=me.getY();
str+="Mouse Moved at:"+x+"\t"+y;
this.display();
}
public void display()
{
ta.setText(str);
str="";
}
public static void main(String[] args) {
import java.util.*;
class slip23_1
{
private int data;
slip23_1()
{
data=0;
}
slip23_1(int data)
{
this();
this.data=data;
}
public void isPositive(int x)
{
if(x>0)
{
System.out.println(x+" Number is Positive ");
}
}
public void isNegetive(int x)
{
if(x<0)
{
System.out.println(x+" Number is Negetive");
}
}
public void isEven(int x)
{
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 ");
}
}
}
Slip23_2: Write a simple currency converter, as shown in the figure. User can
enter the amount of "Singapore Dollars", "US Dollars", or "Euros", in
floating-point number. The convertedvalues shall be displayed to 2 decimal
places. Assume that 1 USD = 1.41 SGD,
1 USD = 0.92 Euro, 1 SGD = 0.65 Euro
import javax.swing.*;
import java.util.*;
import java.text.*;
import java.awt.*;
import java.awt.event.*;
}
catch(Exception e)
{
System.out.println("Enter Vaules in Box");
}
}
public static void main(String []args)
{
slip23_2 ob=new slip23_2();
Scanner sc=new Scanner(System.in);
{
int bal=100;
}
}
int bal=150;
int bal=200;
a.getBalance();
b.getBalance();
c.getBalance();
}
Slip24_2: Program that displays three concentric circles where ever the user clicks the
mouse on a frame.
The program must exit when user clicks ‘X’ on the frame.
import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.*;
import java.awt.event.*;
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)
{
g.setColor(Color.red);
g.fillOval(x-r1, y-r1, 2*r1, 2*r1);
int r2 =(int) ((d.width < d.height)? 0.3*d.width: 0.3* d.height);
g.setColor(Color.blue);
g.fillOval(x-r2, y-r2, 2*r2, 2*r2);
int r3= (int) ((d.width < d.height)? 0.2*d.width: 0.2 *d.height);
g.setColor(Color.yellow);
g.fillOval(x-r3, y-r3, 2*r3, 2*r3);
}
// to choose polygon to draw
public static void main(String[] args)
{
Ovals ovalsPanel = new Ovals();
JFrame newFrame = new JFrame();
newFrame.getContentPane().add(new Ovals());
newFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); //
newFrame.add( ovalsPanel );
newFrame.setSize( 550, 550 );
newFrame.setVisible(true);
}
}
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
System.out.println("Enter name:");
String name = br.readLine();
String number=br.readLine();
System.out.println("Enter percentage:");
String marks=br.readLine();
System.out.println("Enter class");
String classname=br.readLine();
System.out.println("name:"+name);
System.out.println("Roll No.:"+number);
System.out.println("Marks:"+marks);
System.out.println("Class:"+classname);
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
a textbox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
tf1=new JTextField();
rb1=new JRadioButton("FY");
rb2=new JRadioButton("SY");
rb3=new JRadioButton("TY");
rb1.addActionListener(this);
rb2.addActionListener(this);
rb3.addActionListener(this);
bg=new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
bg.add(rb3);
cb1=new JCheckBox("Music");
cb2=new JCheckBox("Dance");
cb3=new JCheckBox("Sports");
cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
p1=new JPanel();
p1.setLayout(new GridLayout(1,2));
p1.add(l1); p1.add(tf1);
p2=new JPanel();
p2.setLayout(new GridLayout(4,1));
p2.add(l2);
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);
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.WEST);
add(p3,BorderLayout.EAST);
add(p4,BorderLayout.SOUTH);
setTitle("INFORMATION");
setSize(500,300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
String s="NAME : "+tf1.getText()+ " CLASS : " +ae.getActionCommand();
l4.setText(s);
}
public void itemStateChanged(ItemEvent ie)
{
String s="";
if(cb1.isSelected())
s=s+cb1.getText()+" ";
if(cb2.isSelected())
s=s+cb2.getText()+" ";
if(cb3.isSelected())
s=s+cb3.getText()+" ";
l5.setText(" HOBBIES : "+s);
}
class Item
import java.io.*;
import java.util.*;
class Donor
{
String name, address,group;
int age, contact, lod;
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
{
int BasicSalary=35000;
public void getSalary()
{
System.out.println("Employee Salary:"+BasicSalary);
}
}
class Manager extends Employee
{
int traveling =2000;
int rent =5000;
System.out.println("Manager Salary:"+(BasicSalary+traveling+rent));
System.out.println("Basic Salary:"+BasicSalary);
System.out.println("Travaling Allowance:"+traveling);
System.out.println("House rent:"+rent);
}
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
}
}
Slip27_2: Write a program to accept a string as command line argument and check
whether it is a file ordirectory. 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.
import java.util.*;
import java.io.*;
class slip27_2
{
}
else if(f.isDirectory())
{
System.out.println("Sure you want Delete All Files (Press 1)");
int n=sc.nextInt();
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.
import java.util.*;
import java.io.*;
class FileReader
{
Scanner sc=new Scanner(System.in);
String f1=sc.next();
if(f.exists())
if(f.canRead())
System.out.println("File is Writeable");
else
else
import javax.swing.*;
import java.util.*;
import java.text.*;
import java.awt.*;
import java.awt.event.*;
}
public static void main(String []args)
{
slip28_2 ob=new slip28_2();
Scanner sc=new Scanner(System.in);
}
}
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
{
for(i=0;i<5;i++)
{
System.out.println("Enter cno,cname,cmob,cadd");
ob[i]=new Customer();
ob[i].cno=sc.nextInt();
ob[i].cname=sc.next();
ob[i].cmob=sc.next();
ob[i].cadd=sc.next();
}
String mb;
System.out.print("enter mob to search");
for(i=0;i<5;i++)
{
if(mb.equals(ob[i]).cmob)
{
System.out.println("Name"+ob[i].cname);
}
}
}
}
}
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 inappropriate form. While taking data, ask user about the type of vehicle
first.
import java.io.*;
class Vehicle
{
String company;
double price;
}
public void display()
{
System.out.println("Company: "+company+" Price: "+price);
}
}
class LightMotorVehicle extends Vehicle
{
double mileage;
public void accept() throws IOException
{
super.accept();
System.out.println("Enter the mileage of the vehicle: ");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
mileage=Double.parseDouble(br.readLine());
}
public void display()
{
super.display();
System.out.println("Mileage: "+mileage);
}
}
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)
{
case 1:
System.out.println("Enter the number of Light vehicles: ");
int n=Integer.parseInt(br.readLine());
LightMotorVehicle [] l=new LightMotorVehicle[n];
for(i=0;i<n;i++)
{
l[i]=new LightMotorVehicle();
l[i].accept();
}
for(i=0;i<n;i++)
{
l[i].display();
}
break;
case 2:
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]=new HeavyMotorVehicle();
h[i].accept();
}
for(i=0;i<m;i++){
h[i].display();
}
break;
}
}
import java.util.*;
class person
{
String Personname;
int Adharno, Panno;
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
Result.setText(ans+" ");
}
catch(NumberFormatException e)
{
System.out.println("Enter a valid number!");
}
www.nrclassespune.com | www.bcsbca.com
Subscribe to our YouTube Channel for BCS Study videos
https://www.youtube.com/@NRClasses
Click on the below link to join our Free Study Material WhatsApp Group
https://chat.whatsapp.com/J8vwXvDl2EW9htNH0LckU9