Java Practical Manual-2025

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

BCA

II SEMESTER
JAVA PROGRAMMING LAB
Total Hours: 20 per batch Hours/Week: 2

Max Marks: 50 Credits: 2

1. Write a Program to find the average and sum of the N Numbers Using command line
arguments.
2. /Using command line arguments
3. class CLArguments {
4. public static void main(String args[])
5. {
6. float sum=0;
7. int n=args.length;
8. for(int i=0;i<n;i++)
9. {
10. sum=sum+Integer.parseInt(args[i]);
11. }
12. float average=sum/n;
13.
14. System.out.println("Average of "+n+ " Arguments is: "
+average);
15. }
16. }
17. /*
18. Filename: CLArguments.java
19. C:\Users\welcome\Documents>javac CLArguments.java
20. C:\Users\welcome\Documents>java CLArguments 10 20 30 40 50
21. Command Line Arguments Are:
22. 10 20 30 40 50
23. Average of 5 Arguments is: 30.0
24. */

2. Write a Program to calculate the Simple Interest and Input by the user.
3. import java.io.*;
4. import java.util.*;
5.
6. class SI
7. {
8. public static void main(String args[])
9. {
10. Scanner in = new Scanner(System.in);
11. System.out.print("Enter Principle Amount: ");
12. double p = in.nextDouble();
13. System.out.print("Enter Interest Rate: ");
14. double r = in.nextDouble();
15. System.out.print("Enter Time in Year: ");
16. int t = in.nextInt();
17.
18. double si=p*r*t/100;
19. double ta=p+si;
20. System.out.println("Simple interest="+si);
21. System.out.println("Total Amount is ="+ta);
22. }
23. }
24. /*
25. FileName:SI.java
26. C:\Users\welcome\Documents>javac SI.java
27. C:\Users\welcome\Documents>java SI
28. Enter Principle Amount: 10000
29. Enter Interest Rate: 10
30. Enter Time in Year: 5
31. Simple interest=5000.0
32. Total Amount is =15000.0
33. */

3. Write a program to create a class Student with data ‘name, city and age’ along with
method printData() to display the data. Create the two objects s1 ,s2 to declare and
access the values.
4. class Student
5. {
6. String name, city;
7. int age;
8. void printData()
9. {
10. System.out.println("Student name = "+name);
11. System.out.println("Student city = "+city);
12. System.out.println("Student age = "+age);
13. }
14. }
15. class StdTest
16. {
17. public static void main(String args[])
18. {
19. Student s1=new Student();
20. Student s2=new Student();
21. s1.name="Arun";
22. s1.city="Dehli";
23. s1.age=20;
24. s2.name="Rahul";
25. s2.city="Bengaluru";
26. s2.age=19;
27. s1.printData();
28. s2.printData();
29. }
30. }
31. /* File name: StdTest.java
32. C:\Users\welcome\Documents>javac StdTest.java
33. C:\Users\welcome\Documents>java StdTest
34. Student name = Arun
35. Student city = Dehli
36. Student age = 20
37. Student name = Rahul
38. Student city = Bengaluru
39. Student age = 19
40. */

4. Write a Program using parameterized constructor with two parameters id and name.
While creating the objects obj1 and obj2 passed two arguments so that this
constructor gets invoked after creation of obj1 and obj2.
5. class Employee
6. {
7. int empId;
8. String empName;
9. //parameterized constructor with two parameters
10. Employee(int id, String name)
11. {
12. this.empId = id;
13. this.empName = name;
14. }
15. void info()
16. {
17. System.out.println("EmpId: "+empId+" EmpName: "+empName);
18. }
19. }
20.
21. class EmpInfo
22. {
23. public static void main(String args[])
24. {
25. Employee obj1 = new Employee(12345,"Arvind");
26. Employee obj2 = new Employee(12346,"Rizwan");
27. obj1.info();
28. obj2.info();
29. }
30. }
31.
32. /*
33. FileName: EmpInfo.java
34. C:\Users\welcome\Documents>javac EmpInfo.java
35. C:\Users\welcome\Documents>java EmpInfo
36. EmpId: 12345 EmpName: Arvind
37. EmpId: 12346 EmpName: Rizwan
38.
39. */

5. Write a program in JAVA to demonstrate the method and constructor overloading.


6. class C
7. {
8. int p,q;
9. C()
10. {
11. p=10,q=20;
12. System.out.println("Non-Parameterized Constructor");
13. System.out.println("p="+p+" q="+q);
14. }
15. C(int x, int y){
16. p=x;
17. q=y;}
18. int add(int i, int j)
19. {
20. return (i+j);
21. }
22. int add(int i, int j, int k)
23. {
24. return (i+j+k);
25. }
26. float add(float f1, float f2)
27. {
28. return (f1+f2);
29. }
30. void printData()
31. {
32. System.out.println("\nParameterized Constructor");
33. System.out.println("p="+p+" q="+q);
34. }
35. }
36. class MCOverlaoding
37. {
38. public static void main(String args[])
39. {
40. int x=2, y=3, z=4;
41. C c=new C();
42. C c1=new C(x,z );
43. c1.printData();
44. float m=7.2F,n=5.2F;
45. int k=c.add(x,y);
46. int t=c.add(x,y,z);
47. float ft=c.add(m,n);
48. System.out.print("Method Overloading\n");
49. System.out.println("k="+k);
50. System.out.println("t="+t);
51. System.out.println("ft="+ft);
52. }}
53. /*
54. Filename:MCOverlaoding.java
55. C:\Users\welcome\Documents>javac MCOverlaoding.java
56. C:\Users\welcome\Documents>java MCOverlaoding
57. Non-Parameterized Constructor
58. p=10 q=20
59. Parameterized Constructor
60. p=2 q=4
61. Method Overloading
62. k=5
63. t=9
64. ft=12.4
65. */

6. Write a java program to illustrate overriding of methods.


7. import java.util.*;
8. import java.lang.*;
9. import java.io.*;
10.
11. class Parent
12. {
13. int x=100;
14. void show()
15. {
16. System.out.println("x="+x);
17. }
18. }
19.
20. class Child extends Parent
21. {
22. int x=200;
23. void show()
24. {
25. System.out.println("x="+x);
26. }
27. }
28.
29. class Overriding
30. {
31. public static void main(String args[])
32. {
33. Parent obj1 = new Parent();
34. System.out.println("From Parent Class:");
35. obj1.show();
36. Parent obj2 = new Child();
37. System.out.println("From Child Class:");
38. obj2.show();
39. }
40. }
41.
42. /*
43. File Name:Overriding.java
44. C:\Users\welcome\Documents>javac Overriding.java
45. C:\Users\welcome\Documents>java Overriding
46. Output:
47. From Parent Class:
48. x=100
49. From Child Class:
50. x=200
51. */

7. Write a program to sort the given strings in an alphabetical order.


8. import java.util.*;
9. class SortStrings
10. {
11. public static void main(String args[])
12. {
13. //defining an array of type String
14. String city[] = {"Dehli", "Hyderabad", "Bengaluru",
"Chennai", "Mysuru"};
15. int size = city.length;
16. //logic for sorting
17. for(int i = 0; i<size-1; i++)
18. {
19. for (int j = i+1; j<size; j++)
20. {
21. //compares each elements of the array to all the remaining
elements
22. if(city[i].compareTo(city[j])>0)
23. {
24. //swapping array elements
25. String temp = city[i];
26. city[i] = city[j];
27. city[j] = temp;
28. }
29. }
30. }
31. //prints the sorted array in ascending order
32. System.out.println(Arrays.toString(city));
33. }
34. }
35. /*
36. FileName:SortStrings.java
37. C:\Users\welcome\Documents>javac SortStrings.java
38. C:\Users\welcome\Documents>java SortStrings
39. Output:
40. [Bengaluru, Chennai, Dehli, Hyderabad, Mysuru]
41. */

8. Write Java Program to demonstrate the working of a banking-system, where the user
deposit and withdraw amount from the bank account.
9. import java.util.Scanner;
10. import java.io.*;
11. class BankingSystem
12. {
13. double balance; // To store the balance of the user
14. // Constructor to initialize balance
15. BankingSystem()
16. {
17. balance = 0;
18. }
19.
20. // Method to deposit money
21. void deposit(double amount)
22. {
23. if (amount > 0)
24. {
25. balance += amount;
26. System.out.println("Deposited: " + amount);
27. }
28. else
29. {
30. System.out.println("Invalid deposit amount.");
31. }
32. }
33.
34. // Method to withdraw money
35. void withdraw(double amount)
36. {
37. if (amount > 0 && amount <= balance) {
38. balance -= amount;
39. System.out.println("Withdrew: " + amount);
40. }
41. else
42. {
43. System.out.println("Invalid or insufficient funds.");
44. }
45. }
46. // Method to check balance
47. void checkBalance()
48. {
49. System.out.println("Current Balance: " + balance);
50. }
51. }
52.
53. class BankInfo
54. {
55. public static void main(String[] args)
56. {
57. Scanner scanner = new Scanner(System.in);
58. BankingSystem bank = new BankingSystem();
59. boolean exit = false;
60. // Main loop for user input
61. while (!exit)
62. {
63. System.out.println("Enter Your Choice:\n (1:
Deposit, 2: Withdraw, 3: Check Balance, 4: Exit):");
64. int choice = scanner.nextInt();
65. switch(choice)
66. {
67. case 1:
68. System.out.println("Enter deposit
amount:");
69. double depositAmount =
scanner.nextDouble();
70. bank.deposit(depositAmount);
71. break;
72. case 2:
73. System.out.println("Enter withdraw
amount:");
74. double withdrawAmount =
scanner.nextDouble();
75. bank.withdraw(withdrawAmount);
76. break;
77. case 3:
78. bank.checkBalance();
79. break;
80. case 4:
81. exit = true;
82. System.out.println("Exiting the banking
system.");
83. break;
84. default:
85. System.out.println("Invalid command.");
86. break;
87. }
88. }
89. }
90. }
91. /*
92. FileName:BankInfo.java
93. C:\Users\welcome\Documents>javac BankInfo.java
94. C:\Users\welcome\Documents>java BankInfo
95. Enter Your Choice:
96. (1: Deposit, 2: Withdraw, 3: Check Balance, 4: Exit):
97. 1
98. Enter deposit amount:
99. 10000
100. Deposited: 10000.0
101. Enter Your Choice:
102. (1: Deposit, 2: Withdraw, 3: Check Balance, 4: Exit):
103. 3
104. Current Balance: 10000.0
105. Enter Your Choice:
106. (1: Deposit, 2: Withdraw, 3: Check Balance, 4: Exit):
107. 2
108. Enter withdraw amount:
109. 5000
110. Withdrew: 5000.0
111. Enter Your Choice:
112. (1: Deposit, 2: Withdraw, 3: Check Balance, 4: Exit):
113. 3
114. Current Balance: 5000.0
115. Enter Your Choice:
116. (1: Deposit, 2: Withdraw, 3: Check Balance, 4: Exit):
117. 4
118. Exiting the banking system.
119. */

9. Write a java program to implement multi-level inheritance.


class A{
int x=100;
void display(){
System.out.println("x="+x);}}

class B extends A{
int y=200;
void display(){
System.out.println("x="+x);
System.out.println("y="+y);}}

class C extends B{
int z=200;
void display(){
System.out.println("x="+x);
System.out.println("y="+y);
System.out.println("z="+z);}}

class ABCDemo{
public static void main(String args[]){
A a=new A();
B b=new B();
C c=new C();
System.out.println("From Class A:");
a.display();
System.out.println("From Class B:");
b.display();
System.out.println("From Class C:");
c.display();}}

/*
FileName:ABCDemo.java
C:\Users\welcome\Documents>javac ABCDemo.java
C:\Users\welcome\Documents>java ABCDemo
From Class A:
x=100
From Class B:
x=100
y=200
From Class C:
x=100
y=200
z=200
*/

10.Write a java program in which you will declare two interface sum and Add inherits
these interface through class A1 and display their content.
11. interface sum
12. {
13. int x=100;
14. void sum();
15. }
16. interface add
17. {
18. int y=200;
19. void add();
20. }
21.
22. class A1 implements add ,sum
23. {
24. public void sum()
25. {
26. System.out.println(x);
27. }
28. public void add()
29. {
30. System.out.println(y);
31. }
32. }
33.
34. class InterfaceDemo
35. {
36. public static void main(String args[])
37. {
38. A1 a= new A1();
39. a.add();
40. a.sum();
41. }
42. }
43.
44. /*
45. FileName:InterfaceDemo.java
46. C:\Users\welcome\Documents>javac InterfaceDemo.java
47. C:\Users\welcome\Documents>java InterfaceDemo
48. 200
49. 100
50. */

11.Write a program in java if number is less than 10 and greater than 50 it generates the
exception out of range. Else it displays the square of number.
12. import java.util.Scanner;
13.
14. public class NumberSquare {
15.
16. public static void main(String[] args) {
17. Scanner scanner = new Scanner(System.in);
18. System.out.print("Enter a number: ");
19. int number = scanner.nextInt();
20.
21. try {
22. if (number < 10 || number > 50) {
23. throw new Exception("Number is out of range
(10-50)");
24. } else {
25. int square = number * number;
26. System.out.println("Square of " + number +
" is: " + square);
27. }
28. } catch (Exception e) {
29. System.out.println("Error: " + e.getMessage());
30. }
31. }
32. }

12.Write a java program in which thread sleep for 5 sec and change the name of thread.
13. public class ThreadSleepAndRename {
14.
15. public static void main(String[] args) {
16. Thread thread = new Thread() {
17. @Override
18. public void run() {
19. try {
20. System.out.println("Initial Thread
Name: " + Thread.currentThread().getName());
21.
22. // Sleep for 5 seconds
23. Thread.sleep(5000);
24.
25. // Change thread name
26.
Thread.currentThread().setName("NewThreadName");
27.
28. System.out.println("Thread Name after
sleep: " + Thread.currentThread().getName());
29. } catch (InterruptedException e) {
30. e.printStackTrace();
31. }
32. }
33. };
34.
35. thread.start();
36. }
37. }

13.Write a java program to create a file and write the text in it and save the file.
14. import java.io.File;
15. import java.io.FileWriter;
16. import java.io.IOException;
17.
18. public class CreateFile {
19.
20. public static void main(String[] args) {
21. String filePath = "myFile.txt"; // Path to the file
you want to create
22. String content = "This is the text to be written in
the file.";
23.
24. try {
25. // Create a File object
26. File file = new File(filePath);
27.
28. // Create a FileWriter object
29. FileWriter writer = new FileWriter(file);
30.
31. // Write the content to the file
32. writer.write(content);
33.
34. // Close the FileWriter
35. writer.close();
36.
37. System.out.println("File created and content
written successfully!");
38. } catch (IOException e) {
39. System.err.println("An error occurred while
creating or writing to the file: " + e.getMessage());
40. }
41. }
42. }

14.Write a java program to create a user defined package "arithmetic " and define a
class called "arithclass" inside this package, define the methods inside this class for
addition, subtraction and multiplication operations. Import the package arithmetic in
another class and access the methods of arithclass.
15. package arithmetic;
16.
17. public class arithclass {
18. public int add(int a, int b) {
19. return a + b;
20. }
21.
22. public int subtract(int a, int b) {
23. return a - b;
24. }
25.
26. public int multiply(int a, int b) {
27. return a * b;
28. }
29. }
30.
31. // In MainClass.java
32.
33. import arithmetic.arithclass;
34.
35. public class MainClass {
36. public static void main(String[] args) {
37. arithclass obj = new arithclass();
38.
39. int num1 = 10;
40. int num2 = 5;
41.
42. int sum = obj.add(num1, num2);
43. int diff = obj.subtract(num1, num2);
44. int product = obj.multiply(num1, num2);
45.
46. System.out.println("Sum: " + sum);
47. System.out.println("Difference: " + diff);
48. System.out.println("Product: " + product);
49. }
50. }

15.Write a Java event handling program by implementing ActionListener where when a


user clicks on a button then it will display welcome message on a TextField.
16. import javax.swing.*;
17. import java.awt.event.*;
18.
19. public class ButtonClickDemo implements ActionListener {
20. private JFrame frame;
21. private JButton button;
22. private JTextField textField;
23.
24. public ButtonClickDemo() {
25. // Create GUI components
26. frame = new JFrame("Button Click Demo");
27. button = new JButton("Click Me");
28. textField = new JTextField(20);
29.
30. // Add ActionListener to the button
31. button.addActionListener(this);
32.
33. // Add components to the frame
34. frame.add(button);
35. frame.add(textField);
36.
37. // Set frame properties
38. frame.setSize(300, 150);
39.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
40. frame.setLayout(null); // Use null layout for
manual component positioning
41.
42. // Position components (adjust as needed)
43. button.setBounds(100, 50, 100, 30);
44. textField.setBounds(50, 10, 200, 30);
45.
46. frame.setVisible(true);
47. }
48.
49. // Implement the actionPerformed method
50. public void actionPerformed(ActionEvent e) {
51. textField.setText("Welcome!");
52. }
53.
54. public static void main(String[] args) {
55. new ButtonClickDemo();
56. }
57. }

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy