[go: up one dir, main page]

0% found this document useful (0 votes)
29 views43 pages

Java 8 To 15

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)
29 views43 pages

Java 8 To 15

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/ 43

import java.util.

Scanner;

import java.util.Vector;

public class StringVectorManager {

public static void main(String[] args) {

// Create a vector to store strings

Vector<String> stringVector = new Vector<>();

// Create a scanner object for input

Scanner scanner = new Scanner(System.in);

// Get the number of strings to add initially

System.out.print("Enter the number of strings to add: ");

int n = scanner.nextInt();

scanner.nextLine(); // Consume the newline character

// Add n strings to the vector

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

System.out.print("Enter string " + (i + 1) + ": ");

String str = scanner.nextLine();

stringVector.add(str);

// Display the vector after the initial addition of strings

System.out.println("Current Vector: " + stringVector);

// Input a new string to check and modify the vector

System.out.print("Enter a new string to check: ");

String newString = scanner.nextLine();

// Check if the string is present in the vector


if (stringVector.contains(newString)) {

// If present, delete the string from the vector

stringVector.remove(newString);

System.out.println("String '" + newString + "' was present and has been removed.");

} else {

// If not present, add the string to the vector

stringVector.add(newString);

System.out.println("String '" + newString + "' was not present and has been added.");

// Display the final state of the vector

System.out.println("Final Vector: " + stringVector);

}
Experiment No. 08
Aim: Write a Java program to add n strings in a vector array.
Prerequisite: JDK 17
Theory:
Vector is part of the Java Collections Framework and is similar to an array, but with two key
differences: it can dynamically grow or shrink in size, and it is synchronized.
Before you start to use vectors, import it from the java.util.package as follow:
import java.util.Vector ;

Creating a Vector:
You can create a Vector using one of its constructors.
For example:
import java.util.Vector;

public class VectorExample {


public static void main(String[] args) {
// Creating a Vector of Strings
Vector<String> vector = new Vector<>();

// Creating a Vector with initial capacity


Vector<Integer> vectorWithCapacity = new Vector<>(10);

// Creating a Vector with initial capacity and capacity increment


Vector<Double> vectorWithCapacityAndIncrement = new Vector<>(10, 5);
}
}
About Vectors:
• A vector in java is a dynamic data structure that can be accessed using an integer index.
• Though similar to ArrayList, it is synchronized, containing some legacy methods not
available in the collection framework.
• Insertion order is maintained.
• It is rarely used in a non-thread environment.
• Due to synchronization, vectors have a poor performance in searching, adding,
updating, and deleting elements.
• Iterators of vector class fail fast and throw the ConcurrentModificationException in case
of concurrent modification.
• A stack is its directly known subclass.
Constructors:
1. Vector(int initialCapacity, int Increment):
This creates a vector in java with an initial capacity as specified, and the increment is
also specified. With increment, the number of elements allocated each time the vector is resized
upward is specified.
Syntax:
Vector<V> e = new Vector<V>(int initialCapacity, int Increment);
2. Vector(int initialCapacity):
It creates a vector in java with an initial capacity equal to size as specified.
Syntax:
Vector<V> e = new Vector<V>(int initialCapacity);
3. Vector():
It creates a vector in java with an initial default capacity of 10.
Syntax:
Vector<V> e = new Vector<V>();
4. Vector(Collection c):
It creates a vector in java whose elements are those of collection c.
Syntax:
Vector<V> e = new Vector<V>(Collection c);
Methods:
Here are some frequently used methods of vector in java:
1. Add Elements
Boolean add(Object o)- An element is appended at the end of the vector
Void add( int index V element)- The given element is added to the specified index in the vector
2. Remove Elements
Boolean Remove(object o) – used to remove the element at the specified index in the vector
When the element is removed, all the elements are shifted left to fill the spaces; the indices are
then updated.
3. Change Elements
The set () method can be used to change the element after adding the elements. The element’s
index can be referenced as a vector is indexed. This method takes the index and the updated
element.
4. Iterate the Vector
There are several ways to loop through a vector. One of them is the get() method.

Advantages of Vector in Java:


The dynamic size of vectors avoids memory wastage, and the size of our data structure can be
changed any time in the middle of the program.
Both vectors and ArrayLists are dynamic. However, vectors are more advantageous as:
• Vectors are synchronized.
• It has some legacy functions that cannot be implemented on ArrayLists.

Conclusion: In this experiment we studied that, a vector in java is a dynamic array with no size
limit that is part of the Java Collection Framework. We also studied the various constructors and
popularly used methods of vectors.
Experiment No.: 09
Name of Experiment: Write a program to study concepts of inheritance. Aim: Study
concepts of inheritance
Requirements: JDK 1.7/8
Theory:
Inheritance is one of the three foundation principles of object-oriented programming because it
allows the creation of hierarchical classifications.
Inheritance Basics:
Java supports inheritance by allowing one class to incorporate another class into its declaration.
This is done by using the extends keyword. Thus, the subclass adds to (extends) the superclass.
When a class inherits from another class, the child class automatically inherits all the
characteristics (member variables) and behavior (methods) from the parent class. Inheritance is
always additive; there is no way to inherit from a class and get less than what the parent class
has. Inheritance in Java is handled through the keyword extends . When one class inherits from
another class, the child class extends the parent class. For example,
public class DogClass extends MammalClass
{
...
}
The items that men and dogs have in common could be said to be common to all
mammals; therefore, you can create a MammalClass to handle these similarities.
Access modifiers:
It’s important to understand when members (both variables and methods) in the class are
accessible.
Why Do We Need Java Inheritance?
• Code Reusability: The code written in the Superclass is common to all subclasses. Child
classes can directly use the parent class code.
• Method Overriding: Method Overriding is achievable only through Inheritance. It is one
of the ways by which Java achieves Run Time Polymorphism.
• Abstraction: The concept of abstract where we do not have to provide all details, is
achieved through inheritance. Abstraction only shows the functionality to the user.
Important Terminologies Used in Java Inheritance
• Class: Class is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. Class is not a real-world entity. It is just a template or
blueprint or prototype from which objects are created.
• Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).
• Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a
derived class, extended class, or child class). The subclass can add its own fields and
methods in addition to the superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.

Types of Inheritance :
Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
ALGORITHM :
1. Declare super class
2. Add data member and methods
3. Declare sub class extends super class
4. Add data member and methods

Conclusion: Thus, we have studied about concept of inheritance, types of inheritance and
access specifiers.
// Base class: Teacher

class Teacher {

String name;

String department;

int age;

// Constructor for Teacher class

public Teacher(String name, String department, int age) {

this.name = name;

this.department = department;

this.age = age;

// Method to display information of the teacher

public void displayInfo() {

System.out.println("Name: " + name);

System.out.println("Department: " + department);

System.out.println("Age: " + age);

// Derived class: Professor

class Professor extends Teacher {

String specialization;

// Constructor for Professor class

public Professor(String name, String department, int age, String specialization) {

super(name, department, age); // Call the constructor of the Teacher class

this.specialization = specialization;

}
// Override displayInfo method to include specialization

@Override

public void displayInfo() {

super.displayInfo();

System.out.println("Designation: Professor");

System.out.println("Specialization: " + specialization);

// Derived class: Associate_Professor

class Associate_Professor extends Teacher {

String researchArea;

// Constructor for Associate_Professor class

public Associate_Professor(String name, String department, int age, String researchArea) {

super(name, department, age); // Call the constructor of the Teacher class

this.researchArea = researchArea;

// Override displayInfo method to include research area

@Override

public void displayInfo() {

super.displayInfo();

System.out.println("Designation: Associate Professor");

System.out.println("Research Area: " + researchArea);

// Derived class: Assistant_Professor

class Assistant_Professor extends Teacher {

int yearsOfExperience;
// Constructor for Assistant_Professor class

public Assistant_Professor(String name, String department, int age, int yearsOfExperience) {

super(name, department, age); // Call the constructor of the Teacher class

this.yearsOfExperience = yearsOfExperience;

// Override displayInfo method to include years of experience

@Override

public void displayInfo() {

super.displayInfo();

System.out.println("Designation: Assistant Professor");

System.out.println("Years of Experience: " + yearsOfExperience);

// Main class to demonstrate the inheritance

public class TeacherInheritanceDemo {

public static void main(String[] args) {

// Create objects for each type of professor

Professor professor = new Professor("Dr. John Smith", "Computer Science", 50, "Artificial
Intelligence");

Associate_Professor associateProfessor = new Associate_Professor("Dr. Jane Doe", "Mechanical


Engineering", 45, "Fluid Dynamics");

Assistant_Professor assistantProfessor = new Assistant_Professor("Dr. Alex Brown", "Physics",


35, 5);

// Display information for each type of professor

System.out.println("===== Professor Info =====");

professor.displayInfo();

System.out.println("\n===== Associate Professor Info =====");


associateProfessor.displayInfo();

System.out.println("\n===== Assistant Professor Info =====");

assistantProfessor.displayInfo();

}
EXPERIMENT NO.10
Aim: design and implement classes for employees and departments using OOP principles like
encapsulation, class interaction, and dynamic behaviors like salary enhancement. This models
organizational structures and relationships effectively.

Theory:

1. Object-Oriented Programming (OOP) in Java

1)Java is a widely-used object-oriented programming language that emphasizes the following core
principles:

2)Encapsulation: This principle restricts direct access to an object's data, allowing the internal
representation to be hidden from the outside. It enables control over how data is accessed and
modified.

3)Abstraction: Java allows the creation of abstract classes and interfaces that define common behavior
without exposing complex implementation details.

4)Inheritance: This allows a new class to inherit properties and methods from an existing class,
promoting code reuse and establishing relationships between classes.

5)Polymorphism: This allows methods to perform differently based on the object invoking them,
enhancing flexibility and extensibility.

2. Class Design for Employee and Department in Java

Employee Class:

Explanation:

1)Private Variables: The private modifier ensures that the salary variable cannot be accessed directly
from outside the class, adhering to encapsulation.

2)Constructor: Initializes an employee object with their number, name, and salary.

3)Public Methods: Provide controlled access to the employee's details and allow salary enhancement.

Department Class:

Explanation:

1)Private Variables: The headOfDepartment variable is private to restrict access to the head's details,
ensuring encapsulation.

2)Constructor: Initializes the department with a name and the current head.
3)Public Methods: Provide controlled access to the department’s information and allow changing the
head of the department.

3. Rationale for Design Choices

1)Encapsulation for Data Protection: By making instance variables private, we protect sensitive
information from being manipulated directly, thus ensuring data integrity.

2)Controlled Access via Methods: The methods in both classes provide a safe way to interact with the
class attributes, enforcing rules (e.g., salary increases can only be done through the enhanceSalary
method).

3)Collaboration Between Classes: The Department class has a direct reference to an Employee object,
demonstrating a "has-a" relationship. This allows easy access to employee details while maintaining a
clear structure.

4. Practical Applications of the Design

1)This design is applicable in various real-world scenarios:

2)Human Resource Management Systems: Organizations can maintain employee data, including their
details and salary records, using this design. It can be expanded to include more functionality like
performance tracking.

3)Payroll Systems: The enhanceSalary method can be utilized to implement annual raises based on
performance metrics or inflation adjustments.

4)Departmental Management: The Department class can be expanded to include additional attributes
such as budget, location, or employee lists, allowing comprehensive management of organizational
units.

Conclusion:

The design of the Employee and Department classes in Java showcases the principles of object-oriented
programming, particularly encapsulation and controlled access to data. By organizing the code in this
manner, we create a maintainable and scalable structure that can adapt to the evolving needs of a
software application. This design fosters best practices in software engineering, making it suitable for
real-world applications such as HR management and departmental organization in various business
environments.
// Employee class

class Employee {

private int empNumber;

private String name;

private double salary;

// Constructor

public Employee(int empNumber, String name, double salary) {

this.empNumber = empNumber;

this.name = name;

this.salary = salary;

// Getters

public int getEmpNumber() {

return empNumber;

public String getName() {

return name;

public double getSalary() {

return salary;

// Setter for salary

public void setSalary(double salary) {

this.salary = salary;

}
// Method to give annual salary enhancement

public void annualSalaryEnhancement(double percentage) {

this.salary += this.salary * (percentage / 100);

// Method to display employee details

public void displayEmployeeDetails() {

System.out.println("Employee Number: " + empNumber);

System.out.println("Name: " + name);

System.out.println("Salary: " + salary);

// Department class

class Department {

private String departmentName;

private Employee headOfDepartment;

// Constructor

public Department(String departmentName, Employee headOfDepartment) {

this.departmentName = departmentName;

this.headOfDepartment = headOfDepartment;

// Getters

public String getDepartmentName() {

return departmentName;

public Employee getHeadOfDepartment() {

return headOfDepartment;
}

// Method to change the head of the department

public void changeHeadOfDepartment(Employee newHead) {

this.headOfDepartment = newHead;

// Method to display department details

public void displayDepartmentDetails() {

System.out.println("Department Name: " + departmentName);

System.out.println("Head of Department: " + headOfDepartment.getName());

// Main class to test the implementation

public class Organization {

public static void main(String[] args) {

// Create employee objects

Employee emp1 = new Employee(101, "Alice Smith", 50000);

Employee emp2 = new Employee(102, "Bob Johnson", 55000);

// Display employee details

System.out.println("===== Employee 1 Details =====");

emp1.displayEmployeeDetails();

System.out.println("\n===== Employee 2 Details =====");

emp2.displayEmployeeDetails();

// Create department objects and assign head of department

Department dept1 = new Department("IT", emp1);

Department dept2 = new Department("HR", emp2);


// Display department details

System.out.println("\n===== Department 1 Details =====");

dept1.displayDepartmentDetails();

System.out.println("\n===== Department 2 Details =====");

dept2.displayDepartmentDetails();

// Change head of the IT department

System.out.println("\nChanging head of the IT department to Employee 2...");

dept1.changeHeadOfDepartment(emp2);

// Display department details after head change

System.out.println("\n===== Department 1 Details After Change =====");

dept1.displayDepartmentDetails();

// Apply salary enhancement for Employee 1

System.out.println("\nApplying 10% salary enhancement for Employee 1...");

emp1.annualSalaryEnhancement(10);

// Display updated salary for Employee 1

System.out.println("\n===== Employee 1 Updated Details =====");

emp1.displayEmployeeDetails();

}
EXPERIMENY NO.11
Aim: To study how to design an interface in Java for a Vehicle and implement various vehicle
types such as Bicycle, Car, and Bike.

Theory:
1. Understanding Interfaces in Java

An interface in Java is a reference type that can contain only constants, method signatures,
default methods, static methods, and nested types. Interfaces cannot contain instance fields,
and all methods are implicitly public and abstract unless specified otherwise. They serve as a
contract that classes can implement, ensuring that they provide certain functionalities.

2. Key Concepts of Interfaces

1)Abstraction: Interfaces provide a way to define abstract methods that must be implemented
by any class that implements the interface. This allows for a separation between what a class
can do (its interface) and how it does it (its implementation).

2)Multiple Inheritance: A class can implement multiple interfaces, allowing for more flexible
designs and promoting code reuse.

3)Polymorphism: By using interfaces, different classes can be treated as instances of the


interface type, enabling a unified way to interact with various implementations.

3. Explanation of the Design

Interface Definition:

The Vehicle interface defines common methods that all vehicle types should implement, ensuring a
consistent API across different vehicle classes.

Class Implementation:

Each class (Bicycle, Car, Bike) implements the methods defined in the Vehicle interface in its own way.
This showcases polymorphism, as different classes can behave differently while adhering to the same
interface.

Encapsulation:

Each class has its own private attributes (e.g., type, model, brand), promoting encapsulation and
allowing for controlled access through methods.

Flexibility:
This design allows for easy extension. If a new vehicle type is needed (like Truck), you simply create a
new class that implements the Vehicle interface, ensuring that it follows the same contract.

Conclusion:
The use of interfaces in Java, as illustrated by the Vehicle interface and its implementations,
promotes the principles of abstraction, encapsulation, and polymorphism. This design pattern
fosters a clean, organized structure that enhances code maintainability and scalability. By
adhering to this approach, developers can create flexible applications that can easily adapt to
changing requirements.
Interface Vehicle {

Void accelerate();

Void brake();

Void turn(String direction);

Void displaySpeed();

Class Bicycle implements Vehicle {

Private int speed;

Public void accelerate() {

Speed += 5;

Public void brake() {

Speed -= 5;

Public void turn(String direction) {

System.out.println(“Turning “ + direction);

Public void displaySpeed() {

System.out.println(“Speed: “ + speed);

Class Car implements Vehicle {

Private int speed;

Public void accelerate() {


Speed += 10;

Public void brake() {

Speed -= 10;

Public void turn(String direction) {

System.out.println(“Turning “ + direction);

Public void displaySpeed() {

System.out.println(“Speed: “ + speed);

Class Bike implements Vehicle {

Private int speed;

Public void accelerate() {

Speed += 7;

Public void brake() {

Speed -= 7;

Public void turn(String direction) {

System.out.println(“Turning “ + direction);

Public void displaySpeed() {

System.out.println(“Speed: “ + speed);
}

Public class Veh {

Public static void main(String[] args) {

Vehicle bicycle = new Bicycle();

Bicycle.accelerate();

Bicycle.displaySpeed();

Bicycle.turn(“left”);

Vehicle car = new Car();

Car.accelerate();

Car.displaySpeed();

Car.turn(“right”);

Vehicle bike = new Bike();

Bike.accelerate();

Bike.displaySpeed();

Bike.turn(“left”);

}
Experiment No : 13
Name of Experiment: Write a program to create GUI application without
event handling.
Aim: Program to create GUI using different AWT controls.
Theory:
JAVA provides a rich set of libraries to create Graphical User Interface in platform
independent way. In this article we'll look in AWT (Abstract Window Toolkit).
Graphical User Interface:
Graphical User Interface (GUI) offers user interaction via some graphical components. For
example our underlying Operating System also offers GUI via window,frame,Panel, Button,
Textfield, TextArea, Listbox, Combobox, Label, Checkbox etc. These all are known as
components. Using these components we can create an interactive user interface for an
application.
GUI provides result to end user in response to raised events.GUI is entirely based events. For
example clicking over a button, closing a window, opening a window, typing something in a
textarea etc. These activities are known as events.GUI makes it easier for the end user to use
an application. It also makes them interesting.
Basic Terminologies :
Term Description

Component Component is an object having a graphical representation displayed


on the screen and that can interact with the user. For examples
buttons, checkboxes, list and scrollbars of a graphical user interface.

Container Container object is a component that can contain other


components.Components added to a container are tracked in a list.
The order of the list will define the components' front-to-back
stacking order within the container. If no index is specified when
Panel adding component to a container, it will be added to the end of the list.
Panel provides space in which an application can attach any other
components,including other panels.

Window Window is a rectangular area which is displayed on the screen. In different


window we can execute different program and display different data.
Window provide us with multitasking environment. A window must have
either a frame, dialog, or another window defined as its owner when it's
constructed.

Frame A Frame is a top-level window with a title and a border. The size of the
frame includes any area designated for the border. Frame encapsulates
window. It and has a title bar, menu bar, borders, and resizing corners.

Canvas Canvas component represents a blank rectangular area of the screen onto
which the application can draw. Application can also trap input events from
the use from that blank area of Canvas component.

AWT UI Elements:
Following is the list of commonly used controls while designed GUI using AWT.

 Label :A Label object is a component for placing text in a container.


 Button :This class creates a labeled button.
 Check Box :A check box is a graphical component that can be in either an on or off state.
 Check Box Group : The CheckboxGroup class is used to group the set of checkbox.
 List : The List component presents the user with a scrolling list of text items.
 Text Field : A TextField object is a text component that allows for the editing of a single
line of text.
 Text Area : A TextArea object is a text component that allows for the editing of a
multiple lines of text.
 Choice : A Choice control is used to show pop up menu of choices. Selected choice is
shown on the top of the menu.
 Canvas : A Canvas control represents a rectangular area where application can draw
something or can receive inputs created by user.
 Image : An Image control is superclass for all image classes representing graphical
images.
 Scroll Bar : A Scrollbar control represents a scroll bar component in order to enable user
to select from range of values.
 Dialog : A Dialog control represents a top-level window with a title and a border used to
take some form of input from the user.
 File Dialog : a FileDialog control represents a dialog window from which the user can
select a file.

Conclusion: Thus, we have studied different controls provided by AWT.


import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class LoginDemo extends JFrame implements Ac onListener {

JPanel panel;

JLabel user_label, password_label, message;

JTextField userName_text;

JPasswordField password_text;

JBu on submit, cancel;

LoginDemo() {

user_label = new JLabel();

user_label.setText("User Name :");

userName_text = new JTextField();

password_label = new JLabel();

password_label.setText("Password :");

password_text = new JPasswordField();

submit = new JBu on("SUBMIT");

panel = new JPanel(new GridLayout(3, 1));

panel.add(user_label);

panel.add(userName_text);

panel.add(password_label);

panel.add(password_text);

message = new JLabel();

panel.add(message);

panel.add(submit);

setDefaultCloseOpera on(JFrame.EXIT_ON_CLOSE);

submit.addAc onListener(this);

add(panel, BorderLayout.CENTER);

setTitle("Please Login Here !");


setSize(450,350);

setVisible(true);

public sta c void main(String[] args) {

new LoginDemo();

@Override

public void ac onPerformed(Ac onEvent ae) {

String userName = userName_text.getText();

String password = password_text.getText();

if (userName.trim().equals("bhishek2569") && password.trim().equals("2569")) {

message.setText(" Hello " + userName + "");

} else {

message.setText(" Invalid user.. ");

OUTPUT:
EXPERIMENT NO. 13

Aim : Java Program to Create Account with 1000 Rs Minimum Balance, Deposit Amount, Withdraw Amount and
Also Throws LessBaIanceException. It has a Class Called LessBaIanceException Which returns the Statement
that Says WithDraw Amount(_Rs) is Not Valid. It has a Class Which Creates 2 Accounts, Both Account Deposite
Money and One Account Tries to WithDraw more Money Which Generates a LessBalanceException Take
Appropriate Action for the Same

In Java, exceptions are a fundamental concept used to handle runtime errors and exceptional situations in code.
Here's a brief overview of the theory behind exceptions in Java:

1 . Exception Hierarchy: Exceptions in Java are represented as objects in a class hierarchy. The 'Throwable' class
is at the top of this hierarchy. It has two main subclasses: 'Error' and 'Exceptiorf. is typically reserved for serious
errors that are beyond the control of the application, such as system failures. 'Exception' is further divided into
checked exceptions and unchecked exceptions.

2.Checked Exceptions: Checked exceptions are exceptions that must be either caught using a 'try-catch' block or
declared in the method's signature using the 'throws' keyword. Examples of checked exceptions include
IOException and SQLException. These exceptions are usually related to external factors like file I/O or database
connections.

3.Unchecked Exceptions: Unchecked exceptions, also known as runtime exceptions, are not required to be caught
or declared. They typically result from programming errors, such as dividing by zero (ArithmeticException) or
accessing an array element out of bounds (ArraylndexOutOfBoundsException).

4.try-catch Blocks:To handle exceptions, you can use 'try-catch' blocks. Code that might throw an exception is
placed inside the block, and you specify how to handle the exception in the block. This allows your program to
gracefully recover from errors.

"java try
{
// Code that might throw an exception
} catch (ExceptionType e) {
// Handle the exception

5. finally Block: You can also include a •finallyn block after the •catch• block. Code within the 'finally' block is
executed whether an exception occurs or not. It's often used for cleanup tasks like closing resources.

try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Handle the exception
} finally {
//cleanup code
}

6.Custom Exceptions: In addition to built-in exceptions, you can create custom exception classes by extending
the exception class or its subclasses. This allows you to define and throw exceptions specific to your application.

class CustomException extends Exception {


//constructor and additional method

7.Throwing Exceptions:You can use the 'throw' keyword to manually throw an exception when a specific
condition is met in your code.

If(some condition){

Throw new customException(“This is a custom exception”);

Conclusion : Understanding and effectively using exceptions in Java is essential for writing robust and reliable
software. They help handle unexpected situations and provide a structured way to manage errors in your code.
// Custom Exception Class

class LessBalanceException extends Exception {

public LessBalanceException(String message) {

super(message);

// Account Class

class Account {

private String accountHolder;

private double balance;

private static final double MINIMUM_BALANCE = 1000.0;

// Constructor to initialize the account with a minimum balance

public Account(String accountHolder, double initialDeposit) throws LessBalanceException {

this.accountHolder = accountHolder;

if (initialDeposit < MINIMUM_BALANCE) {

throw new LessBalanceException("Initial deposit must be at least Rs " +


MINIMUM_BALANCE);

this.balance = initialDeposit;

// Method to deposit amount

public void deposit(double amount) {

balance += amount;

System.out.println("Deposited Rs " + amount + ". Current balance: Rs " + balance);

// Method to withdraw amount

public void withdraw(double amount) throws LessBalanceException {


if (balance - amount < MINIMUM_BALANCE) {

throw new LessBalanceException("Withdrawal of Rs " + amount + " is not valid. Minimum


balance of Rs " + MINIMUM_BALANCE + " must be maintained.");

} else {

balance -= amount;

System.out.println("Withdrew Rs " + amount + ". Current balance: Rs " + balance);

// Method to display the account balance

public double getBalance() {

return balance;

// Main class with the program logic

public class BankApplication {

public static void main(String[] args) {

try {

// Create two accounts

Account account1 = new Account("Alice", 5000); // Valid account with Rs 5000 deposit

Account account2 = new Account("Bob", 3000); // Valid account with Rs 3000 deposit

// Deposit some money

account1.deposit(2000); // Alice deposits Rs 2000

account2.deposit(1000); // Bob deposits Rs 1000

// Attempt to withdraw money

account1.withdraw(2500); // Valid withdrawal for Alice

account2.withdraw(2500); // Bob tries to withdraw Rs 2500, which will throw an exception


} catch (LessBalanceException e) {

System.out.println(e.getMessage()); // Catch the exception and display the error message

OUTPUT:
Experiment No.: 11
Name of Experiment: Write a program to study the concept of multithreading.
Aim: Study the concept of multithreading
Requirements: JDK 1.7/8
Theory:
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
1]Extending the Thread class
2]Implementing the Runnable Interface
In a thread-based multitasking environment, the thread is the smallest unit of dispatchable
code. This means that a single program can perform two or more tasks at once. The principal
advantage of multithreading is that it enables you to write very efficient programs because it
lets you utilize the idle time that is present in most programs. A thread can be in one of
several states. It can be running. It can be ready to run as soon as it gets CPU time. A running
thread can be suspended. A thread can be terminated, in which case
its execution ends and cannot be resumed. Along with thread-based multitasking comes the
need for a special type of feature called synchronization, which allows the execution of
threads to be coordinated in certain well-defined ways. Java has a complete subsystem
devoted to synchronization, and its key features are also described here.
Advantages of Java Multithreading:
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
The Thread Class and Runnable Interface:
Java’s multithreading system is built upon the Thread class and its companion interface,
Runnable. Thread encapsulates a thread of execution. To create a new thread, your program
will either extend Thread or implement the Runnable interface. The Thread class defines
several methods that help manage threads. Here are some of the more commonly used ones
(we will be looking at these more closely as they are used):
Method Meaning
final String getName( ) Obtains a thread’s name.
final int getPriority( ) Obtains a thread’s priority.
final void setPriority(int level) set the thread priority.
final boolean isAlive( ) Determines whether a thread is still running.
final void join( ) Waits for a thread to terminate.
void run( ) Entry point for the thread.
static void sleep(long milliseconds) Suspends a thread for a specified period of milliseconds.
void start( ) Starts a thread by calling its run( ) method.

All processes have at least one thread of execution, which is usually called the main thread,
because it is the one that is executed when your program begins. Thus, the main thread is the
thread that all of the preceding example programs in the book have been using. From the
main thread, you can create other threads.
Creating a Thread:
You create a thread by instantiating an object of type Thread. The Thread class encapsulates
an object that is runnable. As mentioned, Java defines two ways in which you can create a
runnable object:
• .You can implement the Runnable interface.
• .You can extend the Thread class.
Thread defines several constructors. The one that we will use first is shown here:
Thread(Runnable threadOb)
In this constructor, threadOb is an instance of a class that implements the Runnable interface.
This defines where execution of the thread will begin.

Conclusion: Thus, we have studied about concept of thread and how to


implements threads in java.
class NumberPrinter {

private int number = 1; // Star ng number is 1

private final int MAX = 10; // Maximum number to print

// Method to print odd numbers

public synchronized void printOdd() {

while (number <= MAX) {

if (number % 2 == 0) { // If the number is even, wait

try {

wait();

} catch (InterruptedExcep on e) {

e.printStackTrace();

} else {

// Print the odd number and increment

System.out.println(Thread.currentThread().getName() + ": " + number);

number++;

no fy(); // No fy the other thread (even thread) to proceed

// Method to print even numbers

public synchronized void printEven() {

while (number <= MAX) {

if (number % 2 != 0) { // If the number is odd, wait

try {

wait();

} catch (InterruptedExcep on e) {
e.printStackTrace();

} else {

// Print the even number and increment

System.out.println(Thread.currentThread().getName() + ": " + number);

number++;

no fy(); // No fy the other thread (odd thread) to proceed

// Main class that runs the threads

public class EvenOddThreadExample {

public sta c void main(String[] args) {

NumberPrinter numberPrinter = new NumberPrinter();

// Create the thread to print odd numbers

Thread oddThread = new Thread(new Runnable() {

@Override

public void run() {

numberPrinter.printOdd();

}, "Odd Thread");

// Create the thread to print even numbers

Thread evenThread = new Thread(new Runnable() {

@Override

public void run() {


numberPrinter.printEven();

}, "Even Thread");

// Start both threads

oddThread.start();

evenThread.start();

OUTPUT:
EXPERIMENT NO.15
Aim: To study theoretical concepts related to file handling, string manipulation, and filtering based on
file extensions, particularly focusing on the example you provided for identifying Java files.

Theory:

Overview of File Handling in Programming

File handling is an essential aspect of programming that involves creating, reading, writing, and
managing files within a file system. In many programming languages, including Java, file handling allows
developers to interact with the file system and perform operations on files.

Key Concepts

1.File Systems:

A file system organizes how data is stored and retrieved on a storage device. Each file has attributes,
including its name, size, type, and location within the directory structure.

2.File Types:

Files can be categorized based on their content or purpose, such as text files, image files, executable
files, and source code files (like Java files).File types are often indicated by their extensions, which are
suffixes added to filenames (e.g., .txt, .pdf, .java).

3.File Extensions:

A file extension helps the operating system and applications determine how to handle a file. For
instance, files ending in .java are recognized as Java source files and can be compiled and executed by
the Java runtime.

String Manipulation

In many programming tasks, including filtering filenames, string manipulation plays a crucial role. Here
are some key operations:

1.Substring:

A substring is a portion of a string. In this case, we can check the last few characters of a filename to
determine its type.

2.Length:

The length of a string can be determined using methods like length() to understand how many
characters it contains.

3.Comparison:

Comparing strings (e.g., checking if a string ends with a particular substring) can help filter data based on
specific criteria.

Filtering Java Files

To filter a list of filenames and select those that are Java files, we can follow a systematic approach:

1.Input List: Begin with a list of filenames (e.g., test.java, ABC.doc, etc.).

2.Define Criteria: A file is identified as a Java file if its name ends with the .java extension. This can be
checked using string methods.

3.Iterate Through Filenames: Loop through each filename in the list and apply the filtering criteria.

4.Store Results: For each filename that meets the criteria, store it in a new list.

Advantages of This Approach

1.Simplicity: The method is straightforward and easy to understand, making it maintainable and
adaptable for other file types.

2.Efficiency: The linear scan through the list ensures that each filename is checked only once, making it
efficient for small to moderately sized lists.

3.Flexibility: The code can be easily modified to filter other types of files by changing the criteria in the
filtering method.

Conclusion:

Filtering filenames based on their extensions is a common task in software development, particularly in
environments where files are managed and processed programmatically. Understanding file handling,
string manipulation, and basic filtering techniques enables developers to effectively manage file systems
and data. This approach is fundamental to many applications, from simple scripts to complex software
systems, ensuring that only relevant files are processed based on predefined criteria.
import java.u l.ArrayList;

import java.u l.List;

public class JavaFileSelector {

public sta c void main(String[] args) {

// Input list of file names

String[] files = {"test.java", "ABC.doc", "Demo.pdf", "add.java", "factorial.java", "sum.txt"};

// List to store Java files

List<String> javaFiles = new ArrayList<>();

// Iterate over the list of file names

for (String file : files) {

// Check if the file name ends with ".java"

if (file.endsWith(".java")) {

javaFiles.add(file);

// Print the Java files

System.out.println("Java files are:");

for (String javaFile : javaFiles) {

System.out.println(javaFile);

}
OUTPUT:

You might also like