Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
24 views

JavaPractical Merged Removed

Uploaded by

sachinnouxu
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)
24 views

JavaPractical Merged Removed

Uploaded by

sachinnouxu
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/ 27

P age |1

A practical file of
DBMS
Subject Code: BCA-506

Bachelors of Computer Application (BCA)

Harlal Institute of Management & Technology, Greater Noida


(Affiliated to CCSU, Meerut)
Knowledge park-I, Institution Area, Greater Noida 201306

SUBMITTED TO: SUBMITTED BY:

Mr.Narendra Upadhyay Sir Name: Sachin


Roll no: 210916106059
Semester: V
INDEX

S_no. TITLE Page no.

1. Write a program to find number of digits in a number input by the user.

2. Write a program to find the factorial of a number using recursion.

3. Write a java program to find product of two matrices in java.

4. Write a program to print fibnonic series in java

5. Write a program to print diamond pattern in java.

6. Write a program to implement static variable in java.

7. Write a program to implement constructors in java.

8. Create a user defined package and use their classes in java.

9. Write a program to implement simple inheritance in java.

10. Write a program to implement Hierarchical inheritance in java

11. Write a program to implement method overloading in java.

12. Write a program to implement method overriding in java.

13. Write a program to implement dynamic method dispatch in java.

14. Write a program to implement abstract class in java.

15. Write a program to implement interfaces in java.

16. Write a simple Multithread program in java.

17. Write a program to handle try and multiple catch block.

18. Create a custom exception and throw in case of age<18 for voting.

19. Create a student table using <TABLE> tag in html.

20. Write a program to draw different shapes using graphics methods.

21. Create a login form in AWT.

22. Create a calculator using event listener in java.


Q1:- Write a program to find number of digits in a number input by the user.
Ans:- import java.util.Scanner;

public class NumberOfDigits {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
long number = scanner.nextLong();

int digitCount = countDigits(number);


System.out.println("Number of digits: " + digitCount);

scanner.close();
}

public static int countDigits(long number) {


number = Math.abs(number);

int count = 0;
while (number > 0) {
number = number / 10;
count++;
}

return count;
}
}

OUTPUT:-
Q2:-Write a program to find the factorial of a number using recursion.
Ans:- import java.util.Scanner;

public class Factorial {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a non-negative integer: ");
int number = scanner.nextInt();

if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
long factorial = calculateFactorial(number);
System.out.println("Factorial of " + number + " is: " + factorial);
}

scanner.close();
}

public static long calculateFactorial(int n) {


if (n == 0 || n == 1) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
}

OUTPUT:-
Q3:- Write a java program to find product of two matrices in java.
Ans:- import java.util.Scanner;

public class MatrixMultiplication {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows for the first matrix: ");
int rows1 = scanner.nextInt();
System.out.print("Enter the number of columns for the first matrix: ");
int columns1 = scanner.nextInt();
System.out.print("Enter the number of rows for the second matrix: ");
int rows2 = scanner.nextInt();
System.out.print("Enter the number of columns for the second matrix: ");
int columns2 = scanner.nextInt();
if (columns1 != rows2) {
System.out.println("Matrix multiplication is not possible.");
Return;}
int[][] matrix1 = new int[rows1][columns1];
int[][] matrix2 = new int[rows2][columns2];
int[][] resultMatrix = new int[rows1][columns2];
System.out.println("Enter elements of the first matrix:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < columns1; j++) {
matrix1[i][j] = scanner.nextInt();
}
}

System.out.println("Enter elements of the second matrix:");


for (int i = 0; i < rows2; i++) {
for (int j = 0; j < columns2; j++) {
matrix2[i][j] = scanner.nextInt();
}
} for (int i = 0; i < rows1; i++) {
for (int j = 0; j < columns2; j++) {
for (int k = 0; k < columns1; k++) {
resultMatrix[i][j] += matrix1[i][k] * matrix2[k][j];
System.out.println("Resultant Matrix after multiplication:");}}}
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < columns2; j++) {
System.out.print(resultMatrix[i][j] + " ");
}
System.out.println();
}
scanner.close();
}
}
OUTPUT:-
Q4:- Write a program to print fibnonic series in java.
Ans:- import java.util.Scanner;

public class FibonacciSeries {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms in the Fibonacci series: ");
int n = scanner.nextInt();

System.out.println("Fibonacci Series:");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}

scanner.close();
}

public static int fibonacci(int n) {


if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

OUTPUT:-
Q5:- Write a program to implement static variable in java.
Ans:- public class StaticVariableExample {
// Static variable
static int count = 0;

public StaticVariableExample() {
// Increment the count each time an object is created
count++;
}

public static void main(String[] args) {


// Creating objects of the class
StaticVariableExample obj1 = new StaticVariableExample();
StaticVariableExample obj2 = new StaticVariableExample();
StaticVariableExample obj3 = new StaticVariableExample();

// Printing the value of the static variable


System.out.println("Number of objects created: " + StaticVariableExample.count);
}
}

OUTPUT:-
Q6:- Write a program to print diamond pattern in java.
Ans:- import java.util.Scanner;

public class DiamondPattern {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows (odd number): ");
int n = scanner.nextInt();

if (n % 2 == 0) {
System.out.println("Please enter an odd number.");
return;
}

int spaces = n / 2;
int stars = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= spaces; j++) {
System.out.print(" ");
}
for (int j = 1; j <= stars; j++) {
System.out.print("*");
}
System.out.println();

if (i <= n / 2) {
spaces--;
stars += 2;
} else {
spaces++;
stars -= 2;
}
}

scanner.close();
}
}

OUTPUT:-
Q7:-Write a program to implement constructors in java.
Ans:- public class Car {
private String make;
private String model;
private int year;

// Default constructor
public Car() {
make = "Toyota";
model = "Corolla";
year = 2023;
}

// Parameterized constructor
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}

// Method to display car details


public void displayCarDetails() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}

public static void main(String[] args) {


// Creating objects using constructors
Car defaultCar = new Car(); // Default constructor
Car customCar = new Car("Ford", "Mustang", 2024); // Parameterized constructor

// Displaying car details


System.out.println("Default Car Details:");
defaultCar.displayCarDetails();
System.out.println("\nCustom Car Details:");
customCar.displayCarDetails();
}
}

OUTPUT:-
Q8:-Create a user defined package and use their classes in java.
Ans:- package myPackage;

public class Calculator {


public static int add(int a, int b) {
return a + b;
}
public static int subtract(int a, int b) {
return a - b;
}

public static int multiply(int a, int b) {


return a * b;
}

public static double divide(double a, double b) {


if (b == 0) {
throw new IllegalArgumentException("Cannot divide by zero");
}
return a / b;
}
}

------------------------------------And here are the contents of Person.java-----------------------------------------------

package myPackage;

public class Person {


private String name;
private int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}

public void displayInfo() {


System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
--------------------------Now let’s create a java program that uses these classes:-----------------------------
import myPackage.Calculator;
import myPackage.Person;

public class Main {


public static void main(String[] args) {
// Using Calculator class
System.out.println("Addition: " + Calculator.add(5, 3));
System.out.println("Subtraction: " + Calculator.subtract(5, 3));
System.out.println("Multiplication: " + Calculator.multiply(5, 3));
System.out.println("Division: " + Calculator.divide(5.0, 3.0));

// Using Person class


Person person = new Person("Alice", 30);
person.displayInfo();
}
}

OUTPUT:-
Q9:-Write a program to implement simple inheritance in java.
Ans:- // Parent class
class Shape {
// Method to calculate area
double calculateArea() {
return 0;
}
}

// Child class inheriting from Shape


class Rectangle extends Shape {
double length;
double width;
double calculateArea() {
return length * width;
}
}
class Circle extends Shape {
double radius;
double calculateArea() {
return Math.PI * radius * radius;
}
}

public class Main {


public static void main(String[] args) {
// Creating objects of child classes
Rectangle rect = new Rectangle();
Circle circle = new Circle();

// Setting values for rectangle


rect.length = 5;
rect.width = 3;
circle.radius = 4;

// Calculating and printing areas


System.out.println("Area of Rectangle: " + rect.calculateArea());
System.out.println("Area of Circle: " + circle.calculateArea());
}
}

OUTPUT:-
Q10:-Write a program to implement Hierarchical inheritance in java.
Ans:- // Parent class
class Employee {
String name;
double salary;

Employee(String name, double salary) {


this.name = name;
this.salary = salary;
}

void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Salary: $" + salary);}}
class Manager extends Employee {
String department;

Manager(String name, double salary, String department) {


super(name, salary);
this.department = department;
}
void displayDetails() {
super.displayDetails();
System.out.println("Department: " + department);
}
}
class Clerk extends Employee {
String role;

Clerk(String name, double salary, String role) {


super(name, salary);
this.role = role;
}
void displayDetails() {
super.displayDetails();
System.out.println("Role: " + role);}}

public class Main {


public static void main(String[] args) {
// Creating objects of child classes
Manager manager = new Manager("John Doe", 5000.0, "Human Resources");
Clerk clerk = new Clerk("Alice Smith", 3000.0, "Data Entry");
System.out.println("Manager Details:");
manager.displayDetails();
System.out.println("\nClerk Details:");
clerk.displayDetails();}}

OUTPUT:-
Q11:- Write a program to implement method overloading in java.
Ans:- public class MethodOverloadingExample {

void add(int a, int b) {


System.out.println("Sum of two integers: " + (a + b));
}

void add(double a, double b) {


System.out.println("Sum of two doubles: " + (a + b));
}

void add(int a, int b, int c) {


System.out.println("Sum of three integers: " + (a + b + c));
}

void concatenate(String str1, String str2) {


System.out.println("Concatenated string: " + str1 + str2);
}

void concatenate(String str1, String str2, String str3) {


System.out.println("Concatenated string: " + str1 + str2 + str3);
}

public static void main(String[] args) {


MethodOverloadingExample obj = new MethodOverloadingExample();

// Calling methods with different signatures


obj.add(5, 10);
obj.add(5.5, 10.5);
obj.add(5, 10, 15);

obj.concatenate("Hello, ", "World!");


obj.concatenate("Hello, ", "beautiful ", "World!");
}
}

OUTPUT:-
Q12:-Write a program to implement method overriding in java.
Ans:- class Shape {
double area() {
return 0;}}

class Rectangle extends Shape {


double length;
double breadth;

Rectangle(double length, double breadth) {


this.length = length;
this.breadth = breadth;
}
double area() {
return length * breadth;
}
}

class Circle extends Shape {


double radius;

Circle(double radius) {
this.radius = radius;
}
double area() {
return Math.PI * radius * radius;
}
}

public class Main {


public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 3);
System.out.println("Area of rectangle: " + rectangle.area()); // Output: 15.0

Circle circle = new Circle(4);


System.out.println("Area of circle: " + circle.area()); // Output: 50.26548245743669
}
}

OUTPUT:-
Q13:-Write a program to implement dynamic method dispatch in java.
Ans:- // Superclass
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}

class Circle extends Shape {


void draw() {
System.out.println("Drawing a circle");
}
}

class Rectangle extends Shape {


@Override
void draw() {
System.out.println("Drawing a rectangle");
}
}
class Triangle extends Shape {

void draw() {
System.out.println("Drawing a triangle");
}
}
public class DynamicMethodDispatch {
public static void main(String[] args) {
Shape shape1 = new Circle(); // Circle object
Shape shape2 = new Rectangle(); // Rectangle object
Shape shape3 = new Triangle(); // Triangle object

shape1.draw(); // Dynamic method dispatch occurs


shape2.draw(); // Dynamic method dispatch occurs
shape3.draw(); // Dynamic method dispatch occurs
}
}

OUTPUT:-
Q14:- Write a program to implement abstract class in java.
Ans:-abstract class Shape {
abstract double area();
abstract double perimeter();
}
class Circle extends Shape {
private double radius;

Circle(double radius) {
this.radius = radius;
}
double area() {
return Math.PI * radius * radius;
}
double perimeter() {
return 2 * Math.PI * radius;
}
}
class Rectangle extends Shape {
private double length;
private double width;

Rectangle(double length, double width) {


this.length = length;
this.width = width;
}
double area() {
return length * width;
}
double perimeter() {
return 2 * (length + width);}}
public class AbstractClassExample {
public static void main(String[] args) {
Circle circle = new Circle(5);
Rectangle rectangle = new Rectangle(4, 6);

System.out.println("Circle:");
System.out.println("Area: " + circle.area());
System.out.println("Perimeter: " + circle.perimeter());

System.out.println("\nRectangle:");
System.out.println("Area: " + rectangle.area());
System.out.println("Perimeter: " + rectangle.perimeter());
}
}

OUTPUT:-
Q15:-Write a program to implement interfaces in java.
Ans:- interface ElectronicDevice {
void turnOn();
void turnOff();
}
interface Connectable {
void connectToInternet();{
class Smartphone implements ElectronicDevice, Connectable {
public void turnOn() {
System.out.println("Smartphone turned on");
}
public void turnOff() {
System.out.println("Smartphone turned off");
}
public void connectToInternet() {
System.out.println("Smartphone connected to the internet");
}
}
class Laptop implements ElectronicDevice, Connectable {
public void turnOn() {
System.out.println("Laptop turned on");
}
public void turnOff() {
System.out.println("Laptop turned off");
} public void connectToInternet() {
System.out.println("Laptop connected to the internet");
}
}class Smartwatch implements ElectronicDevice {
public void turnOn() {
System.out.println("Smartwatch turned on");
}
public void turnOff() {
System.out.println("Smartwatch turned off");
}
}
public class RealLifeExample {
public static void main(String[] args) {
Smartphone smartphone = new Smartphone();
Laptop laptop = new Laptop();
Smartwatch smartwatch = new Smartwatch();

smartphone.turnOn();
smartphone.connectToInternet();

laptop.turnOn();
laptop.connectToInternet();

smartwatch.turnOn();
}
}
OUTPUT:-
Q16:- Write a simple Multithread program in java.
Ans:-
class MyThread extends Thread {
// Override run method to define the task to be performed by the thread
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread: " + Thread.currentThread().getId() + " Count: " + i);
try {
// Adding a short delay for demonstration purposes
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

// Main class
public class MultiThreadExample {
public static void main(String[] args) {
// Creating and starting multiple threads
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();

// Starting threads
thread1.start();
thread2.start();
}
}

OUTPUT:-
Q17:-Write a program to handle try and multiple catch block.
Ans:-
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
// Attempting to perform division by zero
int result = 10 / 0;
System.out.println("Result: " + result); // This line will not be reached
} catch (ArithmeticException e) {
// Catching ArithmeticException which occurs when dividing by zero
System.out.println("ArithmeticException caught: " + e.getMessage());
} catch (Exception e) {
// Catching any other exception
System.out.println("Exception caught: " + e.getMessage());
} finally {
// The code inside the finally block always executes, regardless of whether an exception occurred or not
System.out.println("Finally block executed");
}

System.out.println("Program continues after exception handling");


}
}

OUTPUT:-
Q18:-Create a custom exception and throw in case of age<18 for voting.
Ans:-
class UnderageVotingException extends Exception {
public UnderageVotingException(String message) {
super(message);
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void vote() throws UnderageVotingException {
if (age < 18) {
throw new UnderageVotingException("Sorry, " + name + ". You are not eligible for voting as your age is
below 18.");
} else {
System.out.println(name + ", you are eligible for voting.");
}
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
// Creating a Person object
Person person1 = new Person("Sachin", 20);
Person person2 = new Person("Nikhil", 16);

try {
// Calling the vote method for person1
person1.vote();
// Calling the vote method for person2
person2.vote();
} catch (UnderageVotingException e) {
// Catching the custom exception and printing the error message
System.out.println("Error: " + e.getMessage());
}
}
}

OUTPUT:-
Q19:-Create a student table using <TABLE> tag in html.
Ans:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Table</title>
</head>
<body>
<h2>Student Table</h2>
<table border="1">
<tr>
<th>Student ID</th>
<th>Name</th>
<th>Age</th>
<th>Grade</th>
</tr>
<tr>
<td>060</td>
<td>Sachin</td>
<td>20</td>
<td>A</td>
</tr>
<tr>
<td>062</td>
<td>Sanjay</td>
<td>21</td>
<td>B+</td>
</tr>
<tr>
<td>059</td>
<td>Kunal</td>
<td>21</td>
<td>A-</td>
</tr>
<tr>
<td>061</td>
<td>Yash</td>
<td>21</td>
<td>C</td>
</tr>
</table>
</body>
</html>

OUTPUT:-
Q20:- Write a program to draw different shapes using graphics methods.
Ans:-//ELLIPSE
import java.awt.*;
import javax.swing.*;
public class ellipse extends JApplet {
public void init()
{
// set size
setSize(400, 400);
repaint();
}
public void paint(Graphics g)
{
// set Color for rectangle
g.setColor(Color.red);

// draw a ellipse
g.drawOval(100, 100, 150, 100);
}
}

OUTPUT:-
Q(B) DrawRect
import java.awt.*;
import javax.swing.*;

public class rectangle extends JApplet {

public void init()


{
// set size
setSize(400, 400);

repaint();
}

// paint the applet


public void paint(Graphics g)
{
// set Color for rectangle
g.setColor(Color.red);

// draw a rectangle
g.drawRect(100, 100, 200, 200);
}
}

OUTOUT:-
Q21:-Create a login form in AWT.
Ans:-
import java.awt.*;
import java.awt.event.*;

public class LoginForm extends Frame implements ActionListener {


Label usernameLabel, passwordLabel;
TextField usernameField, passwordField;
Button loginButton;
public LoginForm() {
setLayout(new FlowLayout());
usernameLabel = new Label("Username:");
add(usernameLabel);

usernameField = new TextField(20);


add(usernameField);

passwordLabel = new Label("Password:");


add(passwordLabel);

passwordField = new TextField(20);


passwordField.setEchoChar('*'); // Mask password
add(passwordField);

loginButton = new Button("Login");


add(loginButton);
loginButton.addActionListener(this);

setTitle("Login Form");
setSize(300, 150);
setVisible(true);

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose(); // Close the window
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();})}
String password = passwordField.getText();
if (username.equals("admin") && password.equals("password")) {
System.out.println("Login successful!");
} else {
System.out.println("Invalid username or password. Please try again.");}}

public static void main(String[] args) {


new LoginForm();
}
}
OUTPUT:-
Q22:- Create a calculator using event listener in java.
Ans:-
import java.awt.*;
import java.awt.event.*;

public class LoginForm extends Frame implements ActionListener {


// Components
Label usernameLabel, passwordLabel;
TextField usernameField, passwordField;
Button loginButton;

// Constructor
public LoginForm() {
// Set layout
setLayout(new FlowLayout());

// Initialize components
usernameLabel = new Label("Username:");
add(usernameLabel);

usernameField = new TextField(20);


add(usernameField);

passwordLabel = new Label("Password:");


add(passwordLabel);

passwordField = new TextField(20);


passwordField.setEchoChar('*'); // Mask password
add(passwordField);

loginButton = new Button("Login");


add(loginButton);

// Register ActionListener for loginButton


loginButton.addActionListener(this);

// Set frame properties


setTitle("Login Form");
setSize(300, 150);
setVisible(true);

// Add WindowListener to handle closing event


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose(); // Close the window
}
});
}

// ActionListener implementation
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = passwordField.getText();

// Validate username and password


if (username.equals("admin") && password.equals("password")) {
System.out.println("Login successful!");
} else {
System.out.println("Invalid username or password. Please try again.");
}
}

// Main method
public static void main(String[] args) {
new LoginForm();
}
}

OUTPUT:-

You might also like