Oops With Java Lab Manual - 2024
Oops With Java Lab Manual - 2024
RV Educational Institutions®
RV Institute of Technology and Management
(Affiliated to VTU, Belagavi)
JP Nagar 8th Phase, Bengaluru - 560076
Department of
Information Science and Engineering
LAB MANUAL
Course Name : Object Oriented Programming with Java Lab
CONTENTS
Sl No Particulars Page No
1 Syllabus 6
2 Introduction To Object Oriented Programming 7
Overview of Java 8
Program 1:
3 13
Develop a JAVA program to add TWO matrices of suitable order N
(The value of N should be read from command line arguments).
Program 2:
4 Develop a stack class to hold a maximum of 10 integers with suitable 17
methods. Develop a JAVA main method to illustrate Stack
operations.
Program 3:
A class called Employee, which models an employee with an ID,
5 name and salary, is designed as shown in the following class 21
diagram. The method raiseSalary (percent) increases the salary by
the given percentage. Develop the Employee class and suitable main
method for demonstration.
Program 4:
A class called MyPoint, which models a 2D point with x and y
coordinates, is designed as follows:
• Two instance variables x (int) and y (int).
• A default (or "no-arg") constructor that construct a point at the
default location of (0, 0).
• A overloaded constructor that constructs a point with the given x
and y coordinates.
• A method setXY() to set both x and y.
6 23
• A method getXY() which returns the x and y in a 2-element int
array.
• A toString() method that returns a string description of the instance
in the format "(x, y)".
• A method called distance(int x, int y) that returns the distance from
this point to another point at the given (x, y) coordinates
Program 5:
Develop a JAVA program to create a class named shape. Create three
7 sub classes namely: circle, triangle and square, each class has two 29
member functions named draw () and erase (). Demonstrate
polymorphism concepts by developing suitable methods, defining
member data and main program.
Program 6:
Develop a JAVA program to create an abstract class Shape with
8 abstract methods calculateArea() and calculatePerimeter(). Create 32
subclasses Circle and Triangle that extend the Shape class and
implement the respective methods to calculate the area and perimeter
of each shape.
Program 7:
Develop a JAVA program to create an interface Resizable with
9 methods resizeWidth(int width) and resizeHeight(int height) that 35
allow an object to be resized. Create a class Rectangle that
implements the Resizable interface and implements the resize
methods
Program 8:
10 Develop a JAVA program to create an outer class with a function 39
display. Create another class inside the outer class named inner with
a function called display and call the two functions in the main class.
Program 9:
11 42
Develop a JAVA program to raise a custom exception (user defined
exception) for DivisionByZero using try, catch, throw and finally.
Program 10:
12 45
Develop a JAVA program to create a package named mypack and
import & implement it in a suitable class.
Program 11:
Write a program to illustrate creation of threads using runnable class.
13 48
(start method start each of the newly created thread. Inside the run
method there is sleep() for suspend the thread for 500 milliseconds).
14 Program 12: 52
Program 13:
15 Create a multi-threaded banking system where multiple customers can
deposit and withdraw money from their accounts concurrently while
maintaining data consistency.
Program 14:
Create a custom exception class called "ProductAddException" that
extends the standard Java "Exception" class.
If the user tries to add a product with a quantity less than 0, throw a
"ProductAddException" with a suitable error message.
Ensure that the program gracefully handles any other exceptions that
may occur during the product addition process.
Course Description
• 15 marks for the conduction of the experiment and preparation of laboratory record,
and 10 marks for the test to be conducted after the completion of all the laboratory
sessions.
• On completion of every experiment/program in the laboratory, the students shall be
evaluated including viva-voce and marks shall be awarded on the same day.
• The CIE marks awarded in the case of the Practical component shall be based on the
continuous evaluation of the laboratory report. Each experiment report can be evaluated
for 10 marks. Marks of all experiments’ write-ups are added and scaled down to 15
marks.
• The laboratory test (duration 02/03 hours) after completion of all the experiments shall
be conducted for 50 marks and scaled down to 10 marks.
• Scaled-down marks of write-up evaluations and tests added will be CIE marks for the
laboratory component of IPCC for 25 marks.
• The student has to secure 40% of 25 marks to qualify in the CIE of the practical
component of the IPCC.
Programs List:
1) Develop a JAVA program to add TWO matrices of suitable order N (The value of N
should be read from command line arguments).
2) Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop
a JAVA main method to illustrate Stack operations.
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 raiseSalary (percent)
increases the salary by the given percentage. Develop the Employee class and suitable
main method for demonstration.
4) A class called MyPoint, which models a 2D point with x and y coordinates, is designed
as follows:
•Two instance variables x (int) and y (int).
•A default (or "no-arg") constructor that construct a point at the default location of (0,
0).
•A overloaded constructor that constructs a point with the given x and y coordinates.
•A method setXY() to set both x and y.
•A method getXY() which returns the x and y in a 2-element int array.
•A toString() method that returns a string description of the instance in the format "(x,
y)".
•A method called distance(int x, int y) that returns the distance from this point to
another point at the given (x, y) coordinates
•An overloaded distance(MyPoint another) that returns the distance from this point to
the given MyPoint instance (called another)
•Another overloaded distance() method that returns the distance from this point to the
origin (0,0)
•Develop the code for the class MyPoint. Also develop a JAVA program (called
TestMyPoint) to test all the methods defined in the class.
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.
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.
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
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.
9) Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.
10) Develop a JAVA program to create a package named mypack and import & implement
it in a suitable class.
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).
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
Laboratory Outcomes:
The student should be able to:
• Use Eclipse/NetBeans IDE to design, develop, debug Java Projects.
• Analyze the necessity for Object Oriented Programming paradigm over structured
programming and become familiar with the fundamental concepts in OOP.
• Demonstrate the ability to design and develop java programs, analyze, and interpret
object-oriented data and document results.
• Apply the concepts of multiprogramming, exception/event handling, abstraction to
develop robust programs.
• Develop user friendly applications using File I/O and GUI concepts.
● Scaled-down marks of write-up evaluations and tests added will be CIE marks for the
laboratory
component of IPCC for 25 marks.
● The student has to secure 40% of 25 marks to qualify in the CIE of the practical component
of the IPCC.
• Classes are user-defined data types that act as the blueprint for individual objects, attributes
and methods.
• Objects are instances of a class created with specifically defined data. Objects can
correspond to real-world objects or an abstract entity. When class is defined initially, the
description is the only object that is defined.
• Methods are functions that are defined inside a class that describe the behaviors of an
object. Each method contained in class definitions starts with a reference to an instance
object. Additionally, the subroutines contained in an object are called instance methods.
Programmers use methods for reusability or keeping functionality encapsulated inside one
object at a time
Encapsulation: This principle states that all important information is contained inside an
object and only select information is exposed. The implementation and state of each object are
privately held inside a defined class. Other objects do not have access to this class or the
authority to make changes. They are only able to call a list of public functions or methods. This
characteristic of data hiding provides greater program security and avoids unintended data
corruption.
Abstraction: Objects only reveal internal mechanisms that are relevant for the use of other
objects, hiding any unnecessary implementation code. The derived class can have its
functionality extended. This concept can help developers more easily make additional changes
or additions over time.
Inheritance: Classes can reuse code from other classes. Relationships and subclasses between
objects can be assigned, enabling developers to reuse common logic while still maintaining a
unique hierarchy. This property of OOP forces a more thorough data analysis, reduces
development time and ensures a higher level of accuracy.
Polymorphism: Objects are designed to share behaviors and they can take on more than one
form. The program will determine which meaning or usage is necessary for each execution of
that object from a parent class, reducing the need to duplicate code. A child class is then created,
which extends the functionality of the parent class. Polymorphism allows different types of
objects to pass through the same interface.
Overview of Java
Java Is Important to the Internet, The Internet helped catapult Java to the forefront of
programming, and Java, in turn, has had a profound effect on the Internet. The reason for this
is quite simple: Java expands the universe of objects that can move about freely in cyberspace.
In a network, two very broad categories of objects are transmitted between the server and our
personal computer: passive information and dynamic, active programs.
Features of JAVA
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
Eclipse IDE
In the context of computing, Eclipse is an integrated development environment (IDE) for
developing applications using the Java programming language and other programming
languages such as C/C++, Python, PERL, Ruby etc. The Eclipse platform which provides the
foundation for the Eclipse IDE is composed of plug-ins and is designed to be extensible using
additional plug-ins. Developed using Java, the Eclipse platform can be used to develop rich
client applications, integrated development environments and other tools. Eclipse can be used
as an IDE for any programming language for which a plug-in is available.
Click "Finish" button and Eclipse IDE will generate the java project automatically
Right click on 'src' folder and select from context menu New --> Class.
Write "Test" in the 'Name' field and select the check-box for 'public static void main(String[]
args)'.
Click "Finish" button. Eclipse will generate a java class and open the same in the java editor
Right click on 'test.java' and select from context menu 'Run As' --> 'Java Application'.
Your code will print related output in the eclipse console.
Lab Programs
1) Develop a JAVA program to add TWO matrices of suitable order N (The value of N
should be read from command line arguments).
int N = Integer.parseInt(args[0]);
if (N <= 0) {
System.out.println("N must be a positive integer.");
System.exit(1);
}
// Fill matrixA and matrixB with values (you can modify this part)
fillMatrix(matrixA, N);
fillMatrix(matrixB, N);
System.out.println("Matrix B:");
printMatrix(matrixB);
// Fill a matrix with random values (you can modify this part)
public static void fillMatrix(int[][] matrix, int N) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = i + j; // You can change this to your desired values
}
}
}
// Print a matrix
public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}
Output:
2) Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a
JAVA main method to illustrate Stack operations.
A stack is a fundamental data structure in computer science and programming that follows the
Last-In, First-Out (LIFO) principle. It's a collection of elements with two primary operations:
push and pop. Stacks are often implemented with arrays or linked lists.
Push: This operation adds an element to the top of the stack. It's like placing an item on top of
a stack of books.
Pop: This operation removes the top element from the stack. You can think of it as taking the
top book off the stack.
Peek or Top: This operation retrieves the top element without removing it from the stack. It's
like looking at the top book without taking it off.
IsEmpty: This operation checks if the stack is empty. If there are no elements in the stack, it
returns true; otherwise, it returns false.
Stacks are often used in situations where you need to maintain a last-in, first-out order. Some
common use cases for stacks include:
Function Call Stack: In many programming languages, function calls are managed using a
stack. When a function is called, its information is pushed onto the stack, and when it returns,
it's popped off the stack.
Undo/Redo Functionality: Stacks are used to implement undo and redo operations in software
applications. Each change is pushed onto the stack, and undo pops the most recent change off
the stack.
Expression Evaluation: Stacks can be used to evaluate expressions in reverse Polish notation
(postfix notation). Operators and operands are pushed and popped as the expression is
processed.
Backtracking: Stacks are helpful for backtracking algorithms, such as depth-first search in
graph traversal.
Code:
class Stack {
private int maxSize = 10;
private int top;
private int[] stackArray;
public Stack() {
stackArray = new int[maxSize];
top = -1; // Initialize the top of the stack
}
stack.push(5);
stack.push(10);
stack.push(15);
stack.display();
stack.display();
stack.push(20);
stack.push(25);
stack.display();
}
}
Output:
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 raiseSalary (percent)
increases the salary by the given percentage. Develop the Employee class and suitable main
method for demonstration.
Code:
import java.text.NumberFormat;
import java.util.Locale;
Output:
4) A class called MyPoint, which models a 2D point with x and y coordinates, is designed
as follows:
•Two instance variables x (int) and y (int).
•A default (or "no-arg") constructor that construct a point at the default location of
(0, 0).
•A overloaded constructor that constructs a point with the given x and y coordinates.
•A method setXY() to set both x and y.
•A method getXY() which returns the x and y in a 2-element int array.
•A toString() method that returns a string description of the instance in the format "(x,
y)".
•A method called distance(int x, int y) that returns the distance from this point to
another point at the given (x, y) coordinates
•An overloaded distance(MyPoint another) that returns the distance from this point to
the given MyPoint instance (called another)
•Another overloaded distance() method that returns the distance from this point to the
origin (0,0)
Develop the code for the class MyPoint. Also develop a JAVA program (called
TestMyPoint) to test all the methods defined in the class.
Code:
class MyPoint {
private int x;
private int y;
// Default constructor
public MyPoint() {
this.x = 0;
this.y = 0;
}
// Overloaded constructor
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
double distance2 = point1.distance(); // Distance between point1 and the origin (0,0)
Output:
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.
Polymorphism is one of the fundamental concepts in object-oriented programming (OOP)
and plays a crucial role in designing and implementing flexible and extensible software. It
allows objects of different classes to be treated as objects of a common superclass, and it
enables you to create more generic and flexible code.
Polymorphism:
"Polymorphism" is derived from two Greek words: "poly," meaning many, and "morph,"
meaning form. In the context of OOP, polymorphism means "many forms."
Polymorphism allows objects of different classes to be treated as objects of a common
superclass or interface. This promotes code reusability and flexibility.
Method Overriding:
Polymorphism is often achieved through method overriding. In a subclass, you can provide a
specific implementation of a method that is already defined in a superclass. This allows you to
customize the behavior of the method for the subclass.
Dynamic Binding:
One of the key features of polymorphism is dynamic method binding. This means that the
decision about which method to call is made at runtime, based on the actual type of the object
rather than the reference type.
This enables the code to work with objects of different subclasses using a common interface or
superclass, and the appropriate method implementation is selected at runtime.
Code:
class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
@Override
public void erase() {
System.out.println("Erasing a circle");
}
}
@Override
public void erase() {
System.out.println("Erasing a triangle");
}
}
@Override
public void erase() {
System.out.println("Erasing a square");
}
}
Output:
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.
In Java, an abstract class and abstract methods are used to define a blueprint for other
classes. They are crucial concepts in object-oriented programming and are often used when
you want to create a common interface for a group of related classes while ensuring that certain
methods are implemented by each subclass. Here's an explanation of abstract classes and
abstract methods:
Abstract Class:
An abstract class is a class that cannot be instantiated on its own. It serves as a blueprint for
other classes and may contain both regular (concrete) methods and abstract methods.
Abstract classes are declared using the abstract keyword in Java.
They can have constructors, instance variables, and regular methods just like any other class.
Abstract classes are typically used when you want to create a common base class for a group
of related subclasses, and you want to ensure that certain methods are implemented in those
subclasses.
Abstract Method:
An abstract method is a method declared in an abstract class but doesn't have a method body
(implementation). It's defined with the abstract keyword and followed by a method signature
and a semicolon, but without curly braces.
Subclasses of an abstract class must provide concrete (implemented) versions of all the abstract
methods declared in the superclass. This is a way to enforce that certain behavior must be
defined in subclasses.
Abstract methods are declared in the abstract class to specify what each subclass should
implement, but the actual implementation details are left to the subclasses.
Abstract methods are often used when you have a method that should be implemented
differently in each subclass, but you want to ensure that it's present in each subclass.
Code:
abstract class Shape {
// Abstract method to calculate the area
public abstract double calculateArea();
// Constructor
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
// Constructor
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
@Override
public double calculateArea() {
// Using Heron's formula to calculate the area of a triangle
double s = (side1 + side2 + side3) / 2.0;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
@Override
public double calculatePerimeter() {
return side1 + side2 + side3;
}
}
public class Main {
public static void main(String[] args) {
Circle circle = new Circle(5.0);
System.out.println("Circle - Area: " + circle.calculateArea());
System.out.println("Circle - Perimeter: " + circle.calculatePerimeter());
Design by Contract:
Interfaces are a way to apply the "Design by Contract" principle, which emphasizes that classes
should adhere to a specific contract in terms of behavior.
Encapsulation:
Interfaces help in encapsulation by providing a clear and well-defined way to interact with
objects.
In summary, the concept of an interface in programming is a powerful way to define a contract
for classes. It promotes flexibility, code reusability, polymorphism, and separation of concerns
in software development. By adhering to these contracts, classes can interact with one another
and share functionality in a structured and predictable way.
Code:
// Define the Resizable interface
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}
// Constructor
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
System.out.println("Resized Dimensions:");
rectangle.displayDimensions();
}
}
Output:
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.
Nested Classes:
In Java, you can define a class within another class. The class defined within is referred to as a
"nested class" or an "inner class."
Inner classes are used to logically group classes that are only used in one place, to increase
encapsulation, and to control access.
Outer Class:
In the program, the Outer class is the "outer" class that contains the Inner class. It also has a
display method.
Inner Class:
The Inner class is an "inner" class defined within the Outer class. It also has a display method.
It can access the members of the outer class, including private members.
Accessing Inner Class:
To create an instance of the inner class, you need to use the outer class instance. In the main
method, Outer.Inner innerObj = outerObj.new Inner(); demonstrates how to create an inner
class object using an outer class object.
Method Overriding:
Both the outer and inner classes have a method named display. This demonstrates the concept
of method overriding. The inner class's display method effectively overrides the outer class's
display method.
Method Invocation:
• The program shows how to call the display methods of both the outer and inner classes.
• When you call outerObj.display(), it invokes the display method of the outer class.
• When you call innerObj.display(), it invokes the display method of the inner class.
Namespace Separation:
Inner classes can provide a way to logically group related functionality and separate their
names from the outer class. This can help avoid naming conflicts and improve code
organization.
Code:
class Outer {
void display() {
System.out.println("This is the outer class's display method.");
}
class Inner {
void display() {
System.out.println("This is the inner class's display method.");
}
}
}
Output:
9) Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.
Exception:
An exception is an abnormal or unexpected event or condition that occurs during the execution
of a program and disrupts the normal flow of the program.
Exceptions can represent various types of errors or problems, such as division by zero, file not
found, invalid input, or network connection issues.
Types of Exceptions:
Exceptions are typically categorized into two types: checked exceptions and unchecked
exceptions.
Checked exceptions are exceptions that must be either caught (using try-catch) or declared
(using throws) by the code that calls a method that might throw the exception. Examples
include IOException.
Unchecked exceptions (also known as runtime exceptions) are exceptions that do not have to
be explicitly handled. They usually indicate programming errors, such as NullPointerException
or ArrayIndexOutOfBoundsException.
Exception Handling:
Exception handling is a mechanism provided by programming languages to gracefully and
safely deal with exceptions when they occur.
It allows you to specify what should happen when an exception is encountered, such as
providing alternative actions, logging the error, or displaying a meaningful error message.
The try-catch Block:
The most common way to handle exceptions is by using a try-catch block. Within the try block,
you enclose code that might throw an exception. In the catch block, you define how to handle
the exception if one is thrown.
If an exception occurs within the try block, the program immediately transfers control to the
appropriate catch block.
The throws Keyword:
The throws keyword is used to declare that a method might throw a specific exception. When
a method declares an exception using throws, it is essentially saying, "I might have a problem,
and I'm not handling it here; I'm passing the responsibility to the caller."
The calling method must either handle the exception using a try-catch block or declare the
exception using throws in its own method signature.
Code:
// Custom exception class for DivisionByZero
class DivisionByZeroException extends Exception {
public DivisionByZeroException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
try {
int numerator = 10;
int denominator = 0;
if (denominator == 0) {
throw new DivisionByZeroException("Division by zero is not allowed.");
}
Output:
10) Develop a JAVA program to create a package named mypack and import & implement
it in a suitable class.
Packages:
In programming, a package is a way to organize related classes and interfaces into a single
namespace. It provides a structured mechanism for grouping classes, which makes it easier to
manage and maintain your code. Here are the key concepts related to packages:
Namespace Organization:
Packages are used to organize classes, interfaces, and other related elements into separate
namespaces.
A package is like a directory or folder that contains related classes. It helps avoid naming
conflicts by keeping classes with the same name separate.
Access Control:
Packages also provide a level of access control. You can use the public, protected, or default
(no modifier) access modifiers to control the visibility of classes and their members within the
same package or in other packages.
Hierarchical Structure:
Packages can have a hierarchical structure, which means you can have sub-packages within
packages. For example, com.example.mypackage is a package hierarchy where mypackage is
a sub-package of example, and example is a sub-package of com.
Package Declaration:
In Java, packages are declared using the package keyword at the top of each source code file.
For example, package com.example.mypackage; declares that the class belongs to the
com.example.mypackage package.
Import Statement:
To use a class or interface from another package, you need to import it using the import
statement. For example, import com.example.mypackage.MyClass; allows you to use MyClass
from the com.example.mypackage package.
Java Standard Libraries:
Java uses packages extensively in its standard libraries. For instance, classes related to I/O
operations are in the java.io package, and classes for handling exceptions are in the java.lang
package.
Third-Party Libraries:
When you use third-party libraries in your Java applications, they are often packaged into JAR
files with well-organized package structures. This allows you to easily integrate and use these
libraries in your code.
Code:
package mypack;
return a / b;
} else {
throw new ArithmeticException("Division by zero is not allowed.");
}
}
}
import mypack.Calculator;
Output:
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).
Threads are a fundamental concept in computer science and programming, allowing a program
to execute multiple tasks concurrently. Here are the key concepts related to threads:
Thread:
A thread is the smallest unit of a program's execution. It represents a single sequence of
instructions and operates independently within a process.
Threads are also known as lightweight processes because they share the same memory space
and resources of the parent process.
Multithreading:
Multithreading is a programming technique that allows a single process to have multiple
threads running concurrently.
Each thread within a process can execute different parts of the program, enabling parallelism
and potentially improving performance.
Concurrency vs. Parallelism:
Concurrency is the ability of a system to handle multiple tasks in overlapping time periods. It
doesn't necessarily mean that tasks are executed simultaneously.
Parallelism, on the other hand, involves tasks running at the same time on multiple processors
or cores, achieving true simultaneous execution.
Thread Creation:
Threads can be created in various ways, such as by extending the Thread class or implementing
the Runnable interface in Java.
Creating threads allows you to perform tasks concurrently and efficiently.
Thread States:
Threads can be in different states, including:
New: The thread has been created but not started yet.
Runnable: The thread is ready to run, but the CPU scheduler has not selected it.
Running: The thread is currently executing its code.
Blocked: The thread is waiting for a resource or condition to become available.
Terminated: The thread has finished its execution.
Synchronization:
When multiple threads access shared resources concurrently, synchronization is used to prevent
data corruption or race conditions.
Locks, semaphores, and monitors are used to control thread access to critical sections of code.
Thread Safety:
Ensuring thread safety is crucial to prevent issues like data corruption or race conditions.
It involves designing code and data structures to work correctly and efficiently in a
multithreaded environment.
Communication Between Threads:
Threads often need to communicate and coordinate their actions. Various mechanisms, such as
message passing, shared memory, and thread signaling, can be used for this purpose.
Benefits of Multithreading:
Improved program responsiveness: Multithreading allows a program to remain responsive even
when performing time-consuming tasks.
Efficient resource utilization: Multithreading can make better use of multiple CPU cores and
resources.
Simplified program structure: Multithreading can make it easier to break complex tasks into
smaller, more manageable parts.
Challenges and Pitfalls:
Multithreading can introduce complexities like race conditions, deadlocks, and increased
debugging difficulties.
Careful design and thorough testing are required to avoid these pitfalls.
Thread Priority:
Threads can have different priorities that affect how the operating system schedules them for
execution. Higher-priority threads are favored but are not guaranteed exclusive execution.
Thread Termination:
Properly terminating threads is important to avoid resource leaks. Threads can be terminated
gracefully or forcefully.
Threads are a powerful tool for enabling concurrent execution in modern software. They allow
programs to take advantage of multicore processors and improve performance and
responsiveness. However, multithreading also introduces complexities that need to be carefully
managed to ensure correct and efficient program behavior.
Code:
class MyRunnable implements Runnable {
public void run() {
try {
System.out.println("Thread started: " + Thread.currentThread().getName());
Thread.sleep(500); // Suspend the thread for 500 milliseconds
System.out.println("Thread ended: " + Thread.currentThread().getName());
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " + Thread.currentThread().getName());
}
}
}
Output:
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
Code:
class MyThread extends Thread {
public MyThread(String name) {
super(name); // Call the Thread class constructor with a thread name
start(); // Start the thread
}
Output:
13) Create a multi-threaded banking system where multiple customers can deposit and
withdraw money from their accounts concurrently while maintaining data
consistency.
Code:
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
balance = initialBalance;
}
customer1.start();
customer2.start();
}
}
Output:
15) Create a custom exception class called "ProductAddException" that extends the
standard Java "Exception" class.
Write a program that allows users to add products to the inventory. Implement exception
handling to catch and handle the following scenarios:
If the user tries to add a product with a negative price, throw a "ProductAddException"
with an appropriate error message.
If the user tries to add a product with a quantity less than 0, throw a
"ProductAddException" with a suitable error message.
Ensure that the program gracefully handles any other exceptions that may occur during
the product addition process
Code:
import java.util.Scanner;
class Product {
private String name;
private double price;
private int quantity;
@Override
public String toString() {
return "Product: " + name + " | Price: $" + price + " | Quantity: " + quantity;
}
}
try {
System.out.println("Add a new product to the inventory:");
System.out.print("Product Name: ");
String name = scanner.nextLine();
if (price < 0) {
throw new ProductAddException("Price cannot be negative.");
}
if (quantity < 0) {
throw new ProductAddException("Quantity cannot be negative.");
}
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
What is a class?
A class is simply a representation of a type of object. It is the blueprint/plan/template that
describes the details of an object.
What is an Object?
An object is an instance of a class. It has its own state, behavior, and identity.
What is Encapsulation?
Encapsulation is an attribute of an object, and it contains all data which is hidden. That
hidden data can be restricted to the members of that class.
What is Polymorphism?
Polymorphism is nothing but assigning behavior or value in a subclass to something that was
already declared in the main class. Simply, polymorphism takes more than one form.
What is Inheritance?
Inheritance is a concept where one class shares the structure and behavior defined in another
class. If Inheritance applied to one class is called Single Inheritance, and if it depends on
multiple classes, then it is called multiple Inheritance.
Constructor Name should be the same as a class name. A constructor must have no return
type.
Define Destructor?
A destructor is a method which is automatically called when the object is made of scope or
destroyed. Destructor name is also same as class name but with the tilde symbol before the
name.
A friend can be declared anywhere in the class declaration, and it cannot be affected by
access control keywords like private, public, or protected.
Example
[crayon-5f2cf66ff2e66074243655/]
15) What is operator overloading?
Operator overloading is a function where different operators are applied and depends on the
arguments. Operator,-,* can be used to pass through the function, and it has its own
precedence to execute
Call by Value – Value passed will get modified only inside the function, and it returns the
same value whatever it is passed into the function.
Call by Reference – Value passed will get modified in both inside and outside the functions
and it returns the same or different value.
What is an interface?
An interface is a collection of an abstract method. If the class implements an interface, it
thereby inherits all the abstract methods of an interface.
A compiler recognizes a token, and it cannot be broken down into component elements.
Keywords, identifiers, constants, string literals, and operators are examples of tokens.
Even punctuation characters are also considered as tokens. Example: Brackets, Commas,
Braces, and Parentheses.
Overriding is the same method names with the same arguments and return types associated
with the class and its child class.
An object is an instance of a class. Objects hold multiple information, but classes don’t have
any information. Definition of properties and functions can be done in class and can be used
by the object.
What is an abstraction?
Abstraction is a useful feature of OOPS, and it shows only the necessary details to the client
of an object. Meaning, it shows only required details for an object, not the inner constructors,
of an object. Example – When you want to switch on the television, it is not necessary to
know the inner circuitry/mechanism needed to switch on the TV. Whatever is required to
switch on TV will be shown by using an abstract class.
Yes, it is possible to call the base method without creating an instance. And that method
should be “Static method."
Doing Inheritance from that class.-Use Base Keyword from a derived class.
The new modifier instructs the compiler to use the new implementation instead of the base
class function. Whereas, Override modifier helps to override the base class function.
–Parametric Constructor – With Parameters. Create a new instance of a class and also passing
arguments simultaneously.
Example -
[crayon-5f2cf66ff2e6f715458999/]
38) What are all the operators that cannot be overloaded?
Dynamic or Run time polymorphism is also known as method overriding in which call to an
overridden function is resolved during run time, not at the compile time. It means having two
or more methods with the same name, same signature but with different implementation.
This is a special constructor for creating a new object as a copy of an existing object. There
will always be only one copy constructor that can be either defined by the user or the system.
The base class is the most generalized class, and it is said to be a root class. A Subclass is a
class that inherits from one or more base classes.
The superclass is the parent class from which another class inherits.
Dynamic Binding is a binding in which name can be associated with the class during
execution time, and it is also called as Late Binding.
Which OOPS concept exposes only the necessary information to the calling functions?
Encapsulation
A sub-class is a class which inherits from another class called super class. Sub-class can
access all public and protected methods and fields of its super class.
2. Protected:Method,Field can be accessed from the same class to which they belong or
from the sub-classes,and from the class of same package,but not from outside.
3. Default: Method,Field,class can be accessed only from the same package and not
from outside of it’s native package.
4. Private: Method,Field can be accessed from the same class to which they belong.
The best example of singleton usage scenario is when there is a limit of having only one
connection to a database due to some driver limitations or because of any licensing issues.
1) For Loops
For loops are used in java to execute statements repeatedly for a given number of times. For
loops are used when number of times to execute the statements is known to programmer.
2) While Loops
While loop is used when certain statements need to be executed repeatedly until a condition
is fulfilled. In while loops, condition is checked first before execution of statements.
3) Do While Loops
Do While Loop is same as While loop with only difference that condition is checked after
execution of block of statements. Hence in case of do while loop, statements are executed at
least once.
An infinite loop runs without any condition and runs infinitely. An infinite loop can be
broken by defining any breaking logic in the body of the statement blocks.
for (;;)
// Statements to execute
used in a loop, loop is broken instantly while when continue keyword is used, current
iteration is broken and loop continues with next iteration.
system.out.println(counter); if (counter==4) {
break;}
In the below example when counter reaches 4, loop jumps to next iteration and any
statements after the continue keyword are skipped for current iteration.
if (counter==4) { continue;
}
In below example, a constant with the name const_val is declared and assigned avalue:
Private Final int const_val=100
When a method is declared as final,it can NOT be overridden by the subclasses.This method
are faster than any other method,because they are resolved at complied time.
When a class is declares as final,it cannot be subclassed. Example String,Integer and other
wrapper classes.
In multi-threading how can we ensure that a resource isn't used by multiple threads
simultaneously?
In multi-threading, access to the resources which are shared among multiple threads can be
controlled by using the concept of synchronization. Using synchronized keyword, we can
ensure that only one thread can use shared resource at a time and others can get control of the
resource only once it has become free from the other one using it.