0% found this document useful (0 votes)
16 views39 pages

javaakr (2)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views39 pages

javaakr (2)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

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 (args.length==0) {
System.out.println("please enter arguments");
}
else {
for(int i=0;i<args.length;i++) {
Double num = Double.parseDouble(args[i]);
sum += num;
}
avg = sum/args.length;
}
System.out.println("sum :"+sum);
System.out.println("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<=Math.sqrt(n);i++){
if (n%i==0) {
return false; }
}
return true;
}
public static void main(String[] args) {
if (args.length==1) {
int n = Integer.parseInt(args[0]);
if (isPrime(n)) {
System.out.println( n + " is a prime number.");
}
else{
System.out.println( n + " is not a prime number."); }
}
else {
System.out.println("only one input is required."); }
}
}

Output :

5
EXPERIMENT-3
Aim: WAP to calculate the Simple Interest and Input by the user.

Code :
import java.util.Scanner ;
class value{
public int getval(){
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
return num;
}
}
public class exp3 extends value {
public static void main(String[] args) {
value v = new value();
System.out.println("Principal amount : ");
int p = v.getval();
System.out.println("Rate of interest (per annum) : ");
int r = v.getval();
System.out.println("Time (in years) : ");
int t = v.getval();
System.out.println("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){
this.length = length;
this.width = width;
}
}
class rect extends val {
rect (int length,int width){
super(length, width);
}
public int area(){
return (super.length*super.width);
}
public int perimeter(){
return (2*(super.length+super.width));
}
}
public class exp4 {
public static void main(String[] args) {
rect r = new rect(10,5);
System.out.println("area of rectangular box : " + r.area());
System.out.println("perimeter of rectangular box : " + r.perimeter());
}
}

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;
System.out.println("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){
this.accountNumber = accountNumber;
this.balance = initialBalance;
totalAccount++;
}
public double Getbalance(){
return balance; }
public void display() {
System.out.println(" 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;
System.out.println(" Depoisted $" + amt + " to account number " + accountNumber + " \n
New Balance : " + balance);
}
else {
System.out.println("Deposit amount must be positive."); }

10
}
public void withdraw(int amt ) {
if(amt>0){
if (amt<=balance) {
balance -= amt;
System.out.println(" Withdrew $" + amt + " from account number " + accountNumber +
" \n New Balance : " + balance);
}
else {
System.out.println("Insufficient balance."); }
}
else {
System.out.println("Withdrawal amount must be positive."); }
}
public static void bankInfo() {
System.out.println("Welcome to XYZ Bank. We offer a range of financial services!");
}
}
public class exp6 {
public static void main(String[] args) {
SavingsAccount.bankInfo();
SavingsAccount acc1 = new SavingsAccount("101",1000);
acc1.deposit(500);
acc1.withdraw(100);
SavingsAccount acc2 = new SavingsAccount("102",2000);
acc2.deposit(500);
acc2.withdraw(100);
acc1.display();
acc2.display();
System.out.println(" Total Accounts Created : " + account.Getaccounts());
}
}

Output :

11
12
EXPERIMENT-7
Aim: WAP to find the factorial of a given number using Recursion.

Code :
import java.util.Scanner;
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();
System.out.print("Enter a number : ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.close();
long result = f.fact(n);
System.out.println("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
System.out.println(" walks....(concrete method of base class )");
}
}
class dog extends animal {
public void makesound(){ //overriding abstract method
System.out.println(" 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
a.makesound();;
a.walk();
}
}

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) {
this.str = str;
}

public boolean isEqual(String otherStr) { // Method to check equality of strings


return this.str.equals(otherStr);
}

public String reverse() { // Method to reverse the string


StringBuilder reversedStr = new StringBuilder(this.str);
return reversedStr.reverse().toString();
}

public String changeCase() { // Method to change the case of characters


StringBuilder changedCaseStr = new StringBuilder();
for (char ch : this.str.toCharArray()) {
if (Character.isUpperCase(ch)) {
changedCaseStr.append(Character.toLowerCase(ch));
} else if (Character.isLowerCase(ch)) {
changedCaseStr.append(Character.toUpperCase(ch));
} else {
changedCaseStr.append(ch); // Append non-alphabetic characters as is
}
}
return changedCaseStr.toString();

15
}

public String getString() { // Getter for the original string


return this.str;
}

public static void main(String[] args) {


exp9 e = new exp9("HelloWorld");

// Check equality
String testString = "HelloWorld";
System.out.println("Is Equal to '" + testString + "': " + e.isEqual(testString));

// Reverse the string


System.out.println("Reversed String: " + e.reverse());

// Change case
System.out.println("Case Changed String: " + e.changeCase());
}
}

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];
System.out.println(z);
}
catch(ArithmeticException ae)
{
System.out.println("ArithmeticException caught: Division by zero is not allowed.");
}
catch(ArrayIndexOutOfBoundsException ai)
{
System.out.println("ArrayIndexOutOfBoundsException caught: Invalid array index.");
}
catch(Exception e){
System.out.println("General Exception caught: " + e.getMessage());
}
finally {
System.out.println("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 :

// ext.java (no package)


public class ext {
// Member variable
public String message = "Hello from external class!";

// Member method
public void displayMessage() {
System.out.println("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();
System.out.println(externalObj.message); // Accessing public field from ext
externalObj.displayMessage(); // Calling public method from ext

// Accessing same package members (same package as exp11)


exp11 Obj = new exp11();
Obj.display();
}

// Method in the same class (exp11)

18
public void display() {
System.out.println("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) {
System.out.println("division is not allowed by zero.");
}

return x/y;
}
}

 Mainfile
package mainfile;
import externalPackage.calc;

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
System.out.println(" Addition : " + add(5,10));
System.out.println( " Subtarction : " + sub(15,20));
// accessing members of external package
calc c = new calc();
System.out.println(" Multiplication : " + c.mul(5,10));
System.out.println( " Division : " + c.div(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() {
System.out.println(" in display ");
}
}

class C extends B {
public void show(){
System.out.println(" in show ");
}
}

public class exp13 {


public static void main(String[] args) {
C c1 = new C();
c1.display();
c1.show();
System.out.println(" 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
System.out.println(" Access Granted ");
}
finally{}
}
public static void main(String[] args) {
try {
checkAge(16);
} catch (IllegalArgumentException e) {
System.out.println( " Caught Exception : " + e.getMessage());
}
}
}

Output :

24
EXPERIMENT-15
Aim: WAP to create a thread that Implement the Runable interface.

Code :
class A implements Runnable {
public void run() {
System.out.println("hi");
}
}

public class exp15 {


public static void main(String[] args) {
A a1 = new A();
Thread t1 = new Thread(a1);
t1.start();
}
}

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) {
Thread.currentThread().interrupt();
System.out.println("Producer interrupted");
}
}
data = value;
hasData = true;
System.out.println("Produced: " + data);
notify();
}

public synchronized int consume() {


while (!hasData) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Consumer interrupted");
}
}
hasData = false;
System.out.println("Consumed: " + data);
26
notify();
return data;
}
}

class Producer extends Thread {


private SharedResource resource;

public Producer(SharedResource resource) {


this.resource = resource;
}

public void run() {


for (int i = 1; i <= 5; i++) {
resource.produce(i);
}
}
}

class Consumer extends Thread {


private SharedResource resource;

public Consumer(SharedResource resource) {


this.resource = resource;
}

public void run() {


for (int i = 1; i <= 5; i++) {
resource.consume();
}
}
}

public class exp16 {


27
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Producer producer = new Producer(resource);
Consumer consumer = new Consumer(resource);

producer.start();
consumer.start();
}
}

Output :

28
EXPERIMENT-17
Aim: WAP to Draw the line, Rectangle, oval, text using the graphics method.

Code :

import javax.swing.*;
import java.awt.*;

public class exp17 extends JPanel {

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(50, 50, 300, 50);
g.drawRect(50, 100, 200, 100);
g.drawOval(50, 250, 200, 100);
g.drawString("Graphics in Java", 100, 400);
}

public static void main(String[] args) {


JFrame frame = new JFrame("Graphics in JFrame");
frame.add(new exp17());
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Output :

29
30
EXPERIMENT-18
Aim: WAP to Implement the Flow layout And Border Layout.

Code :

 Flow Layout :

import javax.swing.*;
import java.awt.*;

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 javax.swing.*;
import java.awt.*;

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, BorderLayout.NORTH);
add(buttonSouth, BorderLayout.SOUTH);
add(buttonEast, BorderLayout.EAST);
add(buttonWest, BorderLayout.WEST);
add(buttonCenter, BorderLayout.CENTER);

// 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 javax.swing.*;
import java.awt.*;

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 java.awt.*;
import javax.swing.*;
import java.awt.event.*;

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();

cPane.setLayout(crd);

// creating the buttons


btn1 = new JButton("Apple");
btn2 = new JButton("Boy");
btn3 = new JButton("Cat");

// adding listeners to it
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);

cPane.add("a", btn1); // first card is the button btn1


cPane.add("b", btn2); // first card is the button btn2
cPane.add("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
crd.next(cPane);
}
public static void main(String argvs[])
36
{
exp19 crdl = new exp19();
crdl.setSize(300, 300);
crdl.setVisible(true);
crdl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

Output :

37
EXPERIMENT-20
Aim: Create a database Connectivity through JDBC & MYSQL.

Code :

import java.sql.*;

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 = DriverManager.getConnection(url, username, password);
System.out.println("Connected to the database!");

// Step 2: Create a statement object to execute queries


Statement statement = connection.createStatement();

// Step 3: Execute a simple query


String query = "SELECT * FROM users";
ResultSet resultSet = statement.executeQuery(query);

// Step 4: Process the result set


while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");

38
String email = resultSet.getString("email");
System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
}

// Clean up
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close(); // Close the connection when done
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Output :

39

You might also like