Java Practical File Rohit

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

1

Lingaya’s Lalita Devi Institute of Management & Sciences


(Affiliated to GGSIP University and Govt. of NCT of Delhi)
NAAC Accredited “A” Grade Institute and Approved under section 2(f) of UGC Act 1956
Mandi Road, Mandi New Delhi -110047,Nearest Metro Station Chattarpur, Tel : 011-26651113

PRACTICAL FILE

ON

Practical – VIII “Java Lab”


(BCA 272)

SUBMITTED BY SUBMITTED TO
Rohit mehra Mr. Deepak Rathore
(21bca35)
2

Index
S.NO. TOPIC PG.NO. TEACHER
SIGN.
1. Write a program declaring a class 4
Rectangle with data member’s length
and breadth and member functions
Input, Output and Calculate Area?

2. Write a program to demonstrate use 6


of method overloading to calculate
area of square, rectangle and
triangle?
3. Write a program to demonstrate the 8
use of static variable, static method
and static block?
4. Write a program to demonstrate 10
concept of ``this``?
5. Write a program to demonstrate 12
multi-level and hierarchical
inheritance?
6. Write a program to use super () to 18
invoke base class constructor?
7. Write a program to demonstrate run- 20
time polymorphism?
8. Write a program to demonstrate the 22
concept of aggregation?
9. Write a program to demonstrate 24
unchecked exception?
3

10. Write a program to use Byte stream 26


class to read from a text file and
display the content on the output
screen?
11. Create a class employee which have 28
name, age and address of employee,
include methods get data () and
show data (), get data () takes the
input from the user, show data ()
display the data in following format:
Name:
Age:
Address:
12. Write a Java program to perform 30
basic Calculator operations. Make a
menu driven program to select
operation to perform (+ - * /). Take 2
integers and perform operation as
chosen by user?
13. Write a program declaring a Java 33
class called Savings Account with
members ``account Number`` and
``Balance``. Provide member
functions as ``deposit Amount ()``
and ``withdraw Amount ()``. If user
tries to withdraw an amount greater
than their balance then throw a user-
defined exception?
14. Write a swing application that uses at 37
least 5 swing controls?
15. Write a program to implement border 40
layout using Swing?
4

Java Practical File


(Section A) Core Practical’s (Implement minimum 10 out of 15 practical)
Q.1 Write a program declaring a class Rectangle with data member’s length and
breadth and member functions Input, Output and Calculate Area?
Ans:-
import java.util.Scanner;

class Rectangle {
double length;
double breadth;

void inputValues() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the length of the rectangle: ");
length = scanner.nextDouble();
System.out.print("Enter the breadth of the rectangle: ");
breadth = scanner.nextDouble();
}

void outputValues() {
System.out.println("Length: " + length);
System.out.println("Breadth: " + breadth);
}

double calculateArea() {
return length * breadth;
5

}
}

public class Main {


public static void main(String[] args) {
Rectangle rectangle = new Rectangle();

rectangle.inputValues();
rectangle.outputValues();

double area = rectangle.calculateArea();


System.out.println("Area: " + area);
}
}
6

Q.2 Write a program to demonstrate use of method overloading to calculate area


of square, rectangle and triangle?
Ans:-
class AreaCalculator {
double calculateArea(double side) {
return side * side; // Area of a square
}

double calculateArea(double length, double breadth) {


return length * breadth; // Area of a rectangle
}

double calculateArea(double base, double height) {


return 0.5 * base * height; // Area of a triangle
}
}

public class Main {


public static void main(String[] args) {
AreaCalculator calculator = new AreaCalculator();

// Calculate and output the area of a square


double squareArea = calculator.calculateArea(5);
System.out.println("Area of square: " + squareArea);
7

// Calculate and output the area of a rectangle


double rectangleArea = calculator.calculateArea(4, 6);
System.out.println("Area of rectangle: " + rectangleArea);

// Calculate and output the area of a triangle


double triangleArea = calculator.calculateArea(3, 8);
System.out.println("Area of triangle: " + triangleArea);
}
}
8

Q.3 Write a program to demonstrate the use of static variable, static method and
static block?
Ans:-
class StaticDemo {
static int staticVariable;
int instanceVariable;

static {
System.out.println("Inside static block");
staticVariable = 10;
}

static void staticMethod() {


System.out.println("Inside static method");
System.out.println("Static Variable: " + staticVariable);
// Cannot access instanceVariable here
}

void instanceMethod() {
System.out.println("Inside instance method");
System.out.println("Static Variable: " + staticVariable);
System.out.println("Instance Variable: " + instanceVariable);
}
}

public class Main {


9

public static void main(String[] args) {


// Accessing static variables and static method without creating
an instance
StaticDemo.staticVariable = 20;
StaticDemo.staticMethod();

// Creating an instance to access instance variables and instance


method
StaticDemo demo = new StaticDemo();
demo.instanceVariable = 30;
demo.instanceMethod();
}
}
10

Q.4 Write a program to demonstrate concept of ``this``?


Ans:- class
student
{ int
id;
String name;
student(int id,String name)
{
this.id=id;
this.name=name;
}
void display()
{
System.out.println("Name of the student : "+name);
System.out.println("Id of the student : "+id);

}
}
class th
{
public static void main(String[] args)
{
student s=new student(1001,"Jestin");
s.display();
}
}
11

Output:-
12

Q.5 Write a program to demonstrate multi-level and hierarchical inheritance?


Hierarchical Inheritance
Ans:-
import java.util.*; class
Account

{
void info(int acc_no,String name)
{
System.out.println("You're Name is : "+name);
System.out.println("You're Account no. is : " +acc_no);

}
}
class Saving extends Account
{
void balance(int balance)
{
System.out.println("You're balance is : "+balance);
if(balance<500)
{
System.out.println("Minimum balance should be 500 or more!");
}
else
{
System.out.println("Account Created");
}
13

}}

class Current extends Account


{
void balance(int balance)
{
System.out.println("You're balance is : "+balance);
if(balance<1000)

{
System.out.println("Minimum balance should be 1000 or more!");
}
else
{
System.out.println("Account Created");
}
}
}
class Bank
{
public static void main(String[] args)
{
int acc_no,n;
// String name;
int balance;
Scanner obj=new Scanner(System.in);
System.out.print("Enter you're account number : " );
acc_no=obj.nextInt();
14

System.out.print("Enter you're name : ");


String name=obj.next();
System.out.print("Enter the balance : ");
balance=obj.nextInt();
System.out.println("Type of Account : ");
System.out.println("1. Saving Account");
System.out.println("2. Current Account");
System.out.print("Enter your option : ");
n=obj.nextInt(); if(n==1)
{
Saving o=new Saving();
o.info(acc_no,name);
o.balance(balance);
}
else if (n==2)
{
Current o=new Current();
o.info(acc_no,name);
o.balance(balance);
}
else
{
System.out.println("Invalid option");
}
}
}
15

Output:-

Multilevel Inheritance Ans:-


class A
{ int
x=10;

void get()
{
System.out.println("Class A");
}
}
class B extends A
{ int
y=20;
void display()

{
System.out.println("Class B");
}
}
16

class C extends B
{ int
z=30;

void show()
{
System.out.println("Class C");
}
}
class multilevel
{
public static void main(String[] args)
{
C obj = new C();
System.out.println("Value of x is : "+obj.x);
System.out.println("Value of y is : "+obj.y);
System.out.println("Value of z is : "+obj.z);
obj.get();
obj.display();
obj.show();

}
}
17

Output:-
18

Q.6 Write a program to use super () to invoke base class constructor?


Ans:-
class parent
{
int a=45; parent()
{
System.out.println("I am parent class constructor");
}
void display()
{
System.out.println("This is parent class function");
}
}

class child extends parent


{
int a=50; void
display()
{
System.out.println("This is child class function");
System.out.println("Value of a in parent class : "+super.a);
System.out.println("Value of a is : "+a);
//super.display();
}
}
public class sup
19

{
public static void main(String[] args)
{
child c= new child();
c.display();
}
}

Output:-
20

Q.7 Write a program to demonstrate run-time polymorphism?


Ans:-
class A
{
void display()
{
System.out.println("Parent");
}
}

class B extends A
{
void display()
{
System.out.println("Child");
}
}

class overriding
{
public static void main(String[] args)
{
A obj =new A(); A
obj1= new B();
21

obj.display();
obj1.display();
}
}

Output:-
22

Q.8 Write a program to demonstrate the concept of aggregation?


Ans:- class Author
{
String authorName;
int age;
String place;

// Author class constructor


Author(String name, int age, String place)
{
this.authorName = name;
this.age = age;
this.place = place;
}
}

class Book
{
String name;
int price;
// author details
Author auther;
Book(String n, int p, Author auther)
{
this.name = n;
this.price = p;
this.auther = auther;
23

}
public static void main(String[] args) {
Author auther = new Author("John", 42, "USA");
Book b = new Book("Java for Begginer", 800, auther);
System.out.println("Book Name: "+b.name);
System.out.println("Book Price: "+b.price);
System.out.println("------------Auther Details----------");
System.out.println("Auther Name: "+b.auther.authorName);
System.out.println("Auther Age: "+b.auther.age);
System.out.println("Auther place: "+b.auther.place);
}

Output:-
24

Q.9 Write a program to demonstrate unchecked exception?


Ans:-
import java.util.*; import
java.lang.Throwable; public

class bca2
{
public static void voter(int age)
{
if (age<18)
{
throw new ArithmeticException("Sorry You are not eligible to vote");
}
else
{
System.out.println("Welcome you are eligible for vote");
}
}
public static void main(String[] args)
{
int age;
Scanner obj=new Scanner(System.in);
System.out.println("Enter your age: ");
age=obj.nextInt(); voter(age);
}
}
25

Output:-
26

Q.10 Write a program to use Byte stream class to read from a text file and display
the content on the output screen?
Ans:-
import java.io.*;
import java.util.*; class
fileread
{
public static void main(String[] args)
{
try
{
File obj=new File ("C:\\Users\\jesti\\OneDrive\\Desktop\\test\\goblin\\jestin.txt");
Scanner obj2=new Scanner(obj); while(obj2.hasNextLine())

{
System.out.println(obj2.nextLine());
}
obj2.close();
}
catch(Exception e)
27

e.printStackTrace();
}
}
}

Output:- Read

Display
28

(Section B) Application Based Practical’s (Implement minimum 5 out of 10


practical)
Q.1 Create a class employee which have name, age and address of employee,
include methods get data () and show data (), get data () takes the input from the
user, show data () display the data in following format:
Name:
Age:

Address:
Ans:-
import java.util.*;
class employee
{
String name;
int age;
String address;

void getdata()
{
Scanner obj=new Scanner(System.in);
System.out.print("Enter the name of the Employee : ");
name=obj.next();
System.out.print("Enter the age of the Employee : "); age=obj.nextInt();
System.out.print("Enter Employee's address : "); address=obj.next();

}
void showdata()
29

System.out.println("Name of the employee is : "+name);


System.out.println("Age of the employee is : "+age);
System.out.println("Address of the employee is : "+address);
}

public static void main(String[] args)


{
employee e=new employee();
System.out.println("Enter the Employee details :- ");
e.getdata();
System.out.println("Employee details as follow :-");
e.showdata();
}
}

Output:-
30

Q.2 Write a Java program to perform basic Calculator operations. Make a menu
driven program to select operation to perform (+ - * /). Take 2 integers and
perform operation as chosen by user?
Ans:-
import java.util.*; class
cal
{
int sum,sub,mul;
float div; void
addition(int a,int b)
{
sum=a+b;
System.out.println("Sum of " +a+ " and " +b+ " is : " +sum );
}
void subtraction(int a,int b)
{
sub=a-b;
System.out.println("Sub of " +a+ " and " +b+ " is : " +sub);
}
void division(int a, int b)
{
div=a/b;
System.out.println("division of " +a+ " and " +b+ " is : " +div);
}
void multiplication(int a, int b)
{
31

mul=a*b;
System.out.println("Multiplication of " +a+ " and " +b+ " is : " +mul);
}
}
class calculator
public static void main(String[] args)
{
int a,b;
String operator;
Scanner obj=new Scanner(System.in);
System.out.println("Enter the value of a : "); a=obj.nextInt();
System.out.println("Enter the value of b : " );
b=obj.nextInt(); cal obj2=new cal();
System.out.println("Operator available :- ");
System.out.println("+");
System.out.println("-");
System.out.println("*");
System.out.println("/");
System.out.print("Enter from the given operator : ");
operator=obj.next(); if(operator.equals("+"))
{
obj2.addition(a,b);
}
else if(operator.equals("-")){ obj2.subtraction(a,b);
}
else if(operator.equals("*")){ obj2.multiplication(a,b);
32

}
else if(operator.equals(" / ")){ obj2.division(a,b);
}
}
}

Output:-
33

Q.3 Write a program declaring a Java class called Savings Account with members
``account Number`` and ``Balance``. Provide member functions as ``deposit
Amount ()`` and ``withdraw Amount ()``. If user tries to withdraw an amount
greater than their balance then throw a user-defined exception?
Ans:-
import java.util.*; import
java.lang.Throwable; class
SavingAccount
{
double accountNumber;
static double Balance;
34

double total;

SavingAccount( double accno,double bala)


{
accountNumber=accno;
Balance=bala;
}
void depositAmount(double deposit)
{
System.out.println("Your deposit is : "+deposit); total=deposit+Balance;
System.out.println("Your total balance is : "+total);
}
public static void withdraw(double amount)
{
if(amount>Balance)
{
throw new ArithmeticException("Sorry! your withdraw amount is more than your balance");
}
else
{
System.out.println("Successfully Withdrawn");
}
}
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
35

double accno,bala;
System.out.println("Enter your Account number : ");
accno=obj.nextDouble();
System.out.println("Enter your Balance : "); bala=obj.nextDouble();
SavingAccount sa=new SavingAccount(accno,bala);
System.out.println("Option we have : ");
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("Enter your option : ");
int option=obj.nextInt(); if(option==1)
{
System.out.println("Enter the amount for deposit : "); double
deposit=obj.nextDouble(); sa.depositAmount(deposit);
}
else if(option==2)
{
System.out.println("Enter the amount to be withdrawn : ");
double amount=obj.nextDouble(); withdraw(amount);
}
else
{
System.out.println("Invalid option");
}
}
}
36

Output:-
37

Q.4 Write a swing application that uses at least 5 swing controls?


Ans:- import javax.swing.*; import java.awt.event.*; public class sam
implements ActionListener
{
JFrame f;
JMenuBar mb;
JMenu file,edit,help;
JMenuItem cut,copy,paste,selectAll;
JTextArea ta;

sam()
{
f=new JFrame(); cut=new
JMenuItem("cut"); copy=new
JMenuItem("copy"); paste=new
JMenuItem("paste"); selectAll = new
JMenuItem("selectAll");
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectAll.addActionListener(this);
mb=new JMenuBar();
file=new JMenu("file");
edit=new JMenu("edit");
help=new JMenu("help");
38

edit.add(cut);
edit.add(copy);
edit.add(paste);
edit.add(selectAll);
mb.add(file);
mb.add(edit);
mb.add(help); ta=new
JTextArea();
ta.setBounds(5,5,360,320);
f.add(mb);
f.add(ta);
f.setJMenuBar(mb);
f.setLayout(null);
f.setSize(500,500);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==cut)
ta.cut();
if(e.getSource()==paste)
ta.paste();
if(e.getSource()==copy) ta.copy();
if(e.getSource()==selectAll)
ta.selectAll();

}
39

public static void main(String[] args)


{
new sam();
}
}
Output:-
40

Q.5 Write a program to implement border layout using Swing?


Ans:-
import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame jframe;

Border()
{

jframe = new JFrame();

JButton btn1 = new JButton("NORTH");


JButton btn2 = new JButton("SOUTH");
JButton btn3 = new JButton("EAST");
JButton btn4 = new JButton("WEST");
JButton btn5 = new JButton("CENTER");

jframe.setLayout(new BorderLayout(20, 15));


jframe.add(btn1, BorderLayout.NORTH);
jframe.add(btn2, BorderLayout.SOUTH);
jframe.add(btn3, BorderLayout.EAST);
jframe.add(btn4, BorderLayout.WEST);
41

jframe.add(btn5, BorderLayout.CENTER);
jframe.setSize(300,300); jframe.setVisible(true);
}

public static void main(String argvs[])


{
new Border();
}
}

Output:-

You might also like