0% found this document useful (0 votes)
57 views

Java Practical File ss1

The document provides 10 code examples demonstrating various Java concepts: 1) counting digits in a number, 2) calculating factorials recursively, 3) multiplying matrices, 4) printing Fibonacci series, 5) printing a diamond pattern, 6) using static variables, 7) using constructors, 8) creating and using custom packages, 9) simple inheritance between two classes, and 10) hierarchical inheritance with a base class.

Uploaded by

Rahul Kumar
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)
57 views

Java Practical File ss1

The document provides 10 code examples demonstrating various Java concepts: 1) counting digits in a number, 2) calculating factorials recursively, 3) multiplying matrices, 4) printing Fibonacci series, 5) printing a diamond pattern, 6) using static variables, 7) using constructors, 8) creating and using custom packages, 9) simple inheritance between two classes, and 10) hierarchical inheritance with a base class.

Uploaded by

Rahul Kumar
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/ 34

Page |1

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


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: ");

int number = scanner.nextInt();

int numberOfDigits = countDigits(number);

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

scanner.close();

public static int countDigits(int number)

{ number = Math.abs(number);

if (number == 0) { return 1;}

int count = 0;

while (number > 0)

{ count++;

number = number / 10;

return count;

OUTPUT:
Page |2

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


import java.util.Scanner;

public class Factorial {

public static int factorial(int n)

if (n == 0) {

return 1;

else {

return n * factorial(n - 1);

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a non-negative integer to find its factorial: ");

int num = scanner.nextInt();

scanner.close();

if (num < 0) {

System.out.println("Factorial is not defined for negative numbers.");

} else {

System.out.println("Factorial of " + num + " is " + factorial(num));

OUTPUT:
Page |3

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

public class MatrixMultiplicationExample{

public static void main(String args[]){

//creating two matrices

int a[][]={{1,1,1},{2,2,2},{3,3,3}};

int b[][]={{3,3,3},{2,2,2},{1,1,1}};

int c[][]=new int[3][3];

System.out.println("***** multiplication of 2 matrices ******");

for(int i=0;i<3;i++){

for(int j=0;j<3;j++){

c[i][j]=0;

for(int k=0;k<3;k++)

c[i][j]+=a[i][k]*b[k][j];

System.out.print(c[i][j]+" ");

System.out.println();

}}

OUTPUT:
Page |4

4 Write a program to print fibnonacci series in java.


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:");

printFibonacci(n);

public static void printFibonacci(int n)

int firstTerm = 0, secondTerm = 1;

System.out.print(firstTerm + " " + secondTerm + " ");

for (int i = 3; i <= n; i++) {

int nextTerm = firstTerm + secondTerm;

System.out.print(nextTerm + " ");

firstTerm = secondTerm;

secondTerm = nextTerm;

OUTPUT:
Page |5

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


import java.io.*;

public class Dimond_Pattern {

public static void main(String[] args){

int number = 7,m, n;

for (m = 1; m <= number; m++) {

for (n = 1; n <= number - m; n++) { System.out.print(" ");}

for (n = 1; n <= m * 2 - 1; n++) {System.out.print("*");}

System.out.println();

for (m = number - 1; m > 0; m--) {

for (n = 1; n <= number - m; n++) {

System.out.print(" ");

for (n = 1; n <= m * 2 - 1; n++) {

System.out.print("*");

System.out.println();

OUTPUT:
Page |6

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

public class StaticVariableExample {


// Static variable
static int staticVariable = 0;

public static void main(String[] args) {


System.out.println("Initial value of staticVariable: " + staticVariable);

staticVariable = 10;

System.out.println("Modified value of staticVariable: " + staticVariable);

StaticVariableExample obj1 = new StaticVariableExample();


StaticVariableExample obj2 = new StaticVariableExample();

System.out.println("Value of staticVariable through obj1: " + obj1.staticVariable);


System.out.println("Value of staticVariable through obj2: " + obj2.staticVariable);

obj1.staticVariable = 20;
System.out.println("Modified value of staticVariable through obj1: " + obj1.staticVariable);
System.out.println("Value of staticVariable through obj2 after modification: " +
obj2.staticVariable);
}
}

OUTPUT:
Page |7

7: Write a program to implement constructors in java.


public class ConstructorExample {
// Instance variables
String name;
int age;
// Default constructor
public ConstructorExample() {
System.out.println("Default constructor called");
name = "Sanjay Kumar";
age = 21;
}
// Parameterized constructor
public ConstructorExample(String name, int age) {
System.out.println("Parameterized constructor called");
this.name = name;
this.age = age;
}
// Method to display details
public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
// Creating objects using different constructors
ConstructorExample obj1 = new ConstructorExample();
ConstructorExample obj2 = new ConstructorExample("Kunal", 20);
// Displaying details of objects
System.out.println("Details of obj1:");
obj1.displayDetails();
System.out.println("\nDetails of obj2:");
obj2.displayDetails();
}
}

OUTPUT:
Page |8

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


//Creating a package mypack1 using package Keyword
package mypack1;
// Define a class named 'facto'
public class facto {

// Method to calculate factorial of an integer 'n'


public void factorial_of_Integer(int n) {
int i, fac = 1; // Initialize variables for iteration and factorial

// Loop through numbers from 1 to 'n' and calculate factorial


for (i = 1; i <= n; i++) {
fac = fac * i; // Update factorial by multiplying with each number
}

// Print the factorial of 'n'


System.out.println("factorial of " + n + " is : " + fac);
}
}

//Using mypack1 on our program by import keyword


import java.util.Scanner; // Import Scanner class for user input
import mypack1.facto; // Import facto class from mypack1 package

// Define a class named 'cal_facto'


public class cal_facto {

public static void main(String args[]) {


facto obj = new facto(); // Create an instance of facto class
System.out.println("Enter an integer for factorial : ");
Scanner scan = new Scanner(System.in); // Create Scanner object for user input
int n = scan.nextInt(); // Read integer input from user
//int n=Integer.parseInt(args[0]); // Alternative way to get integer input from CLA
obj.factorial_of_Integer(n); // Call factorial_of_Integer method of facto class to calculate
factorial
scan.close(); // Close Scanner object to prevent resource leak
}
}
OUTPUT:
Page |9

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


// Parent class
class Parent {
void displayParent() {
System.out.println("This is the parent class");
}
}

// Child class inheriting from Parent class


class Child extends Parent {
void displayChild() {
System.out.println("This is the child class");
}
}

// Main class
public class InheritanceExample {
public static void main(String[] args) {
// Create an object of child class
Child childObj = new Child();
// Call methods of both parent and child classes
childObj.displayParent(); // Method from parent class
childObj.displayChild(); // Method from child class
}
}

OUTPUT:
P a g e | 10

10: Write a program to implement Hierarchical inheritance in java.

// Base class
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
// Derived class 1
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
// Derived class 2
class Cat extends Animal {
void meow() {
System.out.println("Cat is meowing");
}
}
// Main class
public class HierarchicalInheritance {
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();

// Call methods of Dog class


dog.eat(); // Inherited from Animal class
dog.bark(); // Defined in Dog class

// Call methods of Cat class


cat.eat(); // Inherited from Animal class
cat.meow(); // Defined in Cat class
}
}

OUTPUT:
P a g e | 11

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


public class MethodOverloadingExample {

// Method to add two integers

static int add(int a, int b) {

return a + b;

// Method to add three integers

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

return a + b + c;

// Method to concatenate two strings

static String add(String s1, String s2) {

return s1 + s2;

public static void main(String[] args) {

// Calling overloaded methods

int sum1 = add(5, 10);

int sum2 = add(5, 10, 15);

String result = add("Hello, ", "World!");

System.out.println("Sum of 5 and 10 is: " + sum1);

System.out.println("Sum of 5, 10, and 15 is: " + sum2);

System.out.println("Concatenated string is: " + result);

}}

OUTPUT:
P a g e | 12

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


// Base class

class Animal

{ void makeSound() { System.out.println("Animal makes a sound"); }

// Derived class

class Dog extends Animal {

// Overriding the makeSound method of the Animal class

@Override

void makeSound() {

System.out.println("Dog barks");

}}

// Main class

public class MethodOverridingExample {

public static void main(String[] args) {

Animal animal = new Animal(); // Creating an object of Animal class

animal.makeSound(); // Calling method from Animal class

Dog dog = new Dog(); // Creating an object of Dog class

dog.makeSound(); // Calling overridden method from Dog class

OUTPUT:
P a g e | 13

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


// Base class
class Shape {

// Method to calculate area

void calculateArea() {

System.out.println("Area calculation for generic shape");

// Derived class representing a rectangle

class Rectangle extends Shape {

// Overriding the calculateArea method for rectangle

@Override

void calculateArea() {

System.out.println("Area of rectangle = length * width");

// Derived class representing a circle

class Circle extends Shape {

// Overriding the calculateArea method for circle

@Override

void calculateArea() {

System.out.println("Area of circle = π * radius * radius");

// Main class

public class DynamicMethodDispatchExample {

public static void main(String[] args) {

// Creating objects of different classes


P a g e | 14

Shape shape1 = new Shape();

Shape shape2 = new Rectangle();

Shape shape3 = new Circle();

// Calling calculateArea method

shape1.calculateArea(); // Calls calculateArea method of Shape class

shape2.calculateArea(); // Calls calculateArea method of Rectangle class (dynamic method


dispatch)

shape3.calculateArea(); // Calls calculateArea method of Circle class (dynamic method dispatch)

OUTPUT:
P a g e | 15

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

// Abstract class
abstract class Shape {
// Abstract method to calculate area
abstract double calculateArea();

// Concrete method
void display() {
System.out.println("This is a shape.");
}
}

// Derived class representing a rectangle


class Rectangle extends Shape {
double length;
double width;

// Constructor
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

// Implementation of abstract method to calculate area for rectangle


@Override
double calculateArea() {
return length * width;
}
}

// Derived class representing a circle


class Circle extends Shape {
double radius;

// Constructor
Circle(double radius) {
this.radius = radius;
}

// Implementation of abstract method to calculate area for circle


@Override
double calculateArea() {
return Math.PI * radius * radius;
P a g e | 16

}
}

// Main class
public class AbstractClassExample {
public static void main(String[] args) {
// Creating objects of different shapes
Shape rectangle = new Rectangle(5, 3);
Shape circle = new Circle(4);

// Displaying shapes and their areas


rectangle.display();
System.out.println("Area of rectangle: " + rectangle.calculateArea());

circle.display();
System.out.println("Area of circle: " + circle.calculateArea());
}
}

OUTPUT:
P a g e | 17

15: Write a program to implement interfaces in java.


-- // Interface defining methods for shapes

interface Shape {

double calculateArea(); // Method to calculate area

double calculatePerimeter(); // Method to calculate perimeter

// Class representing a rectangle implementing the Shape interface

class Rectangle implements Shape {

double length;

double width;

// Constructor

Rectangle(double length, double width) {

this.length = length;

this.width = width;

// Implementation of methods from the Shape interface

@Override

public double calculateArea() {

return length * width;

@Override

public double calculatePerimeter() {

return 2 * (length + width);


P a g e | 18

// Class representing a circle implementing the Shape interface

class Circle implements Shape {

double radius;

// Constructor

Circle(double radius) {

this.radius = radius;

// Implementation of methods from the Shape interface

@Override

public double calculateArea() {

return Math.PI * radius * radius;

@Override

public double calculatePerimeter() {

return 2 * Math.PI * radius;

// Main class

public class InterfaceExample {

public static void main(String[] args) {


P a g e | 19

// Creating objects of different shapes

Shape rectangle = new Rectangle(5, 3);

Shape circle = new Circle(4);

// Displaying shapes and their properties

System.out.println("Rectangle:");

System.out.println("Area: " + rectangle.calculateArea());

System.out.println("Perimeter: " + rectangle.calculatePerimeter());

System.out.println("\nCircle:");

System.out.println("Area: " + circle.calculateArea());

System.out.println("Perimeter: " + circle.calculatePerimeter());

OUTPUT:
P a g e | 20

16: Write a simple Multithread program in java.


// Define a class that implements the Runnable interface

class MyThread implements Runnable {

// Implement the run() method of the Runnable interface

public void run() {

// Print a message 5 times

for (int i = 0; i < 5; i++) {

System.out.println("Hello from MyThread: " + i);

try {

// Pause execution for a random amount of time (between 0 to 999 milliseconds)

Thread.sleep((long)(Math.random() * 1000));

} catch (InterruptedException e) {

e.printStackTrace();

// Main class

class MultithreadingExample {

public static void main(String[] args) {

// Create an instance of MyThread

MyThread myThread = new MyThread();

// Create a new thread and pass the MyThread instance to its constructor

Thread thread = new Thread(myThread);


P a g e | 21

// Start the thread

thread.start();

// Main thread continues execution

// Print a message 5 times

for (int i = 0; i < 5; i++) {

System.out.println("Hello from Main: " + i);

try {

// Pause execution for a random amount of time (between 0 to 999 milliseconds)

Thread.sleep((long)(Math.random() * 1000));

} catch (InterruptedException e) {

e.printStackTrace();

OUTPUT:
P a g e | 22

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


public class TryCatchExample {

public static void main(String[] args) {

try {

// Division by zero exception

int result = 10 / 0;

// ArrayIndexOutOfBoundsException

int[] arr = {1, 2, 3};

System.out.println(arr[5]);

// NullPointerException

String str = null;

System.out.println(str.length());

} catch (ArithmeticException e) {

System.out.println("ArithmeticException caught: Division by zero");

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("ArrayIndexOutOfBoundsException caught: Index out of range");

} catch (NullPointerException e) {

System.out.println("NullPointerException caught: Attempted to access null object");

} catch (Exception e) {

System.out.println("Exception caught: " + e.getMessage());

OUTPUT:
P a g e | 23

18: Create a custom exception and throw in case of age<18 for voting.
class UnderAgeException extends Exception

{ public UnderAgeException()

{ super("You are under 18 years old. You cannot vote."); }

public class VotingExample {

static void checkVotingEligibility(int age) throws UnderAgeException {

if (age < 18) {

// Throw the custom exception if age is less than 18

throw new UnderAgeException();

} else {

System.out.println("You are eligible to vote.");

public static void main(String[] args) {

int age = 16; // Example age

try {

checkVotingEligibility(age);

catch (UnderAgeException e)

{ System.out.println("Exception caught: " + e.getMessage());

}}

OUTPUT:
P a g e | 24

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


<!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>

<!-- Creating the table -->

<table>

<!-- Table header -->

<tr>

<th>ID</th>

<th>Name</th>

<th>Age</th>

<th>Grade</th>

</tr>

<tr>

<td>1</td>

<td>Sanjay</td>

<td>18</td>

<td>A</td>

</tr>

<tr>

<td>2</td>
P a g e | 25

<td>Kunal</td>

<td>17</td>

<td>B</td>

</tr>

<tr>

<td>3</td>

<td>Yash</td>

<td>19</td>

<td>A</td>

</tr>

</table>

</body>

</html>

OUTPUT:
P a g e | 26

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


import java.awt.*;

import javax.swing.*;

public class DrawShapes extends JPanel {

// Override the paintComponent method to draw shapes

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

// Set the color to red

g.setColor(Color.RED);

// Draw a rectangle

g.drawRect(50, 50, 100, 50);

// Set the color to blue

g.setColor(Color.BLUE);

// Draw a filled rectangle

g.fillRect(200, 50, 100, 50);

// Set the color to green

g.setColor(Color.GREEN);

// Draw an oval

g.drawOval(50, 150, 100, 50);

// Set the color to yellow

g.setColor(Color.YELLOW);

// Draw a filled oval

g.fillOval(200, 150, 100, 50);

// Set the color to black

g.setColor(Color.BLACK);
P a g e | 27

// Draw a line

g.drawLine(50, 250, 300, 250);

// Main method to create and display the GUI

public static void main(String[] args) {

JFrame frame = new JFrame("Draw Shapes");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400, 350);

frame.add(new DrawShapes());

frame.setVisible(true);

OUTPUT:
P a g e | 28

21. Create a login form in AWT.


import java.awt.*;

import java.awt.event.*;

public class LoginForm extends Frame implements ActionListener {

// Components of the login form

private Label lblUsername, lblPassword;

private TextField txtUsername, txtPassword;

private Button btnLogin, btnCancel;

// Constructor to initialize the login form

public LoginForm() {

// Set frame properties

setTitle("Login Form");

setSize(300, 150);

setLayout(new GridLayout(3, 2));

setResizable(false);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

});

// Initialize components

lblUsername = new Label("Username:");

lblPassword = new Label("Password:");

txtUsername = new TextField(20);

txtPassword = new TextField(20);

txtPassword.setEchoChar('*'); // Set password field to hide characters

btnLogin = new Button("Login");


P a g e | 29

btnCancel = new Button("Cancel");

// Add components to the frame

add(lblUsername);

add(txtUsername);

add(lblPassword);

add(txtPassword);

add(btnLogin);

add(btnCancel);

// Add action listeners to the buttons

btnLogin.addActionListener(this);

btnCancel.addActionListener(this);

// ActionListener implementation

public void actionPerformed(ActionEvent e) {

if (e.getSource() == btnLogin) {

String username = txtUsername.getText();

String password = txtPassword.getText();

// Perform login authentication (dummy check)

if (username.equals("admin") && password.equals("password")) {

System.out.println("Login successful!");

// Here you can perform actions after successful login

} else {

System.out.println("Invalid username or password. Please try again.");

}
P a g e | 30

} else if (e.getSource() == btnCancel) {

// Clear input fields

txtUsername.setText("");

txtPassword.setText("");

// Main method to create and display the login form

public static void main(String[] args) {

LoginForm loginForm = new LoginForm();

loginForm.setVisible(true);

OUTPUT:
P a g e | 31

22. Create a calculator using event listener in java.


import java.awt.*;

import java.awt.event.*;

public class Calculator extends Frame implements ActionListener {

// Components of the calculator

private TextField tfDisplay;

private Button[] buttons;

private String[] buttonLabels = {

"7", "8", "9", "+",

"4", "5", "6", "-",

"1", "2", "3", "*",

"0", "=", "C", "/"

};

// Constructor to initialize the calculator

public Calculator() {

// Set frame properties

setTitle("Calculator");

setSize(250, 250);

setLayout(new BorderLayout());

setResizable(false);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

});
P a g e | 32

// Initialize components

tfDisplay = new TextField();

tfDisplay.setEditable(false);

buttons = new Button[buttonLabels.length];

Panel buttonPanel = new Panel();

buttonPanel.setLayout(new GridLayout(4, 4));

// Create and add buttons to the button panel

for (int i = 0; i < buttonLabels.length; i++) {

buttons[i] = new Button(buttonLabels[i]);

buttons[i].addActionListener(this);

buttonPanel.add(buttons[i]);

// Add components to the frame

add(tfDisplay, BorderLayout.NORTH);

add(buttonPanel, BorderLayout.CENTER);

// ActionListener implementation

public void actionPerformed(ActionEvent e) {

String command = e.getActionCommand();

if ("0123456789".contains(command)) {

tfDisplay.setText(tfDisplay.getText() + command);

} else if ("+-*/".contains(command)) {
P a g e | 33

tfDisplay.setText(tfDisplay.getText() + " " + command + " ");

} else if (command.equals("=")) {

calculateResult();

} else if (command.equals("C")) {

tfDisplay.setText("");

// Method to calculate the result

private void calculateResult() {

String expression = tfDisplay.getText();

String[] tokens = expression.split("\\s+");

int result = Integer.parseInt(tokens[0]);

for (int i = 1; i < tokens.length; i += 2) {

String operator = tokens[i];

int operand = Integer.parseInt(tokens[i + 1]);

switch (operator) {

case "+":

result += operand;

break;

case "-":

result -= operand;

break;

case "*":

result *= operand;
P a g e | 34

break;

case "/":

result /= operand;

break;

tfDisplay.setText(Integer.toString(result));

// Main method to create and display the calculator

public static void main(String[] args) {

Calculator calculator = new Calculator();

calculator.setVisible(true);

OUTOUT:

You might also like