0% found this document useful (0 votes)
3 views30 pages

Java Employee and Shape Classes

The document describes the implementation of various Java classes, including Employee, Shape, Circle, Triangle, and Rectangle, demonstrating concepts such as encapsulation, inheritance, polymorphism, and abstraction. It provides class diagrams, constructors, methods, and main methods for demonstration, along with expected outputs for each program. The Employee class manages employee details and salary adjustments, while the Shape class hierarchy showcases polymorphism through drawing and erasing shapes, and the abstract Shape class is extended by Circle and Triangle classes to calculate area and perimeter.

Uploaded by

veeresh2006.cta
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)
3 views30 pages

Java Employee and Shape Classes

The document describes the implementation of various Java classes, including Employee, Shape, Circle, Triangle, and Rectangle, demonstrating concepts such as encapsulation, inheritance, polymorphism, and abstraction. It provides class diagrams, constructors, methods, and main methods for demonstration, along with expected outputs for each program. The Employee class manages employee details and salary adjustments, while the Shape class hierarchy showcases polymorphism through drawing and erasing shapes, and the abstract Shape class is extended by Circle and Triangle classes to calculate area and perimeter.

Uploaded by

veeresh2006.cta
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

3.

A class called Employee, which models an employee with an ID, name and salary, is
designed as shown in the following class diagram. The method raise-Salary (percent)
increases the salary by the given percentage. Develop the Employee class and suitable
main method for demonstration.
(Class Name: employee)
package project1;
Line 1: This declares that the class employee is part of the project1 package. Java uses packages
to group related classes.

public class employee


Line 3: This defines the employee class, which will contain the fields, constructor, and methods
related to an employee. Note that Java conventions recommend class names start with a capital
letter, so it is typically named Employee

{
private int id;
private String name;
private double salary;
Lines 4-6: These are instance variables (also called fields) of the employee class. They are
marked as private, meaning they can only be accessed within this class.

 id: A unique integer identifier for the employee.


 name: The employee's name (String).
 salary: The employee's salary (double).

public employee(int id, String name, double salary)


Line 8: This is a constructor that is called when a new employee object is created. It takes three
parameters: id, name, and salary, and uses them to initialize the object's fields.

{
[Link] = id;
[Link] = name;
[Link] = salary;
}
Lines 9-11: These lines inside the constructor initialize the instance variables (id, name, and
salary) using the this keyword, which refers to the current object. It differentiates between the
local parameters (id, name, salary) and the instance variables ([Link], [Link],
[Link]).

public void raiseSalary(double percent)


Line 13: This is a method to raise the employee's salary. It takes one argument, percent, which
specifies the percentage increase in salary.

{
if (percent > 0)
Line 14: This checks if the input percentage (percent) is greater than 0. If it is positive, the salary
raise is applied.
{
1
double raiseAmount = salary * (percent / 100);
salary += raiseAmount;

Lines 15-16: Inside the if block:

 raiseAmount: Calculates the amount to increase the salary by multiplying the current
salary by the percentage (divided by 100 to convert it to a decimal).
 salary += raiseAmount;: Updates the employee's salary by adding the
raiseAmount to it.

[Link](name + "'s salary raised by " + percent + "%. New salary: $"
+ salary);
Line 17: If the salary was successfully raised, this line prints the employee’s name, the percentage
increase, and the updated salary.
}
else (Line 18: If the percentage is less than or equal to 0, the else block is executed.)

{
[Link]("Invalid percentage. Salary remains unchanged.");
Line 19: If an invalid percentage (e.g., negative or zero) is provided, this line prints an error message
indicating that the salary will not change.
}
}

public String toString()


Line 22: This is the toString method, which returns a string representation of the employee
object. It overrides the default toString method provided by the Object class.
{
return "Employee ID: " + id + ", Name: " + name + ", Salary: $" + salary;
Line 23: This builds and returns a string that contains the employee's id, name, and salary
formatted in a human-readable form.
}
public static void main(String[] args)
Line 25: This is the main method, which serves as the entry point for the program. The Java Virtual
Machine (JVM) calls this method to start execution.
{
// Creating an Employee object
employee employee = new employee(1, "Manju", 50000.0);
Line 27: A new employee object is created using the constructor. The object represents an
employee with an ID of 1, a name of "Manju", and an initial salary of 50000.0.

// Displaying employee details


[Link]("Initial Employee Details:");
[Link](employee);
Lines 29-30: These lines print the initial details of the employee object. Since the toString()
method is overridden in the employee class, calling [Link](employee) will print
the string returned by toString() (i.e., the employee's ID, name, and salary).
// Raising salary by 10%

2
[Link](10);
Line 32: This calls the raiseSalary method, passing in 10 as the percentage. It will raise the
employee's salary by 10%.
// Displaying updated employee details
[Link]("\nEmployee Details after Salary Raise:");
[Link](employee);
Lines 34-35: These lines print the updated employee details after the salary raise, again using the
toString() method to display the employee's new salary.
}
}

----------------------------------------------------------------------------------------------------------------
OUTPUT
Initial Employee Details:
Employee ID: 1, Name: Manju, Salary: $50000.0
Manju's salary raised by 10.0%. New salary: $55000.0

Employee Details after Salary Raise:


Employee ID: 1,
Name: Manju,
Salary: $55000.0

This output shows the initial state of the employee, the salary after a 10% raise, and the
updated employee details.

---------------------------------------------------*****-------------------------------------------------------

3
5. Develop a JAVA program to create a class named shape. Create three sub
classes namely: circle, triangle and square, each class has two member
functions named draw () and erase (). Demonstrate polymorphism concepts
by developing suitable methods, defining member data and main program.
(Inheritance & Polymorphism – Shape Class)

(Class Name: shapeDemo)

package project1;
Declares that this code belongs to the project1 package.

class shape
{
protected String name;

Declares a class named shape. It has a protected member variable name of type
String that holds the shape's name, accessible within the class and its subclasses.

public shape(String name)


{
[Link] = name;
}
Constructor of the shape class. It initializes the name variable with the value provided as a
parameter.

public void draw()


{
[Link]("Drawing a " + name);
}
Method draw in the shape class that prints a generic message saying it is drawing a shape.
This can be overridden by subclasses to provide specific behavior.

public void erase()


{
[Link]("Erasing a " + name);
}
}
Method erase in the shape class that prints a generic message saying it is erasing a shape.
Like draw, this can be overridden in subclasses.

class Circle extends shape


{
private double radius;
Declares a Circle class that inherits from shape. It has an additional property radius of type
double to represent the circle's radius.

4
public Circle(String name, double radius)
{
super(name);
[Link] = radius;
}
Constructor of the Circle class that calls the superclass constructor to initialize name and
initializes the radius of the circle.

//@Override
public void draw()
{
[Link]("Drawing a circle with radius " + radius);
}
Overridden draw method specific to Circle. It displays a message with the radius.

//@Override
public void erase()
{
[Link]("Erasing a circle with radius " + radius);
}
}
Overridden erase method specific to Circle. It displays a message with the radius.

class Triangle extends shape


{
private double base;
private double height;
Declares a Triangle class that also extends shape. It includes base and height properties.

public Triangle(String name, double base, double height)


{
super(name);
[Link] = base;
[Link] = height;
}
Constructor for Triangle that calls the superclass constructor for name and initializes base
and height.

//@Override
public void draw()
{
[Link]("Drawing a triangle with base " + base + " and height " +
height);
}
Overridden draw method specific to Triangle, displaying a message with base and height.

5
// @Override
public void erase()
{
[Link]("Erasing a triangle with base " + base + " and height " +
height);
}
}
Overridden erase method specific to Triangle, displaying a message with base and height.

Square Class
class Square extends shape
{
private double side;
Declares a Square class that extends shape. It includes a side property.

public Square(String name, double side)


{
super(name);
[Link] = side;
}
Constructor for Square that calls the superclass constructor for name and initializes the side.

//@Override
public void draw()
{
[Link]("Drawing a square with side length " + side);
}
Overridden draw method specific to Square, displaying a message with side.

//@Override
public void erase()
{
[Link]("Erasing a square with side length " + side);
}
}
Overridden erase method specific to Square, displaying a message with side.

shapeDemo Class and Main Method


public class shapeDemo
{
public static void main(String[] args)
{
shape[] shapes = new shape[3];
Declares a shapeDemo class with a main method that initializes an array named
shapes to hold shape objects.
6
shapes[0] = new Circle("Circle", 5.0);
shapes[1] = new Triangle("Triangle", 4.0, 6.0);
shapes[2] = new Square("Square", 3.0);
Initializes the array with instances of Circle, Triangle, and Square, each with specific
parameters for their respective properties.
for (shape shape : shapes)
{
[Link]();
[Link]();
[Link]();
}
}
}

Loops through each shape in the shapes array, calling draw and erase on each shape. Since
draw and erase are overridden in subclasses, they display specific messages depending on
the shape type. After each shape, it prints a blank line for clarity.

This program demonstrates polymorphism: each shape type (Circle, Triangle, Square) has a
unique implementation of the draw and erase methods, yet they can all be handled uniformly
as shape objects in the array.

OUTPUT
Drawing a circle with radius 5.0
Erasing a circle with radius 5.0

Drawing a triangle with base 4.0 and height 6.0


Erasing a triangle with base 4.0 and height 6.0

Drawing a square with side length 3.0


Erasing a square with side length 3.0

Explanation of the Output

1. Each shape's specific draw and erase methods are called, displaying messages that
include the unique attributes of each shape (such as radius for Circle, base and
height for Triangle, and side length for Square).
2. The blank lines in between are printed after each shape to separate their outputs for
readability.

7
6. Develop a JAVA program to create an abstract class Shape with abstract
methods calculateArea() and calculatePerimeter(). Create subclasses Circle and
Triangle that extend the Shape class and implement the respective methods to
calculate the area and perimeter of each shape. (Abstract Class)
((Go to file select project2)- Class Name: ShapeDemo)

package project2;
Declares that this code belongs to the project2 package.
Abstract Shape Class
abstract class Shape
{
abstract double calculateArea();
abstract double calculatePerimeter();
}
 Declares an abstract class Shape that serves as a blueprint for various shapes.
 Contains two abstract methods calculateArea() and calculatePerimeter(), which must
be implemented by any subclass of Shape.

Circle Class
class Circle extends Shape
{
private double radius;
Declares a Circle class that extends Shape. It has a private member variable radius of type
double to represent the circle's radius.
public Circle(double radius)
{
[Link] = radius;
}
Constructor for Circle, which takes the radius as a parameter and assigns it to the radius field.
// @Override
double calculateArea()
{
return [Link] * radius * radius;
}
Implementation of the calculateArea method for Circle, which calculates and returns the
area using the formula π×radiusx2.

8
//@Override
double calculatePerimeter()
{
return 2 * [Link] * radius;
}
}
Implementation of the calculatePerimeter method for Circle, which calculates and returns
the perimeter (or circumference) using the formula 2×π×radius

Triangle Class
class Triangle extends Shape
{
private double side1;
private double side2;
private double side3;
Declares a Triangle class that also extends Shape. It has three private member variables side1,
side2, and side3 of type double representing the three sides of the triangle.

public Triangle(double side1, double side2, double side3)


{
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
Constructor for Triangle, which takes the three sides as parameters and assigns them to
the respective fields.

// @Override
double calculateArea()
{
// Using Heron's formula to calculate the area of a triangle
double s = (side1 + side2 + side3) / 2;
return [Link](s * (s - side1) * (s - side2) * (s - side3));
}

9
//@Override
double calculatePerimeter()
{
return side1 + side2 + side3;
}
}
Implementation of calculatePerimeter for Triangle, which returns the perimeter by adding
the three sides.

ShapeDemo Class and Main Method


public class ShapeDemo
{
public static void main(String[] args)
{
// Creating Circle and Triangle objects
Circle circle = new Circle(5.0);
Triangle triangle = new Triangle(3.0, 4.0, 5.0);
Declares the ShapeDemo class with a main method that creates a Circle object with a radius
of 5.0 and a Triangle object with sides 3.0, 4.0, and 5.0.

// Calculating and displaying area and perimeter


[Link]("Circle Area: " + [Link]());
[Link]("Circle Perimeter: " + [Link]());
Calls calculateArea() and calculatePerimeter() on the circle object and prints the
results, showing the area and perimeter of the circle.

[Link]("\n Triangle Area: " + [Link]());


[Link]("Triangle Perimeter: " + [Link]());
}
}
Calls calculateArea() and calculatePerimeter() on the triangle object and prints the
results, showing the area and perimeter of the triangle.

OUTPUT
Circle Area: 78.53981633974483
Circle Perimeter: 31.41592653589793
Triangle Area: 6.0
Triangle Perimeter: 12.0

10
7. Develop a JAVA program to create an interface Resizable with methods
resizeWidth(int width) and resizeHeight(int height) that allow an object to be
resized. Create a class Rectangle that implements the Resizable interface and
implements the resize methods. (Resizable interface)

(Class Name: ResizeDemo)

package project2;
This statement declares that the classes and interfaces are part of the project2 package.
//Resizable interface
interface Resizable
{
void resizeWidth(int width);
void resizeHeight(int height);
}
The Resizable interface declares two methods, resizeWidth(int width) and
resizeHeight(int height). Classes implementing this interface must provide implementations

for these methods to allow resizing of an object’s width and height.


//Rectangle class implementing Resizable interface
class Rectangle implements Resizable
{
private int width;
private int height;
The Rectangle class implements the Resizable interface. It has two private member variables,
width and height, which store the dimensions of the rectangle.

public Rectangle(int width, int height)


{
[Link] = width;
[Link] = height;
}
This is a constructor for the Rectangle class. It initializes the width and height attributes using
values passed as arguments when creating a Rectangle object.
// Implementation of Resizable interface
// @Override
public void resizeWidth(int width)
{
[Link] = width;
[Link]("Resized width to: " + width);
11
}
The resizeWidth method changes the rectangle's width attribute to the new value provided. It
also prints the updated width to the console.
//@Override
public void resizeHeight(int height)
{
[Link] = height;
[Link]("Resized height to: " + height);
}
The resizeHeight method changes the rectangle's height attribute to the new value provided
and prints the updated height.
// Additional methods for Rectangle class
public int getWidth()
{
return width;
}
The getWidth method returns the current value of width.
public int getHeight()
{
return height;
}
The getHeight method returns the current value of height.
public void displayInfo()
{
[Link]("Rectangle: Width = " + width + ", Height = " + height);
}
}
The displayInfo method displays the rectangle's current width and height in a formatted output
to the console.
//Main class to test the implementation
public class ResizeDemo
{
public static void main(String[] args)
{
// Creating a Rectangle object
Rectangle rectangle = new Rectangle(10, 5);

12
The main method in ResizeDemo creates a new Rectangle object with an initial width of 10 and
height of 5.
// Displaying the original information
[Link]("Original Rectangle Info:");
[Link]();
This section displays the initial dimensions of the rectangle by calling displayInfo().
// Resizing the rectangle
[Link](15);
[Link](8);
The resizeWidth method is called with 15 as an argument, changing the width to 15. Then
resizeHeight is called with 8 as an argument, changing the height to 8. Both methods display

messages confirming the new dimensions.


// Displaying the updated information
[Link]("\n Updated Rectangle Info:");
[Link]();
}
}
Finally, the updated dimensions are displayed by calling displayInfo() again. The output reflects
the resized values for width and height.

Original Rectangle Info:


Rectangle: Width = 10, Height = 5
Resized width to: 15
Resized height to: 8

Updated Rectangle Info:


Rectangle: Width = 15, Height = 8

Explanation of Output:

1. Original Rectangle Info:


o The initial width is 10 and the height is 5, which is displayed by the
displayInfo() method.
2. Resizing Messages:
o After calling resizeWidth(15), the width changes to 15, and the program
prints "Resized width to: 15".
o After calling resizeHeight(8), the height changes to 8, and the program
prints "Resized height to: 8".
3. Updated Rectangle Info:
o Finally, displayInfo() is called again to show the updated dimensions, now
showing width as 15 and height as 8.
13
8. Develop a JAVA program to create an outer class with a function display.
Create another class inside the outer class named inner with a function called
display and call the two functions in the main class. (Outer Class)
(Java class Name: OuterInnerDemo)
This program demonstrates the use of a nested class in Java, where an Inner class is defined inside
an Outer class. Here's a detailed, line-by-line explanation of the code:
Package Declaration
package project2;

Declares the program belongs to the project2 package.

Outer Class Definition


class Outer
{
void display()
{
[Link]("Outer class display method");
}
The Outer class contains:

 A non-static method named display() that prints the message "Outer class
display method" to the console.
 A nested (inner) class named Inner.

class Inner
{
void display()
{
[Link]("Inner class display method");
}
}
}
Inner Class:

 Declared inside the Outer class.


 Contains its own display() method, which prints "Inner class display method" to
the console.

Both the Outer and Inner classes have methods named display(), demonstrating
method overriding in context based on which class the method is invoked from.

Main Class Definition


public class OuterInnerDemo
{
public static void main(String[] args)
{
14
The OuterInnerDemo class contains the main method, the program's entry point.

// Create an instance of the Outer class


Creating an Instance of the Outer Class
Outer outer = new Outer();
An object of the Outer class is created using the new keyword.

// Call the display method of the Outer class


Calling the display Method of the Outer Class
[Link]();

Calls the display method of the Outer class, which prints


Outer class display method

// Create an instance of the Inner class (nested inside Outer)


Creating an Instance of the Inner Class
[Link] inner = [Link] Inner();
Step-by-step breakdown:

1. The Inner class is a non-static inner class. To instantiate it, you first need an object
of the enclosing Outer class.
2. [Link] Inner() creates an instance of the Inner class, tied to the outer
object of the Outer class.
3. The reference [Link] inner declares the type of the inner object.

// Call the display method of the Inner class


Calling the display Method of the Inner Class
[Link]();

Calls the display method of the Inner class, which prints


Inner class display method
}
}
OUTPUT
Outer class display method
Inner class display method
----------------------------------------------------*****----------------------------------------------------

Key Concepts Demonstrated

1. Nested Classes:
o The Inner class is a non-static nested class (inner class) that belongs to the
Outer class.
2. Accessing Nested Classes:
o A nested (non-static) class instance is tied to an instance of its enclosing class.
o You access it using [Link] Inner().
3. Method Context:
o The display() methods in Outer and Inner demonstrate method isolation,
where the invoked method depends on the class of the instance.
15
9. Develop a JAVA program to raise a custom exception (user defined exception)
for DivisionByZero using try, catch, throw and finally. (Custom Exception)
(Java Class Name: CustomExceptionDemo)

This program demonstrates the creation and use of a custom exception in Java, including
how to throw, catch, and handle exceptions. Here’s a detailed, line-by-line explanation of
the code:

Package Declaration
package project2;
Declares that the code belongs to the project2 package.

Custom Exception Class Definition


//Custom exception class
class DivisionByZeroException extends Exception
{
public DivisionByZeroException(String message)
{
super(message);
}
}
Custom Exception Class:

 DivisionByZeroException is a custom exception class that extends the built-in


Exception class.
 Constructor:
o Accepts a String message and passes it to the constructor of the superclass
(Exception) using super(message).
o This message will be available when the exception is caught, via the
getMessage() method.

CustomExceptionDemo Class Definition


public class CustomExceptionDemo
{
This is the main class containing the program logic and the main method.
// Method to perform division and throw custom exception if denominator is
zero
Division Method
static double divide(int numerator, int denominator) throws
This method performs division of two integers, numerator and denominator.
throws DivisionByZeroException:

Indicates that this method can throw a DivisionByZeroException.


DivisionByZeroException
{
if (denominator == 0)
16
{
throw new DivisionByZeroException("Cannot divide by zero!");
}
Checks if the denominator is zero. If it is:

 A new DivisionByZeroException is created and thrown using the throw keyword.


 The exception's message is "Cannot divide by zero!"

return (double) numerator / denominator;


}
If no exception is thrown, the method returns the result of the division as a double.

public static void main(String[] args)


{
int numerator = 10;
int denominator = 0;
Initializes two integers: numerator as 10 and denominator as 0.
Try Block
try
{
double result = divide(numerator, denominator);
[Link]("Result of division: " + result);
}
Purpose:

 Calls the divide() method.


 If an exception occurs, it will jump to the catch block.

Flow:

 The divide(numerator, denominator) method is called with denominator = 0.


 Since denominator == 0, a DivisionByZeroException is thrown inside the
method. This transfers control to the catch block.

catch (DivisionByZeroException e)
{

[Link]("Exception caught: " + [Link]());


}
Purpose:

 Catches the DivisionByZeroException thrown by the divide() method.


 Prints the exception’s message (retrieved via [Link]()), which is "Cannot
divide by zero!"

Finally Block
finally
{
[Link]("Finally block executed");
17
}
}
}
Purpose:

 The finally block is always executed, regardless of whether an exception was


thrown or not.
 Prints the message "Finally block executed".

Output of the Program

When you run the program, the following output is produced:

Exception caught: Cannot divide by zero!


Finally block executed

 Custom Exceptions:

 DivisionByZeroException is a user-defined exception extending Exception.

 Throwing Exceptions:

 throw is used to explicitly throw a custom exception when a condition is met.

 Handling Exceptions with Try-Catch-Finally:

 Try Block: Contains the code that might throw an exception.


 Catch Block: Handles the exception if it occurs.
 Finally Block: Contains code that runs irrespective of whether an exception was
thrown or not.

 Exception Propagation:

 The divide() method declares throws DivisionByZeroException, passing


responsibility for handling the exception to the caller (main()).

18
10. Develop a JAVA program to create a package named mypack and import
& implement it in a suitable class. (Packages)

(Create a Package: mypack)


(Java Class Name: MyPackageClass)

-------------------------------------------------------------------------------------------------------------
This Java code defines a class named MyPackageClass within the mypack package. The
class contains a method to display a message and a static utility method for adding two
numbers.
Here's a detailed, line-by-line explanation:
Package Declaration
package mypack;

 Declares that this class belongs to the mypack package.


 Packages in Java are used to organize classes and interfaces into namespaces, making the
code more manageable and avoiding name conflicts.

Class Declaration
public class MyPackageClass
{
Declares a public class named MyPackageClass.

 public: Makes the class accessible from any other class, even outside the package.

displayMessage() Method
public void displayMessage()
{
[Link]("Hello from MyPackageClass in mypack package!");
}
purpose:

 Defines a non-static method named displayMessage() that prints a message to the


console when called.

Details:

 public: The method is accessible from other classes, even outside the package
(provided the class is imported).
 void: The method does not return any value.
 [Link]: Outputs the string "Hello from MyPackageClass in
mypack package!" to the console.

// New utility method


addNumbers() Method
public static int addNumbers(int a, int b)
{
return a + b;
}
19
}
Purpose:

 Defines a static utility method named addNumbers() that takes two integers, a and b,
as input and returns their sum.

Details:

 public: The method is accessible from any class, provided the mypack package is
imported.
 static: The method can be called directly on the class without needing an instance
of MyPackageClass.
 int: The return type of the method, indicating that it returns an integer.
 return a + b;: Calculates the sum of a and b and returns the result.

Key Concepts Demonstrated

1. Package Declaration:
o The mypack package groups this class logically for easier organization and
namespace management.
2. Public Access Modifier:
o Both the class and its methods are declared as public, meaning they can be
accessed from other packages if the mypack package is imported.
3. Static Method:
o The addNumbers() method is static, allowing it to be called directly using the
class name (e.g., [Link](5, 3)).
4. Non-Static Method:
o The displayMessage() method is non-static, meaning you need an object of
MyPackageClass to call it.

---------------------------------------------END------------------------------------------------------------
PackageDemo class using mypack Package
Create a Package: mypack
Java Class Name: PackageDemo
---------------------------------------------------------------------------------------------------------------
This program demonstrates how to use a class from a different package (mypack) by
importing it into the current program. It creates an instance of the MyPackageClass,
calls its methods, and utilizes both static and non-static methods. Here's a detailed, line-by-
line explanation:
Package Declaration
package mypack;
This comment indicates that the MyPackageClass is defined in the mypack package.
//Main program outside the mypack folder
Import Statement
import [Link];
Purpose:
This imports the MyPackageClass from the mypack package so it can be used in the current
program.
20
Details:

 Without this import statement, the program cannot directly reference


MyPackageClass unless its fully qualified name ([Link]) is used.

Class Declaration
public class PackageDemo
{
 Declares the main class PackageDemo, which contains the main method and serves as
the program's entry point.
 public: Makes the class accessible from anywhere.
Main Method
public static void main(String[] args)
{

 This is the program's entry point where execution begins.

// Creating an instance of MyPackageClass from the mypack package


Creating an Instance of MyPackageClass
MyPackageClass myPackageObject = new MyPackageClass();
Purpose:

 Creates an object of the MyPackageClass, allowing access to its non-static methods.

Details:

 MyPackageClass: Refers to the class being instantiated.


 myPackageObject: The reference variable that holds the instance of
MyPackageClass.
 new MyPackageClass(): Allocates memory and initializes a new object of
MyPackageClass.

Calling the displayMessage Method

// Calling the displayMessage method from MyPackageClass


[Link]();
Purpose:

 Calls the displayMessage() method on the myPackageObject instance.

Details:

 This method prints the message: "Hello from MyPackageClass in mypack


package!" to the console.

21
// Using the utility method addNumbers from MyPackageClass
Using the Static addNumbers Method
int result = [Link](5, 3);
Purpose:

 Calls the static addNumbers() method of MyPackageClass to calculate the sum of


two integers: 5 and 3.

Details:

 Static Method Call:


o Since addNumbers() is static, it can be called directly on the class
MyPackageClass without creating an instance.
 Result:
o The method returns 5 + 3 = 8, which is stored in the result variable.

Printing the Result


[Link]("Result of adding numbers: " + result);
}
}
Purpose:

 Prints the result of the addition to the console.

Details:

 The output is: "Result of adding numbers: 8".

OUTPUT
 Hello from MyPackageClass in mypack package!
 Result of adding numbers: 8

Key Concepts Demonstrated

1. Package Import:
o The import [Link]; statement imports a class from a
different package, enabling its use in this program.
2. Object Creation:
o An object of MyPackageClass is created to access non-static methods like
displayMessage().
3. Static Method Usage:
o Static methods like addNumbers() can be directly invoked using the class
name (MyPackageClass).
4. Encapsulation Across Packages:
o The program demonstrates the modularity and reusability provided by
organizing classes in different packages.

22
11. Write a program to illustrate creation of threads using runnable class.
(start method start each of the newly created thread. Inside the run method
there is sleep() for suspend the thread for 500 milliseconds). (Runnable
Interface)
Create a Package: project11
Java Class Name: RunnableThreadExample
----------------------------------------------------------------------------------------------------------------
package project11;
Declares that the code belongs to the project11 package.
MyRunnable Class

class MyRunnable implements Runnable


{
Declares a class MyRunnable that implements the Runnable interface, enabling the creation of
threads with custom behavior.
private volatile boolean running = true;
 volatile: Ensures changes to the running variable are visible to all threads.
 Purpose:

 Controls whether the thread should continue running or stop.

//@Override
//@SuppressWarnings("deprecation")
public void run()
{
while (running)
{
try
{ // Suppress deprecation warning for [Link]()
[Link](500);
[Link]("Thread ID: " + [Link]().getId() + " is
running.");
}
catch (InterruptedException e)
{
[Link]("Thread interrupted.");
}
}
}
23
 run() Method:
o Contains the logic executed by the thread when it starts.
 Details:
o while (running): Loops continuously as long as running is true.
o [Link](500): Pauses the thread for 500 milliseconds (half
a second).
o [Link]: Prints the current thread's ID and indicates
that it's running.
o catch (InterruptedException): Handles interruptions during
sleep.

public void stopThread()


{
running = false;
}
Purpose: Stops the thread gracefully by setting the running variable to false.
}
Main Class: RunnableThreadExample
public class RunnableThreadExample
{
Declares the main class containing the main() method.
public static void main(String[] args)
{
Entry Point:

 The program starts execution from this method.

// Create five instances of MyRunnable

Creating MyRunnable Instances

MyRunnable myRunnable1 = new MyRunnable();


MyRunnable myRunnable2 = new MyRunnable();
MyRunnable myRunnable3 = new MyRunnable();
MyRunnable myRunnable4 = new MyRunnable();
MyRunnable myRunnable5 = new MyRunnable();
Purpose:

 Creates five instances of the MyRunnable class.


 Each instance will run independently in its own thread.

24
Creating Threads
// Create five threads and associate them with MyRunnable instances
Thread thread1 = new Thread(myRunnable1);
Thread thread2 = new Thread(myRunnable2);
Thread thread3 = new Thread(myRunnable3);
Thread thread4 = new Thread(myRunnable4);
Thread thread5 = new Thread(myRunnable5);
Purpose:

 Associates each MyRunnable instance with a Thread object.

// Start the threads


[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
Purpose:

 Starts each thread, which invokes the run() method of the associated MyRunnable
object.

// Sleep for a while to allow the threads to run


Main Thread Sleep
try
{
[Link](500);
}
catch (InterruptedException e)
{
[Link]();
}
Purpose:

 Pauses the main thread for 500 milliseconds to allow other threads to execute and
print their messages.

Details:

 [Link](500): Halts the main thread for 500 ms.


 catch: Handles interruptions during sleep.

// Stop the threads gracefully


25
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Purpose:

 Stops all five threads by calling the stopThread() method on each MyRunnable
instance.
 Sets the running variable to false, causing the threads to exit the while loop and
terminate gracefully.

Key Concepts Demonstrated

1. Runnable Interface:
o The MyRunnable class implements the Runnable interface, defining the
thread's behavior in the run() method.
2. Thread Creation:
o Threads are created by associating MyRunnable objects with Thread instances.
3. Concurrency:
o Multiple threads run concurrently, executing the run() method.
4. Graceful Termination:
o Threads are stopped gracefully by setting the running variable to false.
5. Volatile Keyword:
o Ensures that changes to running are immediately visible to all threads,
preventing inconsistent behavior.

--------------------------------------------*****------------------------------------------------------------
OUTPUT
Thread ID: 10 is running.
Thread ID: 11 is running.
Thread ID: 13 is running.
Thread ID: 14 is running.
Thread ID: 12 is running.
Thread ID: 10 is running.
Thread ID: 11 is running.

26
12. Develop a program to create a class MyThread in this class a
constructor, call the base class constructor, using super and start the
thread. The run method of the class starts after this. It can be observed that
both main thread and created child thread are executed concurrently.

Create a Package: project11


(Java Class Name: ThreadConcurrentExample)

This program demonstrates multithreading in Java by extending the Thread class. It creates a
child thread and runs it concurrently with the main thread. Here's a line-by-line explanation
of the code:
package project11;
Declares that the code belongs to the project11 package.
class MyThread extends Thread
{

 Purpose:
o Defines a custom thread class by extending the Thread class.
 Inheritance:
o The Thread class provides built-in methods and functionality for managing
threads.

// Constructor calling base class constructor using super


public MyThread(String name)
{
super(name);
start(); // Start the thread in the constructor
}
Purpose:

 Initializes the thread with a name and starts it immediately.

Details:

 super(name): Calls the constructor of the parent Thread class to set the thread's
name.
 start(): Starts the thread, which internally calls the run() method. Starting the
thread within the constructor ensures it begins execution as soon as the object is
created.

// The run method that will be executed when the thread starts
// @Override run() Method

public void run()


{

27
for (int i = 1; i <= 5; i++)
{
[Link]([Link]().getName() + " Count: " + i);
try
{
[Link](500); // Sleep for 500 milliseconds
}
catch (InterruptedException e)
{
[Link]([Link]().getName() + " Thread
interrupted.");
}
}
}
}
Purpose:

 Defines the task the thread will perform when it runs.

Details:

 for Loop: Iterates from 1 to 5, printing the thread's name and the current count.
 [Link]().getName(): Retrieves the name of the currently
executing thread.
 [Link](500): Pauses the thread for 500 milliseconds between iterations.
 Exception Handling:
o InterruptedException: Handles cases where the thread is interrupted
during sleep

Main Class: Thread Concurrent Example


public class ThreadConcurrentExample
{
Defines the main class that contains the main() method.
Main Method
public static void main(String[] args)
{
Entry Point:

 The program starts execution from this method.

// Create an instance of MyThread


Creating the MyThread Instance
28
MyThread myThread = new MyThread("Child Thread");
Purpose:

 Creates an instance of the MyThread class, which starts the child thread as the
start() method is called in the constructor.

Thread Name:

 The child thread is named "Child Thread".

// Main thread
for (int i = 1; i <= 5; i++)
{
[Link]([Link]().getName() + " Thread Count: " +
i);
try
{
[Link](500); // Sleep for 500 milliseconds
}
catch (InterruptedException e)
{
[Link]([Link]().getName() + " Thread
interrupted.");
}
}
}
}

Purpose:

o The main thread executes a loop similar to the child thread, printing its name
(main) and a count from 1 to 5.

Details:

o [Link]().getName(): Retrieves the name of the current


thread (the main thread).
o [Link](500): Pauses the main thread for 500 milliseconds between
iterations.

29
Key Concepts Demonstrated

1. Extending Thread:
o The MyThread class extends the Thread class, allowing it to define its own
run() method.
2. Thread Start in Constructor:
o The thread is started immediately upon object creation by calling start() in
the constructor.
3. Concurrent Execution:
o Both the main thread and the child thread execute concurrently, demonstrating
Java's multithreading capabilities.
4. Sleep and Exception Handling:
o Both threads use [Link](500) to pause briefly, ensuring their outputs
interleave.

OUTPUT
Child Thread Count: 1
main Thread Count: 1
Child Thread Count: 2
main Thread Count: 2
Child Thread Count: 3
main Thread Count: 3
main Thread Count: 4
Child Thread Count: 4
main Thread Count: 5
Child Thread Count: 5

-----------------------------------------------END----------------------------------------------------------

30

You might also like