Lab program java new (1)
Lab program java new (1)
1. Program to assign two integer values to X and Y. Using the ‘if’ statement the output of the
program should display a message whether X is greater than Y.
public class CompareNumbers
{
public static void main(String[] args)
{
// Assign two integer values to X and Y
int X = 10;
int Y = 5;
2. Program to list the factorial of the numbers 1 to 10. To calculate the factorial value, use
while loop. (Hint: Fact of 4 = 4*3*2*1).
public class Factorial
{
public static int factorial(int n)
{
int result = 1;
while (n > 1) {
result *= n;
n--;
}
return result;
}
public static void main(String[] args)
Page 1
Java Lab Manual BCA
{
for (int i = 1; i <= 10; i++) {
System.out.println("Factorial of " + i + " = " + factorial(i));
}
}
}
3.Program to find the area and circumference of the circle by accepting the radius from the user.
import java.util.Scanner;
public class Circle {
public static void main(String[] args)
{
double radius;
double area;
double circumference;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the radius of the circle: ");
radius = scanner.nextDouble();
area = Math.PI * radius * radius;
circumference = 2 * Math.PI * radius;
System.out.println("The area of the circle is: " + area);
System.out.println("The circumference of the circle is: " + circumference);
scanner.close();
}
4.Program to add two integers and two float numbers. When no arguments are supplied,
give a default value to calculate the sum. Use function overloading.
public class AddNumbers
{
public static int add(int num1, int num2)
{
return num1 + num2;
}
public static float add(float num1, float num2)
{
return num1 + num2;
}
Page 2
Java Lab Manual BCA
Output:
Addition Result: 15
Subtraction Result: 5
Multiplication Result: 15
Division Result: 5
6 .Program with class variable that is available for all instances of a class. Use static
variable declaration. Observe the changes that occur in the object’s member variable
values.
class MyClass
{
static int staticVariable = 0;
int instanceVariable;
Page 4
Java Lab Manual BCA
{
this.instanceVariable = instanceVariable;
}
public void display()
{
System.out.println("Instance Variable: " + instanceVariable + ", Static Variable: " +
staticVariable);
}
}
public class Main
{
public static void main(String[] args)
{
MyClass obj1 = new MyClass(10);
MyClass obj2 = new MyClass(20);
System.out.println("Initial values:");
obj1.display();
obj2.display();
MyClass.staticVariable = 5;
System.out.println("\nValues after modifying static variable:");
obj1.display();
obj2.display();
}
}
Output :
Initial values:
Instance Variable: 10, Static Variable: 0
Instance Variable: 20, Static Variable: 0
7. Program to create a student class with following attributes; Enrollment No: Name, Mark
of sub1, Mark of sub2, mark of sub3, Total Marks. Total of the three marks must be
calculated only when the student passes in all three subjects. The passing mark for each
subject is 50. If a candidate fails in any one of the subjects his total mark must be declared
as zero. Using this condition write a constructor for this class. Write separate functions for
Page 5
Java Lab Manual BCA
accepting and displaying student details. In the main method create an array of three
student objects and display the details.
import java.util.Scanner;
class Student
{
private String enrollmentNo;
private String name;
private int markSub1;
private int markSub2;
private int markSub3;
private int totalMarks;
System.out.println("\nStudent Details:");
for (Student student : students)
{
student.displayDetails();
System.out.println();
}
}
}
Page 7
Java Lab Manual BCA
Output:
Enter details for student 1:
Enrollment No: 101
Name: Alice
Mark of Sub1: 60
Mark of Sub2: 70
Mark of Sub3: 80
Enter details for student 2:
Enrollment No: 102
Name: Bob
Mark of Sub1: 45
Mark of Sub2: 65
Mark of Sub3: 55
Enter details for student 3:
Enrollment No: 103
Name: Charlie
Mark of Sub1: 80
Mark of Sub2: 75
Mark of Sub3: 85
Student Details:
Enrollment No: 101
Name: Alice
Mark of Sub1: 60
Mark of Sub2: 70
Mark of Sub3: 80
Total Marks: 210
Page 8
Java Lab Manual BCA
@override
public void addGear(int no)
{
System.out.println(“bike has”+no+gear”);
}
thread.sleep(500);
}
catch (interruptedException e)
{
System.out.println(“main threade interrupted:”);
}
System.out.println(“main thread exiting”);
}
}
output:
child thread: thread(demo thread,5,main)
main thread:5
child thread:5
child thread:4
main thread:4
child thread:3
child thread:2
main thread:3
child thread:1
existing child thread
main thread:2
main thread:1
main thread existing
Page 11
Java Lab Manual BCA
{
System.out.println(“main thread:”+i);
thread.sleep(1000);
}
}
catch(interruptedException e)
{
System.out.println(“main thread interrupted”);
}
System.out.println(“main thread exsting”);
}
}
}
class new thread implements Runnable
{
thread t;
newThread();
{
t=new thread(this,”demo thread”);
System.out.println(“child thread”+t);
t.start();
}
public void run()
{
try
{
for(i=5;i>0;i--)
{
System.out.println(“child thread:”+i);
thread.sleep(500);
}
}
catch (interruptedException e)
{
System.out.println(“Existing child thread”);
}
}
output
child thread:thread[demo thread,5,main]
Page 12
Java Lab Manual BCA
child thread:5
main thread:5
child thread:4
child thread:3
main thread:4
child thread:2
child thread:1
main thread:3
exsting child thread
main thread:2
main thread:1
main thread exsisting
System.out.println(“class maruti”);
}
public void brand()
{
System.out.println(“brand:maruthi”);
}
public void speed()
{
System.out.println(“Max:90Kmph”);
}
class Maruti800 extends maruti
{
public maruti800()
{
System.out.println(“maruti model 800”);
}
@override
public void speed()
{
System.out.println(max:80Kmph”);
}
}
output
class car
claas maruti
maruthi:800
vehicle type:car
brand:maruthi
max:80Kmph
1. Program to catch Negative Array Size Exception. This exception is caused when the
array size is initialized to negative values.
import java.util.Scanner;
public class Main
{
Page 14
Java Lab Manual BCA
Page 15
Java Lab Manual BCA
try
{
System.out.print("Enter the numerator: ");
int numerator = scanner.nextInt();
System.out.print("Enter the denominator: ");
int denominator = scanner.nextInt();
int result = divide(numerator, denominator);
System.out.println("Result of division: " + result);
}
catch (Arithmetic Exception e)
{
System.out.println("Arithmetic Exception caught: " + e.getMessage());
}
catch (Exception e)
{
System.out.println("Exception caught: " + e);
}
finally
{
scanner.close();
System.out.println("Scanner closed in finally block.");
}
}
Page 16
Java Lab Manual BCA
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Message Window");
JLabel label = new JLabel("Hello, world!");
frame.add(label);
frame.setSize(300, 100);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
4.Program which creates a frame with two buttons father and mother. When we click the
father button the name of the father, his age and designation must appear. When we click
mother button similar details of mother also appear.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ParentDetailsFrame extends JFrame implements ActionListener
{
private JButton fatherButton, motherButton;
private JLabel nameLabel, ageLabel, designationLabel;
public ParentDetailsFrame()
{
setTitle("Parent Details");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
fatherButton = new JButton("Father");
motherButton = new JButton("Mother");
fatherButton.addActionListener(this);
motherButton.addActionListener(this);
Page 17
Java Lab Manual BCA
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == fatherButton)
{
nameLabel.setText("Father: John Doe");
ageLabel.setText("Age: 45");
designationLabel.setText("Designation: Engineer");
}
else
if (e.getSource() == motherButton)
{
nameLabel.setText("Mother: Jane Doe");
ageLabel.setText("Age: 42");
designationLabel.setText("Designation: Teacher");
}
}
public static void main(String[] args)
{
new ParentDetailsFrame();
}
}
5. Create a frame which displays your personal details with respect to a button click.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
Page 18
Java Lab Manual BCA
import java.awt.event.ActionListener;
public PersonalDetailsFrame()
{
setTitle("Personal Details");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new FlowLayout());
nameLabel = new JLabel("Name: xyz");
ageLabel = new JLabel("Age: 30");
locationLabel = new JLabel("Location: bengaluru");
detailsButton = new JButton("Show Details");
detailsButton.addActionListener(this);
add(nameLabel);
add(ageLabel);
add(locationLabel);
add(detailsButton);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e)
{
nameLabel.setText("Name: ChatGPT");
ageLabel.setText("Age: Not specified");
locationLabel.setText("Location: Internet");
detailsButton.setEnabled(false);
}
public static void main(String[] args)
{
new PersonalDetailsFrame();
}
}
6. Program to create a window with TextFields and Buttons. The "ADD" button adds the
two integers and display the result. The "CLEAR" button shall clear all the text fields.
import javax.swing.*;
import java.awt.*;
Page 19
Java Lab Manual BCA
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public Calculator()
{
setTitle("Simple Calculator");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); setLayout(new FlowLayout());
textField1 = new JTextField(10);
textField2 = new JTextField(10);
resultField = new JTextField(10);
resultField.setEditable(false);
addButton = new JButton("ADD");
clearButton = new JButton("CLEAR");
addButton.addActionListener(this);
clearButton.addActionListener(this);
add(new JLabel("Enter Number 1:"));
add(textField1);
add(new JLabel("Enter Number 2:"));
add(textField2);
add(new JLabel("Result:"));
add(resultField);
add(addButton);
add(clearButton);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == addButton)
{
try
{
int num1 = Integer.parseInt(textField1.getText());
int num2 = Integer.parseInt(textField2.getText());
int result = num1 + num2;
resultField.setText(Integer.toString(result));
}
catch (NumberFormatException ex)
Page 20
Java Lab Manual BCA
{
JOptionPane.showMessageDialog(this, "Invalid input! Please enter valid integers.");
}
} else if (e.getSource() == clearButton)
{
textField1.setText("");
textField2.setText("");
resultField.setText("");
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
@Override
public void keyTyped(KeyEvent e)
{
}
Page 21
Java Lab Manual BCA
@Override
public void keyReleased(KeyEvent e)
{
}
public MouseEventsDemo()
{
setTitle("Mouse Events Demo");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Page 22
Java Lab Manual BCA
setLocationRelativeTo(null);
statusLabel = new JLabel("Status: ");
add(statusLabel);
addMouseListener(this);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
statusLabel.setText("Status: Mouse Clicked");
}
@Override
public void mousePressed(MouseEvent e)
{
statusLabel.setText("Status: Mouse Pressed");
}
@Override
public void mouseReleased(MouseEvent e)
{
statusLabel.setText("Status: Mouse Released");
}
@Override
public void mouseEntered(MouseEvent e)
{
statusLabel.setText("Status: Mouse Entered");
}
@Override
public void mouseExited(MouseEvent e)
{
statusLabel.setText("Status: Mouse Exited");
}
import javax.swing.*;
import java.awt.*;
Page 23
Java Lab Manual BCA
setVisible(true);
}
Page 24
Java Lab Manual BCA
import java.awt.event.*;
public class MenuAndPullDownMenus extends JFrame {
public MenuAndPullDownMenus() {
setTitle("Menu and Pull-Down Menus");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
JMenuItem newItem = new JMenuItem("New");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(e -> System.exit(0));
fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
JMenu editMenu = new JMenu("Edit");
menuBar.add(editMenu);
JMenuItem cutItem = new JMenuItem("Cut");
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem pasteItem = new JMenuItem("Paste");
editMenu.add(cutItem);
editMenu.add(copyItem);
editMenu.add(pasteItem);
setVisible(true);
}
Page 25