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

Java Programming Exercises for Beginners

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)
31 views94 pages

Java Programming Exercises for Beginners

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

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 = [Link];
int[] array = new int [size];
for(int i=0; i<size; i++)

[Link](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 [Link].*;
abstract class Staff
{
protected int id;
protected String name;
public Staff(int id,String name)
{
[Link]=id;
[Link]=name;
}
}
class OfficeStaff extends Staff
{
String dept;
OfficeStaff(int id,String name,String dept)
{

[Link]("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 = [Link](args[2]);

[Link]("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([Link]));
[Link]("Enter the name, no of innings, no of times not out, total runs:
"); name=[Link](); inning=[Link]([Link]());
tofnotout=[Link]([Link]());
totalruns=[Link]([Link]());
}
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;
[Link]("Enter the limit:");

int n=[Link]([Link]()); Cricket c[]=new Cricket[n]; for(int i=0;i<n;i++){


c[i]=new Cricket();

}
[Link](n,c);
[Link](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 [Link];

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;
}
}
}
[Link]("\nSorted names are in Ascending Order: ");
for(int i=0;i<N;i++)
{
[Link](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.
[Link]("Patient is Covid Positive and needs to be hospitalized");

String name;

[Link]=age;

String name;

}
}

double level,hrct;
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter name: "); name=[Link]();
[Link]("Enter the age: ");
age=[Link]([Link]()); [Link]("Oxygen
level: "); level=[Link]([Link]());
[Link]("HRCT report: ");
hrct=[Link]([Link]()); Patient ob=new
Patient(name,age,level,hrct); try{
if([Link]<95 && [Link]>10)

throw new CovidException();

else
[Link]("Patient Info: \n"+"Name: "+[Link]+"\nAge: "+[Link]+"\nHRCT
report: "+[Link]+"\nOxygen level:"

dimensional array.

{
for(int j=0;j<c;j++)
{
mat[i][j] =
[Link]();
}
}
[Link]("the matrix is:"); for(int
i=0;i<c;i++)
{
for(int
j=0;j<r;j++)
{
[Link](" " +mat[j][i]);
}
[Link](" ");
}

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: "
,[Link]); upass=new Label ("Password:
",[Link]); nametext=new TextField(20);
passtext =new TextField(20);
[Link](c); msg=new TextField(10);
[Link](false); login=new
Button("Login");
Clear=new Button("Clear");
[Link](this);
[Link](this); [Link](uname);
[Link](nametext);
[Link](upass);
[Link](passtext);
[Link](login);
[Link](Clear);
[Link](msg); add(p);

Button btn=(Button)([Link]());

[Link]("");

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

String user=[Link]();

{
[Link]("Valid");
[Link]("Username is valid");
}
else
{
throw new InvalidPasswordException();
}
}
catch(Exception e)
{
[Link]("Error");
}
attempt++;
}
}
else
{
[Link]("you are using 3 attempt");
[Link](0);
}

}
}

InputStreamReader i = new InputStreamReader([Link]); BufferedReader r = new


BufferedReader(i);

void con_input() throws IOException


}
}

class Country extends Continent


{ String
cou;
void cou_input()throws IOException
{
[Link]("Enter the country name:"); cou
= [Link]();}
}
class State extends Country
{

String sta;
void sta_input()throws IOException
{
[Link]("Enter the state name:");
sta = [Link]();} }
import [Link].*;
class Matrix
{
Scanner sc = new Scanner([Link]); int a =
[Link](); int b = [Link](); int M[][] = new
int[a][b];
void accept()
{
int a = this.a; int b = this.b;
[Link]("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] = [Link]();
}

}
}

[Link]("enter size 2*2 or 3*3 or ...");

[Link]("values to matrix 1:");

[Link]("enter the size:");


Matrix m2 = new Matrix();

[Link]("values to matrix 2:");

int choice;
Scanner scanner = new Scanner([Link]);
while(true) {
[Link]("Press 1: Addition, 2: Multiplication, 3: Exit");
choice = [Link]();
switch (choice) { case 1:
[Link]("Addition is:" );
for(int i=0;i<m1.a;i++)
{
for(int j=0;j<m1.b;j++)
{
[Link](" "+ (m1.M[i][j]+m2.M[i][j]));
}
[Link](" ");
}
break; case 2:
[Link]("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");
[Link]("Employee details: "+E1);
[Link]("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 [Link]; import [Link]; import
[Link]; abstract class Order{

}
}

String cnm, vnm;


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

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

case 3:
[Link]("exit:");
[Link](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); [Link](250);
[Link]("the withdraw is:"+ [Link]); [Link](400);
[Link]("the deposit is:"+ [Link]);
[Link]("the balance is:"+ [Link]());
}
}

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

[Link](ch);
[Link]();
}
[Link]();
}
else
[Link]("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 [Link].*; class


Sphere
{
public static void main (String[] args)
{
Scanner sc=new Scanner([Link]);
[Link]("Enter the radius of the sphere: ");
double radius=[Link]();
double surface_area = (4*3.14*(radius*radius));
double volume = ((double)4/3)*3.14*(radius*radius*radius);
[Link]("The surface area of the sphere = "+surface_area);
[Link]("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 [Link].*;
import [Link].*;
class MyFrame extends Frame
{
TextField t,t1;
Label l,l1;

MyFrame(String title)

super(title);
setLayout(new FlowLayout());
p=new Panel();
[Link](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);
[Link](l);
[Link](t);
[Link](l1);
[Link](t1);
add(p);
addMouseListener(new MyClick());
addMouseMotionListener(new MyMove());
setSize(500,500);
setVisible(true);
}
class MyClick extends MouseAdapter
{
public void mouseClicked(MouseEvent me)
{
x=[Link]();
y=[Link]();

}
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 [Link].*; class
Clock
{
int hours,minutes,seconds;
Clock()
{
[Link]("enter the time in HH MM SS format");
Scanner sc= new Scanner([Link]);
[Link] = [Link]();
[Link] = [Link]();
[Link] = [Link]();
}
void isTimeValid()
{
if(hours>=0 && hours<24 && minutes>0 &&minutes<60
&&seconds>0 && seconds<60)
[Link]("time is valid");
else
[Link]("time is not valid");
}
}

count.

import [Link].*;

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([Link]);

[Link]("Enter Number of Product : ");


int n = [Link]();

product pr[] = new product[n];


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

[Link]("\nEnter " + (i + 1) + " Product Details :\n");


[Link]("Enter Product ID: ");
int pid = [Link]();

[Link]();
[Link]("Enter Product Name: ");
String pn = [Link]();

[Link]("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 [Link].*;

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

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

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([Link]);


[Link]("Enter Roll no:= "); roll
= [Link]();
[Link]("Enter Name:= ");
nm = [Link]();
[Link]("Enter class:= "); clas=
[Link]();

int m1,m2,m3,m4,m5,m6;
[Link]("Enter 6 sub mark:= ");
m1 = [Link]();
m2 = [Link](); m3
= [Link]();
m4 = [Link]();
m5 = [Link]();
m6 = [Link]();

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

[Link]();
}
}

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 [Link].*;

BufferedReader br = new BufferedReader(new InputStreamReader([Link]));

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


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

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 [Link].*; import


[Link].*; import
[Link].*;
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");
[Link](this);
[Link](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([Link](pass)==0)

[Link](0);
}
else
{
throw new InvalidPasswordException();
}
}
catch(Exception e1)
{
cnt++;
[Link](null, "Login Failed", "Login",
JOptionPane.ERROR_MESSAGE);
[Link]("");
[Link]("");
[Link]();
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([Link]); public void
accept()
{

name=[Link]();

dname=[Link]();

[Link]("college name"+name);
[Link]("college address"+addr);

}
public static void main(String a[])
{
Dept ob=new Dept();
[Link]();
[Link]();
}
}
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 [Link].*; import
[Link].*;
import [Link].*;

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); [Link](t);
p1=new JPanel(); [Link](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="">


{
[Link](b[i]);
}

[Link](equals); [Link](add);
[Link](sub); [Link](mul);
[Link](div); [Link](clear);

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


{
b[i].addActionListener(this);
}
[Link](this); [Link](this);
[Link](this); [Link](this);
[Link](this); [Link](this);

add(p,[Link]); add(p1);

public void actionPerformed(ActionEvent ae)


{
String str = [Link](); char ch =
[Link](0); if ( [Link](ch))
[Link]([Link]()+str); else
if([Link]("+"))
{
v1=[Link]([Link]()); choice='+';
[Link](""); }
else if([Link]("-"))
{
v1=[Link]([Link]()); choice='-';
[Link](""); }
else if([Link]("*"))
{
v1=[Link]([Link]()); choice='*';
[Link](""); }
else if([Link]("/"))
{ v1=[Link]([Link]()); choice='/';
[Link]("");
}
if([Link]("="))
{
v2=[Link]([Link]()); 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([Link]())

FileInputStream fis=new FileInputStream(fname);

int ch,cnt=0;

while((ch=[Link]())!=-1)
{

if(ch=='\n')

cnt++;

}
}

[Link]("Number of line in Given file is "+cnt);

import [Link];

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

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


String strDate1= [Link](date);
[Link](strDate1);

SimpleDateFormat formatter2 = new SimpleDateFormat("EEEEE


MMMMM dd yyyy");
String strDate2= [Link](date);
[Link](strDate2);

SimpleDateFormat formatter3 = new SimpleDateFormat("EEEEE


MMMMM dd HH:mm:ss z yyyy");
String strDate3= [Link](date);
[Link](strDate3);

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


HH:mm:ss a");
String strDate4= [Link](date);
[Link](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 [Link]; import


[Link].*;
class Zerono extends Exception
{}

int no,i,j;
Scanner sc=new Scanner([Link]);
try
{
[Link]("enter no");
no=[Link]();
if(no==0)
throw new Zerono();
if(no>0)
{
for(i=2;i<=no/2;i++)
{
if(no%i==0)
{
count++;
}

}
}
if(count==0)
[Link]("No is Prime");
else

int ct,mt,et; public SYMarks(int

ct,int mt,int et)

[Link]=ct;

[Link]=mt;

[Link]=et;
}
public void display()
{
[Link]("\nMarks are;");

[Link]("Computer\tMaths\tElectronics");

[Link](ct+"\t"+mt+"\t"+et);

[Link]("Theory\tPracticals");

[Link](Theory+"\t"+Practicals);

}
}
Mainfile import
[Link]; import
[Link];
import [Link].*;
class SYTY
{
int rollno;

int ComputerTotal, MathsTotal, ElecTotal, Theory, Practicals;

String name;

[Link]("Enter SY marks: ");

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

[Link]("\n\tInvalid marks.....");

[Link]("Please ReEnter the marks: ");

ComputerTotal = [Link]([Link]());
}
[Link]("\nEnter maths marks");

MathsTotal=[Link]([Link]());

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

[Link]("\n\tInvalid marks.....");

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

[Link]("\nEnter TY marks: ");

[Link]("\nEnter theory marks ");


Theory = [Link]([Link]());
while((Theory<0 || Theory>100))
{
[Link]("\n\tInvalid marks.....");

[Link]("Please Reenter the marks: ");


Theory = [Link]([Link]());

CalculateGrade();

public void getdata() throws Exception


{
[Link]("\nEnter number of students: ");
int n=[Link]([Link]());
SYTY object[]=new SYTY[n];

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

[Link]("\nEnter name: ");

public void CalculateGrade()

percentage = (ComputerTotal+ MathsTotal + ElecTotal + Theory +


Practicals)/5;

[Link]("Result:");

if(percentage >= 70)

[Link]("Grade:A");
else if(percentage >= 60)

[Link]("Grade:B");

else if(percentage >= 50)


[Link]("Grade:C");

else if(percentage >= 40)

Book name and Author name in file.

import [Link].*; import


[Link].*;

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

[Link]("Enter the first file");

String f1=[Link]();

[Link]("Enter the second file");

String f2=[Link]();

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 = [Link](a);
[Link](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 [Link].*;
class Customer {
String name;
int Pno;
}
class Depositer extends Customer
{
}

[Link]("The details are:");


[Link]("name: " +[Link]);
[Link]("phone number: "+[Link]);
[Link]("accout number: " +[Link]);
[Link]("Balance: " +[Link]);
[Link]("loan number: "+[Link]);
[Link]("loan amount: "+[Link]);
[Link]("------------------------------------");

public static void main(String args[]){


int i;
Scanner sc = new Scanner([Link]);
[Link]("enter total number:");
int n =[Link]();
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 [Link].*; import


[Link].*; import
[Link].*;
class TextField implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextField(){
JFrame f= new JFrame();
tf1=new JTextField();
[Link](50,50,150,20);
tf2=new JTextField();
[Link](50,100,150,20);
tf3=new JTextField();
[Link](50,150,150,20);
[Link](false); b1=new
JButton("concatenation");
[Link](30,200,100,50);
b2=new JButton("reverse");
[Link](150,200,100,50);
[Link](this);
[Link](this);
[Link](tf1);[Link](tf2);[Link](tf3);[Link](b1);[Link](b2);
[Link](300,300);
[Link](null);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
StringBuffer sb = new StringBuffer();
String s1=[Link]();
String s2=[Link]();
if([Link]()==b1){
String s3= s1+s2;
[Link](s3);
}else if([Link]()==b2){
String str = s1;
String strArray = "";
for (int i = [Link]()-1; i>=0 ; i--){
strArray+=[Link](i);
}
[Link](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 [Link]; class
cricket
{
int inning, tofnotout, totalruns;

}
void put()
{
[Link]("name: "+name);
[Link]("no of innings: "+inning);
[Link]("no of time(s) not out: "+tofnotout);
[Link]("total runs: "+totalruns);
[Link]("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([Link]);
[Link]("Enter The Limit: ");
int n= [Link](); cricket
c[]= new cricket[n];
for(int i=0; i<n; i++)
{
c[i]= new cricket();
c[i].get();
}
[Link](n, c);
[Link](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 [Link]; class


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

}
}

Slip19_2: Write a program which shows the combo box which includes list of
[Link].(Comp. Sci) subjects. Display the selected subject in a text field

import [Link].*; import


[Link].*;
import [Link].*; class
ComboBoxExample
{
JFrame f;
JTextField t1;
ComboBoxExample()
{
f=new JFrame("ComboBox Example");
final JLabel label = new JLabel(); t1=new
JTextField(10);
[Link]([Link]);
[Link](400,100);
JButton b=new JButton("Show");
[Link](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 [Link].*;
class continent
{
String c1;

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

public void display()


{
[Link]("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


[Link].*;
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;
[Link]("addition is="+ans);
}

public void sub()

else
[Link](n2+" is greater than "+n1);
import [Link];

import [Link].*;
class Arithmatic
{
public static void main (String args[])
{
int n1,n2; float num1,num2;
Scanner sc=new Scanner([Link]);
[Link]("Enter first no="); n1=[Link]();
[Link]("Enter second no="); n2=[Link]();
[Link]("Enter third no=");
num1=[Link]();
[Link]("Enter fourth no=");
num2=[Link]();

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

[Link]();
[Link]();
[Link]();

{
[Link]("Enter Date, Month and Year");

day=[Link](); if(day<1 ||
day>31) throw new
InvalidDateException();
month=[Link](); if(month>12
||month<1) throw new
InvalidDateException();
year=[Link]();
if(year>10000 ||year<1000) throw
new InvalidDateException();
}
catch(InvalidDateException e)
{
[Link]("Invalid Date entered");
[Link](0);
}
catch(Exception e)
{
[Link]("Enter Valid Date");
[Link](0);
}
}
public void display()
{
[Link]("Entered Date is "+day+":"+month+":"+year);

double sal; static int

cnt=0;
Employee()
}
Employee(int id,String name,String deptname,double sal)
{
[Link]=id;
[Link]=name;
[Link]=deptname;
[Link]=sal;
cnt++;
displayCount();
}
public static void displayCount()
{
[Link]("Total Objects created "+cnt);

}
public void displayData()
{

[Link]([Link]+"\t\t"+[Link]+"\t\t\t"+[Link]+"\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);
[Link]("EID\t\tName\t\t\tDepartment\t\tSalary");
[Link](); [Link]();
[Link]();
}
}

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;
[Link]("area of rectangle="+area);
}
}
class Triangle extends Shape
{
Triangle(int a,int b)
{
n1=a;
n2=b;
}
public void printArea()
{
{

[Link]();

Triangle tr=new Triangle(n1,n2);


[Link]();

Circle cr=new Circle(n1);


[Link]();
}
}

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 [Link].*; import


[Link].*; import
[Link].*;
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";
[Link]();

}
public void mouseEntered(MouseEvent me)
{
str+="Mouse Entered ";
[Link]();
}
public void mouseExited(MouseEvent me)
{
str+="MouseExited"; [Link]();

}
public void mousePressed(MouseEvent me)
{
x=[Link]();
y=[Link]();
str+="MousePressed at: "+x+"\t"+y; [Link]();
}

x=[Link]();
y=[Link]();

x=[Link]();
y=[Link]();

x=[Link]();
y=[Link]();
str+="Mouse Moved at:"+x+"\t"+y;

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

MouseEvents mes=new MouseEvents();


[Link](400,400); [Link](true);
[Link](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 [Link]
command line arguments to pass a value to the Object

import [Link].*;
class slip23_1
{
private int data;

slip23_1()

{
[Link](x+" Number is Negetive");
if(x%2==0)
{
[Link](x+" Number is Even");
}
}
public void isOdd(int x)
{
if(x%2!=0)
{
[Link](x+" Number is Odd ");
}
}
public void isZero(int x)
{
if(x==0)
{
[Link](x+" Number is Zero ");
}
}
public static void main(String args[])
{
int data=[Link](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);
[Link](l1); [Link](t1);
[Link](l2); [Link](t2);
[Link](l3); [Link](t3);
[Link](true);
[Link](this);
[Link](new FlowLayout());
[Link](400,400);
[Link](3);
}

public void keyReleased(KeyEvent ke)


{
try
{
Double USD=[Link]([Link]());
[Link](""+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()

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

[Link]();
[Link]();
[Link]();

import [Link].*;

import [Link]; 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 =[Link]/2;
int y = [Link]/2;
int r1=(int) (([Link] < [Link])? 0.4*[Link]: 0.4*[Link]);

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

import [Link].* ;

class Student

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

{
InputStreamReader r=new InputStreamReader([Link]);

BufferedReader br=new BufferedReader(r);


[Link]("Enter name:");
String name = [Link]();

[Link]("Enter roll no.:");

String number=[Link]();

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");

[Link](new GridLayout(1,2));

[Link](rb1);
[Link](rb2);
[Link](rb3);

p3=new JPanel();
[Link](new GridLayout(4,1));
[Link](l3);
[Link](cb1);
[Link](cb2);
[Link](cb3); p4=new JPanel();
[Link](new GridLayout(1,2));
[Link](l4);
[Link](l5);

BorderLayout bob=new BorderLayout();


setLayout(bob);

add(p1,[Link]);
add(p2,[Link]);
add(p3,[Link]);

add(p4,[Link]);

setTitle("INFORMATION");
setSize(500,300);
if([Link]())
s=s+[Link]()+" ";

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()
{
[Link]("Total objects created "+count);
[Link](ino+" "+iname+" "+iprice);
}
public static void main(String args[])
{
Item ob1=new Item(1,"Laptop",20000.00);
[Link]();
Item ob2=new Item(1,"Laptop",20000.00);
[Link]();
}
}
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)


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

public static void main(String args[])


{
Scanner s=new Scanner([Link]);
[Link]("Enter how many records you want");
int n=[Link](); try {
ObjectOutputStream o=new ObjectOutputStream(new FileOutputStream("[Link]"));

catch(IOException e)
{

for(int i=0;i<n;i++)
{
Donor d=(Donor)[Link](); if([Link]("A+ve")&&[Link]>=6)
[Link](d);
}
}
catch(Exception e)
{
[Link](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 [Link].*;
class Employee
{
}
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]);
[Link]("Press 1 for Employee Salary and 0 for Manager");
int ch=[Link](); if(ch==1)
{
Employee Eob=new Employee();
[Link]();
}
else if(ch == 0)
{
Manager Mob=new Manager();
[Link]();
}
else
[Link]("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=[Link]();
String a=".txt";
for(String str: s1)
{
[Link](str);
if([Link](a))
{
File f1=new File(fname, str);
[Link](str+"-->Deleted");
[Link]();
}
}

}
else
[Link]("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.

[Link]("Name of the File is "+[Link]());

if([Link]())

[Link]("File is Readable ");

else

[Link]("File is not Readable "); if([Link]())

[Link]("File is Writeable");

else

[Link]("File is not Writeable");


[Link]("Length of the File= "+[Link]());

import [Link].*; import


[Link].*; import
[Link].*;
import [Link].*;

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); [Link](l1); [Link](t1);
[Link](l2); [Link](t2);
[Link](true);
[Link](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 [Link];
class Customer
{

int cno;
String cname,cmob,cadd;

public static void main(String [] args)


{
int i=0;
{

Scanner sc = new Scanner([Link]);


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 [Link].*; class Vehicle


{
String company; double price;
public void accept() throws
IOException
{
[Link]("Enter the Company and price of the
Vehicle: ");
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
company=[Link]();
price=[Link]([Link]());

}
public void display()
{

[Link]("Mileage: "+mileage);
}

public void accept() throws IOException


{
[Link]();
[Link]("Enter the capacity of vehicle in tons: ");
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
captons=[Link]([Link]());
}
public void display()
{
[Link]();
[Link]("Capacity in tons: "+captons);
}
}
class Sa3
{
public static void main(String [] args) throws IOException
{
int i;
[Link]("Enter the type of vehicle: ");
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
[Link]("[Link] Vehicle");

[Link]("[Link] Vehicle"); int


ch=[Link]([Link]());
switch(ch)
[Link]("Enter the number of Heavy vehicles: ");
int m=[Link]([Link]());
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 [Link].*;
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 [Link].*;
import [Link].*; import
[Link].*;
class Division extends JFrame implements ActionListener
{

JLabel l1,l2,Result;

setLayout(new FlowLayout());
[Link](this);
setVisible(true);
setSize(300,400);
int v1=[Link]([Link]());
int v2=[Link]([Link]());
int ans=v1/v2;

[Link](ans+" ");
}
catch(NumberFormatException e)
{
[Link]("Enter a valid number!");
}

catch(ArithmeticException o)
{
[Link]("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

Common questions

Powered by AI

The program uses the File class to accept a filename from the user and checks properties such as existence, readability, and writability. It then displays relevant information about the file, including its type and byte length, showcasing systematic file handling .

The Matrix class uses a Scanner to record dimensions and elements of the matrix. It then iterates over these inputs, storing them in a two-dimensional array and printing them in a structured format, demonstrating basic input-output handling with matrices .

The inheritance structure uses a multilevel approach where the class 'country' extends 'continent', and 'state' extends 'country'. This hierarchical relationship allows each class to inherit attributes and methods from its predecessor, facilitating the modeling of place-based information .

The Division program sets up a JFrame with text fields for input and a button for executing division. Action listeners are attached to handle division and exception cases like ArithmeticException and NumberFormatException. Results are displayed using a JLabel, emphasizing error handling and user feedback .

The CricketPlayer class utilizes a static method avg() to calculate the batting average by dividing total runs by the number of innings for each player. It then employs a static sort method to arrange the players based on their batting averages in descending order .

The Patient class uses conditional checks within a try-catch block to handle medical evaluations. It throws a custom exception if the patient's oxygen level is below 95 and their HRCT report exceeds 10, demonstrating defensive programming techniques to flag critical conditions .

The program checks if the patient's oxygen level is below 95% and their HRCT scan report is greater than 10. If both conditions are met, it throws a user-defined exception indicating that the patient is Covid positive and needs hospitalization .

The program uses a Scanner to take user inputs for matrix size and values. It provides options for addition and multiplication through a menu system implemented with a while loop and a switch case structure, allowing the user to choose the operation until they decide to exit .

The Item class uses a static variable to maintain a count of the number of instances created. As each new object is instantiated using the parameterized constructor, the count is incremented, demonstrating the use of static fields to manage class-level data .

The SalesOrder class extends the abstract Order class by implementing additional attributes such as vendor name. It also provides specific implementations of the abstract methods, accept() and display(), to incorporate vendor-related functionality while leveraging the base logic from the Order class .

You might also like