Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 42

Assignment No.

1. Write a Java program to create a class Person which contains data members as
P_Name, P_City, P_Contact_Number. Write methods to accept and display two
Persons information.

Answer :

Program :

import java.io.*;
class Person{
String P_Name;
String P_City;
String P_Contact_Number;
void accept()throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter Person Name :- ");
P_Name = br.readLine();
System.out.println("Enter Person City :- ");
P_City = br.readLine();
System.out.println("Enter Person Contact Number :- ");
P_Contact_Number = br.readLine();
}
void display(){
System.out.println("Person Name = "+P_Name);
System.out.println("Person City = "+P_City);
System.out.println("Person Contact Number = "+P_Contact_Number);
}
}
class PersonInformation{
public static void main(String args[])throws IOException{
Person p1 = new Person();
Person p2 = new Person();
p1.accept();
p1.display();
p2.accept();
p2.display();
}
}
Output:
2. Define a class ‘Month’ having data members: name, total_days and
total_holidays. Define appropriate methods to initialize and display the
values of these data members. Input values for two objects and determine
which month is having maximum working days.

Answer :

Program :

class Month{
String name;
int total_days;
int total_holidays;
void accept(String n, int td, int th){
name = n;
total_days = td;
total_holidays = th;
}
void display(){
System.out.println("Name = "+name);
System.out.println("Total Days = "+total_days);
System.out.println("Total Holidays = "+total_holidays);
}
int MaxWork(){
return total_days-total_holidays;
}
}
class MaxWorkDay{
public static void main(String args[])throws IOException{
Month m1 = new Month();
Month m2 = new Month();
int day1;
int day2;
m1.accept("May", 31, 100);
m2.accept("Jun", 30, 6);
m1.display();
m2.display();
day1 = m1.MaxWork();
day2 = m2.MaxWork();
if(day1>day2){
System.out.println(m1.name+" have maximum working days.");
}
else{
System.out.println(m2.name+" have maximum working days.");
}
}
}

Output :
3. Define a class Shape having overloaded member function area() to calculate and
display area of Square and Rectangle

Answer :

Program :

class Shape{

void area(double s){

double a;

a = s*s;

System.out.println("Area of Square = "+a);

void area(double l, double w){

double a;

a = l*w;

System.out.println("Area of Rectangle = "+a);

class AreaOf{

public static void main(String args[]){

Shape ob = new Shape();

ob.area(42);

ob.area(84, 54);

}
Output :
4. Define a class ‘Salary’ which will contain data members basic, TA, DA, HRA.
Write a program using constructors which will initialize these values for object.
Calculate total salary of the employee using the method.

Answer :

Program :

class Salary{

double basic;

double TA;

double DA;

double HRA;

Salary(){

basic = 30000;

TA = 3000;

DA = 2000;

HRA = 4000;

double TotalSalary(){

return (basic+TA+DA+HRA);

class SalaryCalculation{

public static void main(String args[]){

double total;

Salary s = new Salary();

total = s.TotalSalary();

System.out.println("Total Salary = "+total);

}
Output :
5. Define a class Book having instance variables: name, totalPages, coverPrice and
author_name. Initialize theses values using constructor for four objects and
calculate average pages and average cover price.

Answer :

Program :

class Book{

String name;

String auther_name;

int totalPages;

int coverPrice;

Book(String n, String an, int tp, int cp){

name = n;

auther_name = an;

totalPages = tp;

coverPrice = cp;

void Display(){

System.out.println("Book Name = "+name);

System.out.println("Auther Name = "+auther_name);

System.out.println("Total Pages = "+totalPages);

System.out.println("Cover Price = "+coverPrice);

class BookDetails{

public static void main(String args[]){

Book b1 = new Book("Rich Dad Poor Dad", "Robert Kiyosaki", 887, 497);

Book b2 = new Book("The Theory Of Everything", "Stephen W Hawking", 754, 219);

Book b3 = new Book("Sherlock Holmes", "Conan Doyle", 985, 258);

Book b4 = new Book("The Lord Of Rings", "J. R. R. Tolkien", 781, 233);


int avtp;

int avcp;

b1.Display();

b2.Display();

b3.Display();

b4.Display();

avtp = (b1.totalPages+b2.totalPages+b3.totalPages+b4.totalPages)/4;

System.out.println("Average Pages = "+avtp);

avcp = (b1.coverPrice+b2.coverPrice+b3.coverPrice+b4.coverPrice)/4;

System.out.println("Average Price = "+avcp);

Output :
6. Write a java Program to accept ‘n’ no’s through the command line and store all
the prime no’s and perfect no’s into the different arrays and display both the
arrays.

Answer :

Program :

import java.io.*;

class CommandLineArray{

public static void main(String args[]){

int n=args.length;

int pr[]=new int[n];

int per[]=new int[n];

int k=0,i,j;

int sum=0;

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

for(j=2;j<Integer.parseInt(args[i]);j++){

if(Integer.parseInt(args[i])%j==0)

break;

if(Integer.parseInt(args[i])==j)

pr[k++]=Integer.parseInt(args[i]);

System.out.println("Prime Array = ");

for(j=0;j<k;j++){

System.out.print(" "+pr[j]);

k=0;

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

sum=0;

for(j=1;j<Integer.parseInt(args[i]);j++){
if(Integer.parseInt(args[i])%j==0){

sum=sum+j;

if(sum==Integer.parseInt(args[i])){

per[k++]=sum;

System.out.println("\nPerfect Array = ");

for(i=0;i<k;i++){

System.out.print(" "+per[i]);

Output :
7. 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.

Answer :

Program :

class Employee{

String name;

int sal ;

int id;

Employee(String n, int s, int i){

name = n;

sal = s;

id = i;

int getSalary(){

return sal;

class Manager extends Employee{

int hra, ta;

Manager(String n, int sal,int i, int h, int t){

super(n, sal, i);

hra = h;

ta = t;

int getSalary(){

return (super.getSalary()+hra+ta);

}
}

class EmpSal{

public static void main(String args[]){

Manager m1=new Manager("Jhony English", 45000, 101, 1000, 1500);

System.out.println("Manager Salary = "+m1.getSalary());

Output :
8. Define a class ‘Student’ having data members name and roll_no. Inherit class
‘Teacher’ from it to have data members name and subject. Derive one more
class from ‘Teacher’ called ‘Info’. All three classes contain the Overridden
method display to display respective information of the object. Input the data in
object using constructors.

Answer :

Program :

class Student{

String sname;

int roll_no;

Student(String sn, int rn){

sname = sn;

roll_no = rn;

void display(){

System.out.println("Student Name = "+sname);

System.out.println("Student Roll No = "+roll_no);

class Teacher extends Student{

String tname;

String subject;

Teacher(String sn, int rn, String tn, String s){

super(sn, rn);

tname = tn;

subject = s;

void display(){

System.out.println("Teacher Name = "+tname);

System.out.println("Teacher's Subject = "+subject);


}

class Info extends Teacher{

Info(String sn, int rn, String tn, String s){

super(sn, rn, tn, s);

void display(){

System.out.println("Student Name = "+sname);

System.out.println("Student Roll No = "+roll_no);

System.out.println("Teacher Name = "+tname);

System.out.println("Teacher's Subject = "+subject);

class Stud_Teach_Info{

public static void main(String args[]){

Info i = new Info("Jhon Wick", 12060, "Jack Sparrow", "Python");

i.display();

Output :
9. Create a class Shape which consists one final method area () and volume
().Create three subclasses Rect, Circle and Triangle and calculate area and
volume of it .Implement following inheritance. Use constructors to initialize the
objects.

Answer :

Program :

class Shape{

final void area(){

System.out.println("This is final");

void volume(){

System.out.println("This is volume");

class Rect extends Shape{

double lenght;

double width;

double height;

Rect(double l, double w, double h){

lenght = l;

width = w;

height = h;

void rarea(){

double a;

a = lenght*width;

System.out.println("Area of Rectangle = "+a);

void volume(){
double v;

v = lenght*width*height;

System.out.println("Volume of Rectangle = "+v);

class Circle extends Shape{

double radius;

Circle(double r){

radius = r;

void carea(){

double a;

a = 3.14*radius*radius;

System.out.println("Area of Circle = "+a);

void volume(){

double v;

v = 4/3*3.14*radius*radius;

System.out.println("Volume of Circle = "+v);

class Triangle extends Shape{

double base;

double heightt;

double a;

Triangle(double b, double w, double ht){

base = b;

heightt = ht;
}

void tarea(){

a = base*heightt/2;

System.out.println("Area of Triangle = "+a);

void volume(){

double v;

v = 0.5*base*heightt*a;

System.out.println("Volume of Rectangle = "+v);

class Rect_Cir_Tri{

public static void main(String args[]){

Rect r = new Rect(54, 85, 65);

r.rarea();

r.volume();

Circle c = new Circle(84);

c.carea();

c.volume();

Triangle t = new Triangle(78, 75, 38);

t.tarea();

t.volume();

}
Output :
10. Define an Interface Shape with abstract method area(). Write a java program
to calculate an area of Circle and Sphere.(use final keyword).

Answer :

Program :

import java.io.*;

interface Shape{

void area();

class Circle implements Shape{

final double PI = 3.14;

double a;

double r = 54;

public void area(){

a = PI*r*r;

System.out.println("Area of Circle = "+a);

class Sphere implements Shape{

final double PI = 3.14;

double a;

double r = 85;

public void area(){

a = 4*PI*r*r;

System.out.println("Area of Sphere = "+a);

class Cir_Sph_Interface{

public static void main(String args[])throws IOException{

Circle c = new Circle();


c.area();

Sphere s = new Sphere();

s.area();

Output :
11. Write a package for Games in Java, which have two classes Indoor and
Outdoor. Use a method display () to generate the list of players for the specific
games. (Use Parameterized constructor,  finalize() method and Array Of Objects)

Answer :

Program :

Indoor.java

package Games;

public class indoor{

protected String player;

public indoor(){

public indoor(String p){

player = p;

public void display(){

System.out.println(player);

protected void finalize(){

System.out.println("Terminating Indoor....");

outdoor.java

package Games;

public class indoor{

protected String player;

public indoor(){

}
public indoor(String p){

player = p;

public void display(){

System.out.println(player);

protected void finalize(){

System.out.println("Terminating Indoor....");

Players.java

import Games.*;

class Players{

public static void main(String args[]){

indoor in[] = new indoor[3];

System.out.println("Indoor Players...");

in[0] = new indoor("Mark Ruffalo");

in[1] = new indoor("Robert Downey");

in[2] = new indoor("Chris Evans");

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

in[i].display();

outdoor out[] = new outdoor[3];

System.out.println("Undoor Players...");

out[0] = new outdoor("Chris Hemsworth");

out[1] = new outdoor("Jeremy Renner");

out[2] = new outdoor("Paul Rudd");


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

in[i].display();

Output :
12. Write a java program to accept the details of  ‘n’ employees (EName ,Salary)
from the user, store them into the Hashtable and displays the Employee Names
having maximum Salary.

Answer :

Program :

import java.util.*;

import java.io.*;

public class Employee_Hashtable{

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

int n,sal=0;

String name;

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

Hashtable h = new Hashtable();

System.out.println("\nEnter number of Employee : ");

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

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

System.out.println("\nEnter Name of "+i+" :- ");

name = br.readLine();

System.out.println("\nEnter Salary "+i+" :-");

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

h.put(name,sal);

Enumeration v = h.elements();

Enumeration k = h.keys();

while(k.hasMoreElements()){

System.out.println(k.nextElement()+" "+v.nextElement());

int max = 0;

String str="";
k = h.keys();

v = h.elements();

while(v.hasMoreElements()){

sal=(Integer)v.nextElement();

name = (String)k.nextElement();

if(sal>max){

max = sal;

str = name;

System.out.println(str +" has maximum salary is "+max);

Output :
}

13. Write a java program to accept Employee name from the user and check
whether it is valid or not. If it is not valid then throw user defined Exception
“Name is Invalid” otherwise display it.

Answer :

Program :

import java.util.*;

import java.io.*;

class InvalidNameException extends Exception{

class InvalidNameExc{

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

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


System.out.println("Enter the name :- ");

String name = br.readLine();

try{

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

int ch=(int)name.charAt(i);

if((ch>=65 && ch<=90) || (ch>=97 && ch<=122)){

else{

throw new InvalidNameException();

System.out.println("Employee Name = "+name);

catch(InvalidNameException e){

System.out.println("Invalid User Name");

Output :
14. Write a java program to accept n names of cites from user and display them
in descending   order.

Answer :

Program :

import java.util.*;

class City{

String a[];

int n;

City(){

Scanner s=new Scanner(System.in);

System.out.print("Enter how many city you want to enter : ");

n=s.nextInt();

a=new String[n];
for(int i=0;i<n;i++){

System.out.print("Enter "+(i+1)+" element: ");

a[i]=s.next();

void display(){

String temp="";

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

for(int j=i+1;j<n;j++){

if(a[i].compareTo(a[j])>0){

temp=a[i];

a[i]=a[j];

a[j]=temp;

System.out.println("Sorted Cities are ");

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

System.out.println(a[i]+" ");

class TestCity{

public static void main(String args[]){

City obj=new City();

obj.display();

}
Output :

15. Write a java program to accept list of file names through command line and
delete the files having extension “.txt”. Display the details of remaining files
such as FileName and size.

Answer :

Program :

import java.io.*;

class FileDeleteWithCommindLine{

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

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

File f=new File(args[i]);

if(f.isFile()){

String name = f.getName();


if(name.endsWith(".txt")){

f.delete();

System.out.println("File is deleted " +f);

else{

System.out.println(name + " "+f.length()+" bytes");

else{

System.out.println(args[i]+ " is not a file");

Output :
16. Design a screen in Java to handle the Mouse Events such as MOUSE_MOVED
and MOUSE_CLICK and display the position of the Mouse_Click in a TextField.

Answer :

Program :

import java.awt.*;

import java.awt.event.*;

class MouseEvents extends Frame{

TextField statusBar;

public static void main(String []args){

new MouseEvents().show();

MouseEvents(){
addMouseListener(new MouseAdapter(){

public void mouseClicked(MouseEvent e){

statusBar.setText("Clicked at (" + e.getX() + "," + e.getY() + ")");

repaint();

public void mouseEntered(MouseEvent e){

statusBar.setText("Entered at (" + e.getX() + "," + e.getY() + ")");

repaint();

);

addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

System.exit(0);

});

setLayout(new FlowLayout());

setSize(275,300);

setTitle("Mouse Click Position");

statusBar = new TextField(20);add(statusBar);

setVisible(true);

Output :
17. Write a Java program to design a screen using Awt that will take a user name
and password. If the user name and password are not same, raise an Exception
with appropriate message. User can have 3 login chances only. Use clear button
to clear the TextFields.
Answer :

Program :

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class InvalidPasswordException extends Exception{}


class UsernamePassword extends JFrame implements ActionListener{

JLabel name, pass;

JTextField nameText;

JPasswordField passText;

JButton login, end;

static int cnt=0;

UsernamePassword(){

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

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

cnt++;

JOptionPane.showMessageDialog(null,"Login
Failed","Login",JOptionPane.ERROR_MESSAGE);

nameText.setText("");

passText.setText("");

nameText.requestFocus();

if(cnt == 3){

JOptionPane.showMessageDialog(null,"3 Attempts
Over","Login",JOptionPane.ERROR_MESSAGE);

System.exit(0);

}
}

public static void main(String args[]){

new UsernamePassword();

Output :

18. Write a Java program which will create a frame if we try to close it, it should
change it’scolor and it remains visible on the screen(Use swing).
Answer :

Program :

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class CloseFormUseSwing extends JFrame{


JPanel p = new JPanel();

CloseFormUseSwing(){

setVisible(true);

setSize(400,400);

setTitle("Swing Background");

add(p);

addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

p.setBackground(Color.RED);

JOptionPane.showMessageDialog(null,"Close
window","Login",JOptionPane.INFORMATION_MESSAGE);

});

public static void main(String args[]){

new CloseFormUseSwing();

Output :
19. Write a java program to accept the details employee (Eno, Ename ,Salary)
and add it into the JTable by clicking on the Button.(Max : 5 Records)
Answer :

Program :

You might also like