Sujal Java
Sujal Java
Sujal Java
BACHELOR OF COMPUTER APPLICATION
“JAVA” PROGRAMMING LAB
BCA 272
Guru Gobind Singh Indraprastha University
Sector - 16C, Dwarka, Delhi - 110078
SUBMITTED TO: SUBMITTED BY:
Ms. Sakshi Khullar Sujal
Assistant Professor 06217702021
VSIT BCA-4B
2
INDEX – PRACRICAL
interface.
class q1{
public static int factorial(int num){
if(num ==0 || num==1)
return 1;
else
return num*factorial(num-1);
}
Output:
6
class q1{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println(" Enter number to find fibonacci series : ");
int num= sc.nextInt();
int fibonacci =fibonacci(num);
System.out.println( " fibonacci of "+ num + " is "+ fibonacci);
}
public static int fibonacci(int num){
if(num<=1)
return num;
else
return fibonacci(num-1)+fibonacci(num-2);
}
}
Output:
7
class q1{
public static void main(String args[]){
System.out.println("Command line arguments:");
for ( int i=0 ;i<args.length ;i++)
System.out.println( " Argument : "+ args[i]);
}
Output:
8
class q1{
public static void main(String args[]){
System.out.println("Enter a Number to check if it's prime or not : \
n");
Scanner sc = new Scanner(System.in);
int num= sc.nextInt();
if( prime(num)){
System.out.println(" yes ,it is prime ");
}
else{System.out.println(" no ,it is not prime ");}
}
public static boolean prime(int num){
if(num<=1)
return false;
else{
for ( int i=2; i<= Math.sqrt(num);i++){
if( num % i==0){
return false;
}
}
}
return true;
}
}
9
Output:
10
class Accounts{
int acount_no;
String name,acount_name;
double balance;
Scanner sc = new Scanner(System.in);
public Accounts(){
System.out.print(" \nEnter your Account Number : ");
acount_no=sc.nextInt();
}
public boolean withdrawl(){
System.out.print("\nEnter your amount for withdrawal: ");
double amount = sc.nextDouble();
balance -=amount;
display();
return true;
}
public boolean deposit(){
System.out.print(" \nEnter your amount for deposit : ");
double amount = sc.nextDouble();
balance +=amount;
display();
return true;
}
public void display(){
System.out.print("\n----------------- Details:------------- \nAccount
Number : "+acount_no);
System.out.print("\n Name: "+name);
System.out.print("\n Account name: "+acount_name);
System.out.print(" \n Balance: "+balance);
11
}
};
class q1{
public static void main (String[] args){
Accounts a1= new Accounts();
a1.display();
a1.deposit();
a1.withdrawl();
}
}
Output:
12
Shape(){
length=breadth=height=0;
color=null;
}
Shape(int l,int b,int h){
length=l;
breadth=b;
height=l;
color="blue";
}
Shape(String c){
length=breadth=height=70;
color="Green";
}
public void display(){
System.out.println("-------Details of Shape :_--------"+"\
nlength:"+length+"\nbreadth: "+breadth+ "\nheight: "+height+"\n Color:
"+color);
}
}
class q1{
public static void main (String[] args){
Shape a1= new Shape();
Shape a2= new Shape(23,34,56);
Shape a3= new Shape("cyan");
a1.display();
a2.display();
a3.display();
}
}
13
Output:
14
class q1{
public static void main (String[] args){
Shape a1= new Shape(12,24,45,"blue");
Shape a2= new Shape(23,34,56,"cyan");
Shape a3= new Shape(23,56,78,"cyan");
// a1.display();
// a2.display();
a3.display();
}
}
Output:
15
class q1{
public static void ChangeValue(int value){
value+=4;
System.out.println(" Inside function value of variable : "
+value);
}
}
Output:
17
Code:
// method overriding
class Animal{
public void makeSound(){
System.out.println(" The animal make sound ");
}
}
class Dog extends Animal{
public void makeSound(){
System.out.println("\nBark Bark");
}
}
class Cat extends Animal{
public void makeSound(){
System.out.println("\nMeow\n");
}
}
// method overloading
class Calculator{
public int add(int a, int b){
return a+b;
}
public int add(int a, int b, int c){
return a+b+c;
}
}
class q1{
public static void main(String[] args){
System.out.println("\nMethod overriding");
Cat c= new Cat();
System.out.println("Cat sound");
c.makeSound();
Dog d =new Dog();
System.out.println("Dog sound");
d.makeSound();
System.out.println("\nMethod overloading");
Calculator cal= new Calculator();
System.out.println("Sum of two number 3+4 = "+ cal.add(3,4));
System.out.println("Sum of three number 3+4+8 = "+ cal.add(3,4,8));
}
}
18
Output:
19
Code:
class BaseClass{
protected int var;
public BaseClass(int v){
this.var=v;
System.out.println("this is Base class");
}
}
}
class DrivedClass extends BaseClass{
protected int var;
DrivedClass(int b,int d){
super(b); //super(b); call parent constructor
var=d;
}
public void getdata(){
super.getdata();// super.getdata(); //call parent member function
System.out.println("Value of var of base + Drived class: "+
(super.var+this.var));
//super.var //value of parent data member
}
}
class q10 {
public static void main(String[] args){
DrivedClass obj= new DrivedClass(89, 43);
obj.getdata();
}
}
20
Output:
21
11. Create a class box having height, width , depth as the instance
variables & calculate its volume. Implement constructor overloading
in it. Create a subclass named box_new that has weight as an instance
variable. Use super in the box_new class to initialize members of the
base class.
Code:
import java.util.Scanner;
class Box{
protected double height,width,depth;
Scanner sc= new Scanner(System.in);
Box(){
height=width=depth=0.0;
System.out.print("you wont to input data (y/n): ");
char op= sc.next().charAt(0);
// char op = sc.nextChar();
if (op=='y'){
System.out.print("Enter Details of Box: ");
System.out.print("Enter Height: ");
height=sc.nextDouble();
System.out.print("Enter width: ");
width=sc.nextDouble();
System.out.print("Enter depth: ");
depth=sc.nextDouble();
}
}
Box(Double value){
height=width=depth=value;
}
Box(Double h,Double w,Double d){
height=h;width=w;depth=d;
}
void display(){
System.out.println("\n Details of box : \n height: "+height+"\nwidth:
"+width+"\n Depth: "+depth);
}
void volume(){
System.out.println("Volume of Box : "+(height*width*depth));
}
}
22
// sub class
class Box_New extends Box{
protected double weight;
Box_New(){
super();
System.out.print("Enter Weight of Box_New : ");
weight=sc.nextDouble();
}
Box_New(double v,double w){
super(v);
weight=w;
}
void display(){
super.display();
System.out.println("weight: "+weight);
super.volume();
}
Output:
24
}
}
class Poodle extends Dog{
void groom(){
System.out.println("Grooming----------------------");
}
}
Output:
25
Code:
import java.util.Scanner;
class Student{
protected String name;
protected long enroll;
protected char shift;
public Student(){
name= "abc";
enroll=000000000;
shift= 'E';
}
public Student(String name, long enroll, char shift){
this.name=name;
this.enroll=enroll;
this.shift=shift;
}
void Display(){
System.out.println("\nName : "+ name+" \nEnrollno : "+enroll+"\nShift
: "+ shift);
}
}
double marks ;
public Exam(){
marks=000;
}
public Exam(String name, long enroll, char shift,double marks){
super(name,enroll,shift);
this.marks=marks;
}
void Display(){
super.Display();
System.out.print("\nMarks out of 100 : "+marks);
}
}
interface Sports{
if (marks<=40){
System.out.print("With Sports Grace Marks===== ") ;
result=marks+getSportGraceMarks();
}
else if(marks>=100){
27
result=marks;
}
System.out.println("\nResult of Student : "+result);
}
else{
System.out.println("Error: Invalid Sports grace marks ");
}
}
}
28
OutPut:
29
refAnimal=Aobj;
refAnimal.makeSound();
refAnimal=Cobj;
refAnimal.makeSound();
refAnimal =Dobj;
refAnimal.makeSound();
}
}
30
Output:
31
Code:
import java.util.Scanner;
interface Shape{
double area();
double perimeter();
}
class Circle implements Shape{
protected double radius;
}
public double area(){
return side*side;
}
public double perimeter(){
return 4*side;
}
}
double var1,var2;
System.out.print("\n Enter the Details of Shape: \
n-----------------------------------------");
System.out.print("\nEnter radius of circle:");
var1=sc.nextDouble();
//object of circle
Circle c= new Circle(var1);
System.out.print("Area of circle: "+ c.area());
System.out.print("\nPerimeter of circle: "+ c.perimeter());
}
}
33
Output:
34
interface Tv {
void turnOn();
void turnOff();
void changeChannel(int channel);
void adjustVolume(int volume);
}
interface SmartDevice{
void connectWifi(String network_name,String password);
void browsWeb(String url);
void sendEmail(String receipient,String subject ,String message);
}
class SmartTv implements Tv, SmartDevice{
private boolean isOn;
private int currentChannel,currentVolume;
private String currentWifi;
}
else{
System.out.println("Tv is turnOff ");
}
}
}
else{
System.out.println("Tv is turnOff ");
}
}
public void connectWifi(String network_name,String password){
if (isOn){
this.currentWifi=network_name;
System.out.println("Wiffi is connected "+currentWifi);
}
else{
System.out.println("Tv is turnOff ");
}
}
public void browsWeb(String url){
if (isOn){
System.out.println("Cuurent browsing web is : "+ url);
}
else{
System.out.println("Tv is turnOff ");
}
}
public void sendEmail(String recipient,String subject ,String message){
if (isOn){
System.out.println("Sending an email :\n recipient :
"+recipient+" Subject : "+subject+ " Message : "+message);
}
else{
System.out.println("Tv is turnOff ");
}
}
}
st1.browsWeb("https://www.abc.com/");
st1.turnOn();
st1.connectWifi("XYZ","abcd1234");
st1.sendEmail("efg.gmail.com","Java Lab ","sldfrhnfdljdiofjdlkf");
st1.turnOff();
}
}
Output:
37
Code:
import java.util.Scanner;
Output:
38
class NumberChecker {
public static void checkNumber(int number) throws NoMatchException {
if (number != 10) {
throw new NoMatchException("Number does not match!");
} else {
System.out.println("Number is a match!");
}
}
}
try {
NumberChecker.checkNumber(userInput);
} catch (NoMatchException e) {
System.out.println(e.getMessage());
}
}
}
Output:
39
20. WAP that creates three threads which print no.s from 1 to 5, 6 to 10
and 11 to 15 respectively .Set the name & priority of the threads.
@Override
public void run() {
for (int i = start; i <= end; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
40
Output:
41
Output:
}
try {
// Wait for the threads to finish
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output:
44
23. WAP that demonstrates the use of sleep and join methods in thread.
Use minimum three threads.
Code:
try {
// Wait for all three threads to complete using join()
thread12.join();
thread13.join();
45
thread14.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All threads completed.");
}
}
Output:
46
Code:
Output:
47
25. WAP to implement file handling . The program should copy the content
from one file to another.
Code:
import java.io.*;
try {
File sourceFile = new File(sourceFilePath);
File destinationFile = new File(destinationFilePath);
// Close streams
fileReader.close();
fileWriter.close();
Output:
48
26. WAP to implement all mouse events and mouse motion events. Change the
background color, text and foreground color at each mouse event.
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public q25() {
setTitle("Mouse Events Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMouseListener(this);
addMouseMotionListener(this);
setSize(400, 300);
setVisible(true);
}
@Override
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked");
getContentPane().setBackground(Color.YELLOW);
label.setForeground(Color.RED);
}
@Override
public void mousePressed(MouseEvent e) {
label.setText("Mouse Pressed");
getContentPane().setBackground(Color.BLUE);
label.setForeground(Color.WHITE);
}
@Override
public void mouseReleased(MouseEvent e) {
49
label.setText("Mouse Released");
getContentPane().setBackground(Color.GREEN);
label.setForeground(Color.BLACK);
}
@Override
public void mouseEntered(MouseEvent e) {
label.setText("Mouse Entered");
getContentPane().setBackground(Color.CYAN);
label.setForeground(Color.MAGENTA);
}
@Override
public void mouseExited(MouseEvent e) {
label.setText("Mouse Exited");
getContentPane().setBackground(Color.PINK);
label.setForeground(Color.ORANGE);
}
@Override
public void mouseDragged(MouseEvent e) {
label.setText("Mouse Dragged: (" + e.getX() + ", " + e.getY() + ")");
getContentPane().setBackground(Color.LIGHT_GRAY);
label.setForeground(Color.DARK_GRAY);
}
@Override
public void mouseMoved(MouseEvent e) {
label.setText("Mouse Moved: (" + e.getX() + ", " + e.getY() + ")");
getContentPane().setBackground(Color.WHITE);
label.setForeground(Color.BLACK);
}
}
Output:
50
import java.awt.*;
import java.awt.event.*;
28. WAP that creates a button in Swings. On clicking the button, the content of
the button should be displayed on a label.
Code:
import javax.swing.*;
// import java.awt.*;
import java.awt.event.*;
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText(button.getText());
}
});
frame.setVisible(true);
}
}
Output:
52
29. Write a Java program that simulates a traffic light. The program lets the user
select one of three lights: red, yellow, or green. When a button is selected,
the light is turned on, and only one light can be on at a time No light is on
when the program starts.
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public q28() {
setTitle("Traffic Light Simulator");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
redButton.addActionListener(this);
yellowButton.addActionListener(this);
greenButton.addActionListener(this);
setLayout(new BorderLayout());
add(trafficLightPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
53
switch (command) {
case "Red":
turnOnRedLight();
break;
case "Yellow":
turnOnYellowLight();
break;
case "Green":
turnOnGreenLight();
break;
}
}
Output:
55
public CalculatorGUI() {
// Set up the frame
setTitle("Simple Calculator");
setSize(300, 200);
setLayout(new GridLayout(5, 2));
// Create components
firstInput = new TextField();
secondInput = new TextField();
resultField = new TextField();
addButton = new Button("Add");
subtractButton = new Button("Subtract");
multiplyButton = new Button("Multiply");
divideButton = new Button("Divide");
cancelButton = new Button("Cancel");
calculateResult('+');
}
});
subtractButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculateResult('-');
}
});
multiplyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculateResult('*');
}
});
divideButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculateResult('/');
}
});
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearFields();
}
});
switch (operator) {
case '+':
result = firstNumber + secondNumber;
break;
case '-':
result = firstNumber - secondNumber;
break;
case '*':
result = firstNumber * secondNumber;
break;
57
case '/':
result = firstNumber / secondNumber;
break;
}
resultField.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
resultField.setText("Invalid input");
}
}
Output:
58
31. Write an Jframe that contains three choices and 30 * 30 pixel canvas. The
three check boxes should be labeled “red” ,”Green” and “Blue” .The
selections of the choice should determine the color of the background.
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public q30() {
setTitle("Color Chooser");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
canvas = new JPanel();
canvas.setPreferredSize(new Dimension(30, 30));
add(canvas, BorderLayout.CENTER);
redCheckBox = new JCheckBox("Red");
greenCheckBox = new JCheckBox("Green");
blueCheckBox = new JCheckBox("Blue");
redCheckBox.addItemListener(new ColorChangeListener());
greenCheckBox.addItemListener(new ColorChangeListener());
blueCheckBox.addItemListener(new ColorChangeListener());
JPanel checkBoxPanel = new JPanel();
checkBoxPanel.add(redCheckBox);
checkBoxPanel.add(greenCheckBox);
checkBoxPanel.add(blueCheckBox);
add(checkBoxPanel, BorderLayout.SOUTH);
}
Output:
60
32. Create a login form using AWT controls like labels, buttons, textboxes,
checkboxes, list, radio button. The selected checkbox item names should be
displayed.
Code:
import java.awt.*;
import java.awt.event.*;
public LoginFrame() {
setTitle("Login Form");
setSize(300, 200);
setLayout(new FlowLayout());
setVisible(true);
}
Output:
62
33. Create an program using Combobox and textfield as per the below figure:
Code:
import java.awt.*;
import java.awt.event.*;
public CalculatorGUI() {
// Set up the frame
setTitle("Simple Calculator");
setSize(300, 200);
setLayout(new GridLayout(5, 2));
// Create components
firstInput = new TextField();
secondInput = new TextField();
resultField = new TextField();
addButton = new Button("Add");
subtractButton = new Button("Subtract");
multiplyButton = new Button("Multiply");
divideButton = new Button("Divide");
cancelButton = new Button("Cancel");
subtractButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculateResult('-');
}
});
multiplyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculateResult('*');
}
});
divideButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculateResult('/');
}
});
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clearFields();
}
});
switch (operator) {
case '+':
result = firstNumber + secondNumber;
break;
case '-':
result = firstNumber - secondNumber;
64
break;
case '*':
result = firstNumber * secondNumber;
break;
case '/':
result = firstNumber / secondNumber;
break;
}
resultField.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
resultField.setText("Invalid input");
}
}
Code:
import javax.swing.*;
import java.awt.*;
// Creating panels
JPanel borderLayoutPanel = new JPanel(new BorderLayout());
JPanel flowLayoutPanel = new JPanel(new FlowLayout());
JPanel gridLayoutPanel = new JPanel(new GridLayout(3, 3));
JPanel boxLayoutPanel = new JPanel();
boxLayoutPanel.setLayout(new BoxLayout(boxLayoutPanel,
BoxLayout.Y_AXIS));
// FlowLayout
flowLayoutPanel.add(new JButton("Button 1"));
flowLayoutPanel.add(new JButton("Button 2"));
flowLayoutPanel.add(new JButton("Button 3"));
// GridLayout
for (int i = 1; i <= 9; i++) {
gridLayoutPanel.add(new JButton("Button " + i));
}
// BoxLayout
boxLayoutPanel.add(new JButton("Button 1"));
boxLayoutPanel.add(Box.createVerticalStrut(10));
boxLayoutPanel.add(new JButton("Button 2"));
boxLayoutPanel.add(Box.createVerticalStrut(10));
boxLayoutPanel.add(new JButton("Button 3"));
frame.pack();
frame.setVisible(true);
}
}
Output:
67
35. Create a simple JDBC program that displays & updates(insert or delete) the
content of a table named employee having fields (id,name,deptt).
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public EmployeeManagementGUI() {
super("Employee Management");
// Set layout
setLayout(new FlowLayout());
add(deptField);
add(displayButton);
add(insertButton);
add(deleteButton);
add(new JScrollPane(outputArea));
rs.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
if (rowsAffected > 0) {
JOptionPane.showMessageDialog(null, "Record deleted
successfully!");
} else {
JOptionPane.showMessageDialog(null, "No record found with
ID: " + id);
}
}
Output: