MAHARSHI DAYANAND
UNIVERSITY
PROGRAMMING
IN JAVA LAB
(LC-CSE-327G)
Name: Akriti
Course: B-Tech (CSE)
Session: 2022-2026
Enrollment No: 2213081362
1
INDEX
LIST OF PRACTICALS
S. NO PRACTICAL DATE SIGN
1. WAP to find the average and sum of the N 30/08/2024
numbers using Command line argument.
2. WAP to Test the Prime number. 02/09/2024
3. WAP to calculate the Simple Interest and 07/09/2024
Input by the user.
4. WAP to create a Simple class to find out 11/09/2024
the Area and perimeter of rectangular box
using super and this keyword.
5. WAP to find G.C.D of the number. 15/09/2024
6. WAP to design a class account using the 20/09/2024
inheritance and static that shows all
functions of bank (withdrawal, deposit).
7. WAP to find the factorial of a given 24/09/2024
number using Recursion.
8. WAP to design a class using abstract 29/09/2024
Methods and Classes.
9. WAP to design a String class that perform 02/10/2024
String Methods (Equal, Reverse the string,
change case).
10. WAP to handle the Exception using try 07/10/2024
and multiple catch block.
11. WAP to Create a package that access the 11/10/2024
member of external class as well as
same package.
12. WAP that import the user define package 16/10/2024
and access the Member variable of classes
that Contained by Package.
13. WAP that show the partial 20/10/2024
implementation of Interface.
14. WAP to Handle the user defined 23/10/2024
Exception using throw keyword.
15. WAP to create a thread that Implement 27/10/2024
the Runable interface.
2
16. WAP to Implement Interthread 31/10/2024
communication.
17. WAP to Draw the line, Rectangle, oval, 03/11/2024
text using the graphics method.
18. WAP to Implement the Flow layout And 06/11/2024
Border Layout.
19. WAP to Implement the Grid Layout and 09/11/2024
Card Layout.
20. Create a database Connectivity through 11/11/2024
JDBC & MYSQL.
3
EXPERIMENT-1
Aim: WAP to find the average and sum of the N numbers using Command line
argument.
Code :
public class exp1{
public static void main(String[] args) {
double sum = 0, avg = 0;
if ([Link]==0) {
[Link]("please enter arguments");
}
else {
for(int i=0;i<[Link];i++) {
Double num = [Link](args[i]);
sum += num;
}
avg = sum/[Link];
}
[Link]("sum :"+sum);
[Link]("average :"+avg);
}
}
Output :
4
EXPERIMENT-2
Aim: WAP to Test the Prime number.
Code :
public class exp2 {
public static boolean isPrime(int n){
if (n<=1) {
return false;
}
for(int i = 2 ; i<=[Link](n);i++){
if (n%i==0) {
return false; }
}
return true;
}
public static void main(String[] args) {
if ([Link]==1) {
int n = [Link](args[0]);
if (isPrime(n)) {
[Link]( n + " is a prime number.");
}
else{
[Link]( n + " is not a prime number."); }
}
else {
[Link]("only one input is required."); }
}
}
Output :
5
EXPERIMENT-3
Aim: WAP to calculate the Simple Interest and Input by the user.
Code :
import [Link] ;
class value{
public int getval(){
Scanner sc = new Scanner([Link]);
int num = [Link]();
return num;
}
}
public class exp3 extends value {
public static void main(String[] args) {
value v = new value();
[Link]("Principal amount : ");
int p = [Link]();
[Link]("Rate of interest (per annum) : ");
int r = [Link]();
[Link]("Time (in years) : ");
int t = [Link]();
[Link]("Simple Interest : " + ((p*r*t)/100));
}
}
Output :
6
EXPERIMENT-4
Aim: WAP to create a Simple class to find out the Area and perimeter of
rectangular box using super and this keyword
Code :
class val {
int length , width;
val(int length , int width){
[Link] = length;
[Link] = width;
}
}
class rect extends val {
rect (int length,int width){
super(length, width);
}
public int area(){
return ([Link]*[Link]);
}
public int perimeter(){
return (2*([Link]+[Link]));
}
}
public class exp4 {
public static void main(String[] args) {
rect r = new rect(10,5);
[Link]("area of rectangular box : " + [Link]());
[Link]("perimeter of rectangular box : " + [Link]());
}
}
Output :
7
8
EXPERIMENT-5
Aim: WAP to find G.C.D of the number.
Code :
public class exp5 {
public static int gcd(int a , int b){
int temp;
while(b!=0){
temp=b;
b=a%b;
a=temp;
}
return a;
}
public static void main(String[] args) {
int num1 = 56;
int num2 = 98;
[Link]("GCD of " + num1 + " and " + num2 + " is " + gcd(num1, num2));
}
}
Output :
9
EXPERIMENT-6
Aim: WAP to create a Simple class to find out the Area and perimeter of
rectangular box using super and this keyword.
Code :
class account{
private static int totalAccount;
protected String accountNumber;
protected double balance;
public account(String accountNumber,double initialBalance){
[Link] = accountNumber;
[Link] = initialBalance;
totalAccount++;
}
public double Getbalance(){
return balance; }
public void display() {
[Link](" Account Number : " + accountNumber + "\n Balance : " + balance);
}
public static int Getaccounts(){
return totalAccount; }
}
class SavingsAccount extends account{
public SavingsAccount(String accountNumber , double initialBalance){
super(accountNumber, initialBalance );
}
public void deposit(double amt){
if (amt>0) {
balance+=amt;
[Link](" Depoisted $" + amt + " to account number " + accountNumber + " \n
New Balance : " + balance);
}
else {
[Link]("Deposit amount must be positive."); }
10
}
public void withdraw(int amt ) {
if(amt>0){
if (amt<=balance) {
balance -= amt;
[Link](" Withdrew $" + amt + " from account number " + accountNumber +
" \n New Balance : " + balance);
}
else {
[Link]("Insufficient balance."); }
}
else {
[Link]("Withdrawal amount must be positive."); }
}
public static void bankInfo() {
[Link]("Welcome to XYZ Bank. We offer a range of financial services!");
}
}
public class exp6 {
public static void main(String[] args) {
[Link]();
SavingsAccount acc1 = new SavingsAccount("101",1000);
[Link](500);
[Link](100);
SavingsAccount acc2 = new SavingsAccount("102",2000);
[Link](500);
[Link](100);
[Link]();
[Link]();
[Link](" Total Accounts Created : " + [Link]());
}
}
Output :
11
12
EXPERIMENT-7
Aim: WAP to find the factorial of a given number using Recursion.
Code :
import [Link];
class factorial{
public long fact(int n){
if (n==0||n==1) {
return 1;
}
else {
return (n*fact(n-1));
}
}
}
public class exp7 {
public static void main(String[] args) {
factorial f = new factorial();
[Link]("Enter a number : ");
Scanner sc = new Scanner([Link]);
int n = [Link]();
[Link]();
long result = [Link](n);
[Link]("The factorial of " + n + " is " + result);
}
}
Output :
13
EXPERIMENT-8
Aim: WAP to design a class using abstract Methods and Classes.
Code :
abstract class animal {
abstract void makesound(); // this method must be overridden by concrete class
public void walk(){ //abstract classes can have both abstract and concrete methods
[Link](" walks....(concrete method of base class )");
}
}
class dog extends animal {
public void makesound(){ //overriding abstract method
[Link](" dog barks....(overridden method in derived class )"); }
}
public class exp8 {
public static void main(String[] args) {
animal a = new dog(); // we can only create a reference of an abstract class
[Link]();;
[Link]();
}
}
Output :
14
EXPERIMENT-9
Aim: WAP to design a String class that perform String Methods (Equal, Reverse
the string, change case).
Code :
public class exp9 {
private String str;
public exp9(String str) {
[Link] = str;
}
public boolean isEqual(String otherStr) { // Method to check equality of strings
return [Link](otherStr);
}
public String reverse() { // Method to reverse the string
StringBuilder reversedStr = new StringBuilder([Link]);
return [Link]().toString();
}
public String changeCase() { // Method to change the case of characters
StringBuilder changedCaseStr = new StringBuilder();
for (char ch : [Link]()) {
if ([Link](ch)) {
[Link]([Link](ch));
} else if ([Link](ch)) {
[Link]([Link](ch));
} else {
[Link](ch); // Append non-alphabetic characters as is
}
}
return [Link]();
15
}
public String getString() { // Getter for the original string
return [Link];
}
public static void main(String[] args) {
exp9 e = new exp9("HelloWorld");
// Check equality
String testString = "HelloWorld";
[Link]("Is Equal to '" + testString + "': " + [Link](testString));
// Reverse the string
[Link]("Reversed String: " + [Link]());
// Change case
[Link]("Case Changed String: " + [Link]());
}
}
Output :
16
EXPERIMENT-10
Aim: WAP to handle the Exception using try and multiple catch block.
Code :
public class exp10 {
public static void main(String[] args) {
int x = 0 , y = 10;
int arr[]= new int[5];
try{
y = y/x; // this line will give an arithmetic exception that's why the following code in try
block will not execute
int z = arr[5];
[Link](z);
}
catch(ArithmeticException ae)
{
[Link]("ArithmeticException caught: Division by zero is not allowed.");
}
catch(ArrayIndexOutOfBoundsException ai)
{
[Link]("ArrayIndexOutOfBoundsException caught: Invalid array index.");
}
catch(Exception e){
[Link]("General Exception caught: " + [Link]());
}
finally {
[Link]("Finally block executed.");
}}}
Output :
17
EXPERIMENT-11
Aim: WAP to Create a package that access the member of external class as well
as same package.
Code :
External File :
// [Link] (no package)
public class ext {
// Member variable
public String message = "Hello from external class!";
// Member method
public void displayMessage() {
[Link]("Message from external class: " + message);
}
}
Main Package :
package p;
public class exp11 {
public static void main(String[] args) {
// Accessing external class member (ext is in the default package)
ext externalObj = new ext();
[Link]([Link]); // Accessing public field from ext
[Link](); // Calling public method from ext
// Accessing same package members (same package as exp11)
exp11 Obj = new exp11();
[Link]();
}
// Method in the same class (exp11)
18
public void display() {
[Link]("This is a method in the same class.");
}
}
Output :
19
EXPERIMENT-12
Aim: WAP that import the user define package and access the Member variable
of classes that contained by Package.
Code :
External Package :
package externalPackage ;
public class calc {
public int mul(int x , int y){
return x*y;
}
public int div(int x , int y){
if (y==0) {
[Link]("division is not allowed by zero.");
}
return x/y;
}
}
Mainfile
package mainfile;
import [Link];
public class exp12 {
public static int add(int x , int y){
return x+y; }
public static int sub(int x , int y){
return x-y; }
public static void main(String[] args) {
// accessing members of same package
20
[Link](" Addition : " + add(5,10));
[Link]( " Subtarction : " + sub(15,20));
// accessing members of external package
calc c = new calc();
[Link](" Multiplication : " + [Link](5,10));
[Link]( " Division : " + [Link](50,10));
}
}
Output :
21
EXPERIMENT-13
Aim: WAP that show the partial implementation of Interface.
Code :
interface A {
int x = 45; // variables in interface are by default final and static
void display(); // methods in interface are by default public and abstract
void show();
}
abstract class B implements A {
public void display() {
[Link](" in display ");
}
}
class C extends B {
public void show(){
[Link](" in show ");
}
}
public class exp13 {
public static void main(String[] args) {
C c1 = new C();
[Link]();
[Link]();
[Link](" Accessing interface variable directly : \n " + A.x);
}
}
Output :
22
23
EXPERIMENT-14
Aim: WAP to Handle the user defined Exception using throw keyword.
Code :
public class exp14 {
public static void checkAge(int x) {
try{
if(x<18){
throw new IllegalArgumentException(" Age must be 18 or above " );
}
else
[Link](" Access Granted ");
}
finally{}
}
public static void main(String[] args) {
try {
checkAge(16);
} catch (IllegalArgumentException e) {
[Link]( " Caught Exception : " + [Link]());
}
}
}
Output :
24
EXPERIMENT-15
Aim: WAP to create a thread that Implement the Runable interface.
Code :
class A implements Runnable {
public void run() {
[Link]("hi");
}
}
public class exp15 {
public static void main(String[] args) {
A a1 = new A();
Thread t1 = new Thread(a1);
[Link]();
}
}
Output :
25
EXPERIMENT-16
Aim: WAP to Implement Interthread communication.
Code :
class SharedResource {
private int data;
private boolean hasData = false;
public synchronized void produce(int value) {
while (hasData) {
try {
wait();
} catch (InterruptedException e) {
[Link]().interrupt();
[Link]("Producer interrupted");
}
}
data = value;
hasData = true;
[Link]("Produced: " + data);
notify();
}
public synchronized int consume() {
while (!hasData) {
try {
wait();
} catch (InterruptedException e) {
[Link]().interrupt();
[Link]("Consumer interrupted");
}
}
hasData = false;
[Link]("Consumed: " + data);
26
notify();
return data;
}
}
class Producer extends Thread {
private SharedResource resource;
public Producer(SharedResource resource) {
[Link] = resource;
}
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](i);
}
}
}
class Consumer extends Thread {
private SharedResource resource;
public Consumer(SharedResource resource) {
[Link] = resource;
}
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]();
}
}
}
public class exp16 {
27
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Producer producer = new Producer(resource);
Consumer consumer = new Consumer(resource);
[Link]();
[Link]();
}
}
Output :
28
EXPERIMENT-17
Aim: WAP to Draw the line, Rectangle, oval, text using the graphics method.
Code :
import [Link].*;
import [Link].*;
public class exp17 extends JPanel {
@Override
protected void paintComponent(Graphics g) {
[Link](g);
[Link](50, 50, 300, 50);
[Link](50, 100, 200, 100);
[Link](50, 250, 200, 100);
[Link]("Graphics in Java", 100, 400);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Graphics in JFrame");
[Link](new exp17());
[Link](400, 400);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Output :
29
30
EXPERIMENT-18
Aim: WAP to Implement the Flow layout And Border Layout.
Code :
Flow Layout :
import [Link].*;
import [Link].*;
public class FlowLayoutExample extends JFrame {
public FlowLayoutExample() {
// Set the title for the window
setTitle("FlowLayout Example");
// Set the layout to FlowLayout
setLayout(new FlowLayout());
// Create some buttons for FlowLayout
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
// Add buttons to the frame
add(button1);
add(button2);
add(button3);
// Set window size and behavior
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
31
public static void main(String[] args) {
new FlowLayoutExample();
}
}
Output :
Border Layout :
import [Link].*;
import [Link].*;
public class exp19 extends JFrame {
public BorderLayoutExample() {
// Set the title for the window
setTitle("BorderLayout Example");
// Set the layout to BorderLayout
setLayout(new BorderLayout());
// Create buttons for each region of BorderLayout
JButton buttonNorth = new JButton("North");
JButton buttonSouth = new JButton("South");
32
JButton buttonEast = new JButton("East");
JButton buttonWest = new JButton("West");
JButton buttonCenter = new JButton("Center");
// Add buttons to their respective positions in BorderLayout
add(buttonNorth, [Link]);
add(buttonSouth, [Link]);
add(buttonEast, [Link]);
add(buttonWest, [Link]);
add(buttonCenter, [Link]);
// Set window size and behavior
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new BorderLayoutExample();
}}
Output :
33
EXPERIMENT-19
Aim: WAP to Implement the Grid layout And Card Layout.
Code :
Grid Layout :
import [Link].*;
import [Link].*;
public class GridLayoutExample extends JFrame {
public GridLayoutExample() {
// Set the title for the window
setTitle("GridLayout Example");
// Set the layout to GridLayout (2 rows, 3 columns)
setLayout(new GridLayout(2, 3));
// Create buttons for the grid layout
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
JButton button4 = new JButton("Button 4");
JButton button5 = new JButton("Button 5");
JButton button6 = new JButton("Button 6");
// Add buttons to the frame
add(button1);
add(button2);
add(button3);
add(button4);
add(button5);
add(button6);
34
// Set window size and behavior
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new GridLayoutExample();
}
}
Output :
Card Layout :
import [Link].*;
import [Link].*;
import [Link].*;
public class exp19 extends JFrame implements ActionListener
{
CardLayout crd;
// button variables to hold the references of buttons
JButton btn1, btn2, btn3;
35
Container cPane;
// constructor of the class
exp19()
{
cPane = getContentPane();
crd = new CardLayout();
[Link](crd);
// creating the buttons
btn1 = new JButton("Apple");
btn2 = new JButton("Boy");
btn3 = new JButton("Cat");
// adding listeners to it
[Link](this);
[Link](this);
[Link](this);
[Link]("a", btn1); // first card is the button btn1
[Link]("b", btn2); // first card is the button btn2
[Link]("c", btn3); // first card is the button btn3
}
public void actionPerformed(ActionEvent e)
{
// Upon clicking the button, the next card of the container is shown
// after the last card, again, the first card of the container is shown upon clicking
[Link](cPane);
}
public static void main(String argvs[])
36
{
exp19 crdl = new exp19();
[Link](300, 300);
[Link](true);
[Link](EXIT_ON_CLOSE);
}
}
Output :
37
EXPERIMENT-20
Aim: Create a database Connectivity through JDBC & MYSQL.
Code :
import [Link].*;
public class JdbcExample {
public static void main(String[] args) {
// Database credentials
String url = "jdbc:mysql://localhost:3306/testdb"; // Change 'localhost' to your MySQL host
String username = "root"; // Your MySQL username
String password = "password"; // Your MySQL password
// JDBC connection setup
Connection connection = null;
try {
// Step 1: Open a connection
connection = [Link](url, username, password);
[Link]("Connected to the database!");
// Step 2: Create a statement object to execute queries
Statement statement = [Link]();
// Step 3: Execute a simple query
String query = "SELECT * FROM users";
ResultSet resultSet = [Link](query);
// Step 4: Process the result set
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
38
String email = [Link]("email");
[Link]("ID: " + id + ", Name: " + name + ", Email: " + email);
}
// Clean up
[Link]();
[Link]();
} catch (SQLException e) {
[Link]();
} finally {
try {
if (connection != null) {
[Link](); // Close the connection when done
}
} catch (SQLException e) {
[Link]();
}
}
}
}
Output :
39