Java 8 To 15
Java 8 To 15
Scanner;
import java.util.Vector;
int n = scanner.nextInt();
stringVector.add(str);
stringVector.remove(newString);
System.out.println("String '" + newString + "' was present and has been removed.");
} else {
stringVector.add(newString);
System.out.println("String '" + newString + "' was not present and has been added.");
}
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;
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;
this.name = name;
this.department = department;
this.age = age;
String specialization;
this.specialization = specialization;
}
// Override displayInfo method to include specialization
@Override
super.displayInfo();
System.out.println("Designation: Professor");
String researchArea;
this.researchArea = researchArea;
@Override
super.displayInfo();
int yearsOfExperience;
// Constructor for Assistant_Professor class
this.yearsOfExperience = yearsOfExperience;
@Override
super.displayInfo();
Professor professor = new Professor("Dr. John Smith", "Computer Science", 50, "Artificial
Intelligence");
professor.displayInfo();
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)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.
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.
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.
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 {
// Constructor
this.empNumber = empNumber;
this.name = name;
this.salary = salary;
// Getters
return empNumber;
return name;
return salary;
this.salary = salary;
}
// Method to give annual salary enhancement
// Department class
class Department {
// Constructor
this.departmentName = departmentName;
this.headOfDepartment = headOfDepartment;
// Getters
return departmentName;
return headOfDepartment;
}
this.headOfDepartment = newHead;
emp1.displayEmployeeDetails();
emp2.displayEmployeeDetails();
dept1.displayDepartmentDetails();
dept2.displayDepartmentDetails();
dept1.changeHeadOfDepartment(emp2);
dept1.displayDepartmentDetails();
emp1.annualSalaryEnhancement(10);
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.
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.
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 displaySpeed();
Speed += 5;
Speed -= 5;
System.out.println(“Turning “ + direction);
System.out.println(“Speed: “ + speed);
Speed -= 10;
System.out.println(“Turning “ + direction);
System.out.println(“Speed: “ + speed);
Speed += 7;
Speed -= 7;
System.out.println(“Turning “ + direction);
System.out.println(“Speed: “ + speed);
}
Bicycle.accelerate();
Bicycle.displaySpeed();
Bicycle.turn(“left”);
Car.accelerate();
Car.displaySpeed();
Car.turn(“right”);
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
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.
import java.awt.event.*;
import javax.swing.*;
JPanel panel;
JTextField userName_text;
JPasswordField password_text;
LoginDemo() {
password_label.setText("Password :");
panel.add(user_label);
panel.add(userName_text);
panel.add(password_label);
panel.add(password_text);
panel.add(message);
panel.add(submit);
setDefaultCloseOpera on(JFrame.EXIT_ON_CLOSE);
submit.addAc onListener(this);
add(panel, BorderLayout.CENTER);
setVisible(true);
new LoginDemo();
@Override
} else {
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.
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){
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
super(message);
// Account Class
class Account {
this.accountHolder = accountHolder;
this.balance = initialDeposit;
balance += amount;
} else {
balance -= amount;
return balance;
try {
Account account1 = new Account("Alice", 5000); // Valid account with Rs 5000 deposit
Account account2 = new Account("Bob", 3000); // Valid account with Rs 3000 deposit
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.
try {
wait();
} catch (InterruptedExcep on e) {
e.printStackTrace();
} else {
number++;
try {
wait();
} catch (InterruptedExcep on e) {
e.printStackTrace();
} else {
number++;
@Override
numberPrinter.printOdd();
}, "Odd Thread");
@Override
}, "Even Thread");
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:
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.
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.
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;
if (file.endsWith(".java")) {
javaFiles.add(file);
System.out.println(javaFile);
}
OUTPUT: