javaakr (2)
javaakr (2)
javaakr (2)
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
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 :
15
}
// Check equality
String testString = "HelloWorld";
System.out.println("Is Equal to '" + testString + "': " + e.isEqual(testString));
// 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 :
// 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
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 ;
return x/y;
}
}
Mainfile
package mainfile;
import externalPackage.calc;
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();
}
class C extends B {
public void show(){
System.out.println(" in show ");
}
}
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");
}
}
Output :
25
EXPERIMENT-16
Aim: WAP to Implement Interthread communication.
Code :
class SharedResource {
private int data;
private boolean hasData = false;
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.*;
@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);
}
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 FlowLayoutExample() {
// Set the title for the window
setTitle("FlowLayout Example");
Output :
Border Layout :
import javax.swing.*;
import java.awt.*;
public BorderLayoutExample() {
// Set the title for the window
setTitle("BorderLayout Example");
32
JButton buttonEast = new JButton("East");
JButton buttonWest = new JButton("West");
JButton buttonCenter = new JButton("Center");
33
EXPERIMENT-19
Aim: WAP to Implement the Grid layout And Card Layout.
Code :
Grid Layout :
import javax.swing.*;
import java.awt.*;
public GridLayoutExample() {
// Set the title for the window
setTitle("GridLayout Example");
Output :
Card Layout :
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
CardLayout crd;
35
Container cPane;
cPane = getContentPane();
cPane.setLayout(crd);
// adding listeners to it
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
}
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.*;
try {
// Step 1: Open a connection
connection = DriverManager.getConnection(url, username, password);
System.out.println("Connected to the database!");
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