0% found this document useful (0 votes)
6 views65 pages

1726532641-Object Oriented Programming Lab Manual

The document is a laboratory manual for the Object Oriented Programming course (CS 4191) at NIIT University for the academic year 2023-24. It outlines the vision, mission, program outcomes, specific outcomes, educational objectives, general laboratory instructions, course description, and evaluation criteria, as well as detailed course content and practical exercises. The manual emphasizes the importance of hands-on experience and prepares students for industry demands in computer science and engineering.

Uploaded by

Simarpreet singh
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)
6 views65 pages

1726532641-Object Oriented Programming Lab Manual

The document is a laboratory manual for the Object Oriented Programming course (CS 4191) at NIIT University for the academic year 2023-24. It outlines the vision, mission, program outcomes, specific outcomes, educational objectives, general laboratory instructions, course description, and evaluation criteria, as well as detailed course content and practical exercises. The manual emphasizes the importance of hands-on experience and prepares students for industry demands in computer science and engineering.

Uploaded by

Simarpreet singh
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/ 65

OBJECT ORIENTED PROGRAMMING (CS 4191)

LABORATORY MANUAL

B.Tech. (CSE/iMSc/ECE/DS/CYS)
Semester I
L-T-P-C: 2-0-4-4

Academic Year: 2023-24

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

NIIT UNIVERSITY, NEEMRANA


NH-8, Delhi-Jaipur Highway,
Neemrana, District Alwar (Rajasthan),
Pin-301705
Website: www.niituniversity.in
VISION OF THE UNIVERSITY

To be the role model of learning, research, innovation, and sustainability for the knowledge society.

MISSION OF THE UNIVERSITY


1. To deliver distinctive education through the pioneering use of technology.
2. To develop superior talent through partnerships with industry and society.
3. To promote research, discovery, and entrepreneurship through collaborative action.
4. To build responsible citizens of the world by instilling a culture of seamlessness in all facets
of life.

VISION OF THE DEPARTMENT

NIIT University emerged from the visionary aspirations of esteemed intellectuals who sought to
revolutionize the Indian education system, with a focus on cultivating original thinkers, innovative
problem solvers, and inspiring leaders. Their goal was to foster a dynamic and intellectually
stimulating learning environment that seamlessly blends academic theories with real-life
experiences. NU's Computer Science and Engineering (CSE) programmes (Undergraduate,
Postgraduate, and PhD) are designed to provide a comprehensive understanding of the foundational
principles of computing and equip students with the necessary engineering skills for designing,
implementing, and utilizing computer systems. This course offers a holistic perspective on the field
of computing, encompassing the concepts, principles, and practical applications, allowing students
to gain both theoretical knowledge and hands-on experience. By enrolling in our CSE program,
students will embark on a journey that not only acquaints them with the intricacies of computing
but also nurtures their ability to apply and extend these concepts. Our curriculum is carefully crafted
to ensure that students develop a well-rounded skill set, encompassing theoretical understanding,
practical skills, and the capacity to apply these principles in real-world scenarios.

MISSION OF THE DEPARTMENT


The area of Computer Science and Engineering at NIIT University is dedicated to fulfilling the
following mission:
M1: Providing the ideal environment for students to become industry-ready professionals,
researchers, and entrepreneurs. We achieve this by offering courses on cutting-edge technology and
advanced laboratory courses, ensuring that our students are well-equipped with the knowledge and
skills demanded by the industry.

CS251 Object Oriented Programming


M2: Establishing Centres of Excellence that foster a conducive environment for our faculty to
engage in progressive and convergent research themes. Through these centers, we aim to train our
students in the latest advancements and emerging technologies, ensuring that they stay at the
forefront of the field.
M3: Imparting high-quality experiential learning to our students, enabling them to gain expertise in
modern software tools and cater to the real-time requirements of the industry. We focus on providing
practical knowledge and hands-on experience to ensure our students are well-prepared for their
professional careers.
M4: Instilling problem-solving and team-building skills among our students, emphasizing the
importance of lifelong learning, and nurturing a sense of societal and ethical responsibilities. We
believe in creating well-rounded professionals who are not only skilled in their domain but also
possess the necessary attributes to make a positive impact on society.
M5: Offering continuing education programs in emerging areas of computer science, such as
cybersecurity, data science, machine learning, and cloud computing. These programs are designed
to provide ongoing learning opportunities for our stakeholders, including professionals already
working in the industry, ensuring that they stay updated with the latest advancements.
At NIIT University, we are committed to providing a comprehensive and holistic learning
experience to our students, empowering them to excel in their chosen fields and make significant
contributions to the ever-evolving world of computer science and engineering.

PROGRAM OVERVIEW

The Computer Science and Engineering at NIIT University seems to have a strong focus on
providing quality education and preparing students for practical challenges in the field. This
approach is valuable in ensuring that students are equipped with the necessary skills and knowledge
to contribute to fundamental research in computer science and engineering. By emphasizing real-
world challenges, the area likely provides a curriculum that integrates theoretical knowledge with
hands-on experience, preparing students for the demands of the industry. The University is actively
seeking out students with a passion for innovation and a drive to contribute to the field. This
approach can foster an environment that encourages creativity, problem-solving, and critical
thinking, which are all essential qualities for success in computer science and engineering.

CS251 Object Oriented Programming


PROGRAM OUTCOMES (POs)
PO1: Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering problems.

PO2: Problem Analysis: Identify, formulate, research literature, and analyze complex engineering
problems reaching substantiated conclusions using the first principles of mathematics, natural
sciences, and engineering sciences.

PO3: Design/Development of Solutions: Design solutions for complex engineering problems and
system components or processes that meet the specified needs with appropriate consideration for
the public health and safety, and the cultural, society, and environmental considerations.

PO4: Conduct Investigations of Complex Problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions.

PO5: Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.

PO6: The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.

PO7: Environment and Sustainability: Understand the impact of the professional engineering
solutions in society and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.

PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

PO9: Individual and Team Work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multi-disciplinary settings.

PO10: Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.

PO11: Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and leader
in a team, to manage projects and in multi-disciplinary environments.

PO12: Life-long Learning: Recognize the need for and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.

CS251 Object Oriented Programming


PROGRAM SPECIFIC OUTCOMES (PSOs)

PSO 1: Ability to apply the knowledge of basic and advanced concepts of Computer
Science in order to address compelling problems of society and provide an acceptable
and practical solution.

PSO 2: Ability to understand the mathematical background to solve computational


tasks and model solutions to real-life problems.

PSO 3: Ability to understand state-of-the-art research problems and identify the


research gaps so as to provide innovative and effective methods to fill-up those gaps.

PSO 4: Use new technical advancements of Computer Science to produce


appreciable contributions in the profession.

PSO 5: Ability to analyze a complex computing problem and to apply principles of


computing and other relevant disciplines to identify solutions.

PSO 6: Ability to model data and design the system architecture of high-performance
and tolerant systems.

PSO 7: Ability to formulate learning solutions for process-centric systems.

PSO 8: Ability to achieve a successful career in Industry, in Research Institute, in


Academics, and in Entrepreneurship.

PSO 9: Ability to publish technical papers in reputed journals and conferences under
the guidance of dedicated faculty members.

PSO 10: Ability to get involved in innovative, industry-relevant projects jointly with
world class engineers in Collaborative Education mode which will provide an
environment to convert their innovation into reality.

PSO 11: Develop expertise in specialized areas like Data Science, Artificial
Intelligence, Cyber Security, Cloud Computing and Big data Engineering.

PSO 12: Ability to seamlessly become industry professional after six months
Industry Practice in Industry Environment in the final academic year.

CS251 Object Oriented Programming


PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

PEO 1: The Computer Science and Engineering program at NIIT University is designed to
empower graduates with the skills and knowledge necessary to achieve the following educational
objectives.

PEO 2: Thrive as proficient computer professionals: Our graduates will be equipped to work
productively as successful computer professionals in a diverse range of career paths. Whether in
supportive or leadership roles within multidisciplinary teams, they will possess the competence to
contribute effectively. Additionally, they will have the option to pursue higher studies to further
enhance their expertise in the field.

PEO 3: Demonstrate effective communication and ethical conduct: We emphasize the development
of excellent communication skills among our graduates, enabling them to effectively convey ideas
and solutions.

PEO 4: CSE program instills a strong awareness of societal needs and constraints, empowering
graduates to incorporate these considerations into their professional endeavors. With a high regard
for ethical responsibilities, they will contribute to the betterment of society through their practice.

PEO 5: Embrace lifelong learning for personal and organizational growth: Our program encourages
graduates to engage in lifelong learning, ensuring they remain up-to-date in their profession. By
nurturing a mindset of continuous growth, they will adapt to evolving technologies and industry
trends, fostering personal development and contributing to the growth of the organizations they
join. Through their commitment to ongoing learning, our graduates will stay at the forefront of the
field.

CS251 Object Oriented Programming


GENERAL LABORATORY INSTRUCTIONS

1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time),
those who come after 5 minutes will not be allowed into the lab.

2. Plan your task properly before the commencement, come prepared to the lab with the synopsis/
program/experiment details.

3. Students should enter the laboratory with:


a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any)
needed in the lab.
c. Proper Dress code and Identity card.

4. Execute your task in the laboratory, record the results/output, and get certified by the concerned
faculty.

5. All the students should be polite and cooperative with the laboratory staff, and must maintain
discipline and decency in the laboratory.

6. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment and misbehavior with the staff will attract severe punishment.

7. Students must get the permission of the faculty in case of any urgency to go out; if anybody is
found outside the lab/class without permission during working hours will be treated seriously and
punished appropriately.

8. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab
after completing the task (experiment) in all aspects. He/she must ensure the system/seat is kept
properly.

CS251 Object Oriented Programming


COURSE DESCRIPTION

By empowering students with the skills necessary to access, understand and evaluate Information,
Capstone Project will support students in the achievement of 21st century learning expectations.
Students work in teams to develop or implement a real world IT solution

COURSE OUTCOMES

S.No. Description
Identify classes, objects, members, methods of a class and relationships among them
CO1
needed for a specific problem
CO2 Demonstrate the concepts of polymorphism and inheritance and reusability
Relate Java programs to implement error handling techniques using exception
CO3
handling
CO4 Compare Multithreaded programming with ordinary programming models
CO5 Design and Develop applications which connects with database using JDBC

CS251 Object Oriented Programming


EVALUATION CRITERIA

Exam Component Marks

Mid Term 1 Practical 10


Mid Term 2 Practical 10

FACULTY DETAILS

Course In charge: Prof. Manish Hurkat (manish.hurkat@niituniversity.in)

COURSE CONTENTS

1. Introduction to OOP concepts, Overview of Java, Features of Java


2. Data types, Operators and their precedence ordering, Input and Output, Simple programs,
Programming errors
3. Control Structures, Arrays, Wrapper classes and ArrayList
4. Encapsulation, Classes and Constructors, Constructors and their Overloading
5. Methods, Static overloading, the Scanner Class, Formatted output
6. String, StringBuffer and StringBuilder classes, Command-line arguments
7. Inheritance concepts, Method overriding, Polymorphism, Abstract Classes, Interfaces
8. Exception-handling Fundamentals
9. Collection and Generics
10. Databases Connecting in Java
11. File Handling in Java, Input and Output Streams
12. Networks, Clients and Servers, Writing a simple Client
13. Java Threads, Writing a simple Server

CS251 Object Oriented Programming


List of Experiments

Practical No. Aim of Practical COs Page No.


1 Data types CO1 11
2 Classes, Constructors and Method Overloading CO1 13
3 Arrays CO1 17
4 Strings CO2 25
5 Inheritance concepts CO2 35
6 Method overriding CO2 41
7 Exception-handling Fundamentals CO3 43
8 Collection & Generics CO3 47
9 Event-handling CO3 51
10 JDBC CO5 53
11 Clients & Servers CO4 59
12 Java Threads CO4 61

CS251 Object Oriented Programming


Practical 1: Data Types:

Exercise 1: Assign values to variables in Java


First, use the class DeclareDatatype that is provided below,

public class DeclareDatatype {


public static void main(String[] args) {
// Enter your code here
}
}

Secondly, declare and assign variables of the following different data types.

• Declare a variable named value_int of the data type int that is assigned the value 20
• Secondly, declare a variable named value_string of the data type string that is assigned the value
“Java”
• Third, create a variable named value_double of the data type double that is assigned the value
23.63
• Finally, print all variables in the console.

To create a new variable in Java,

• First specify the data type followed by the variable name


• Then assign the value equal to the “=” operator
• Don’t forget the semicolon at the end

public class DeclareDatatype {


public static void main(String[] args) {
// Assigns the value 20 to the variable value_int of type int
int value_int = 20;
// Assigns the value "Java" to value_string
String value_string = "Java";
// Assigns the value 23.63 to the value type double value_double
double value_double = 23.63;

CS251 Object Oriented Programming


// Print the variables
System.out.println(value_int);
System.out.println(value_string);
System.out.println(value_double);
}
}

Resulting in,

20
Java
23.63

Exercise 2: Assign values to variables and convert data type


Similarly, use the class DeclareDatatype that is provided below,

public class DeclareDatatype {


public static void main(String[] args) {
// Enter your code here
}
}

First,

• Declare a variable named value of the data type int that is assigned the value 50
• Secondly, declare a variable named another_value of the data type double that is assigned the
value 30.2

Secondly,

• Convert the variable value from data type int to data type double. Save the new variable to a new
variable value_double

Finally,

• Add the variable value and another_value and assign the value to a new variable which is
assigned the name sum_value of type double.
• Print the result

CS251 Object Oriented Programming


• We easily create variables by first specifying the data type, followed by the variable name and the
value we want to assign to the variable.
• We can convert an int to a double by creating a new variable of the data type double.
• Summing up is easy with the plus operator +

public class DeclareDatatype {


public static void main(String[] args) {
//First, declaring the variables
int value = 50;
double another_value = 30.2;
// Convert the variable value to a double
double value_double = value;
// Finally, Sum the variables
double sum_value = value_double + another_value;
// Print the result
System.out.println(sum_value);
}
}

Practical 2: Classes, Constructors and Method Overloading:

Write a Java program to create a class called "Person" with a name and age attribute. Create two
instances of the "Person" class, set their attributes using the constructor, and print their name and
age.

Sample Solution:

Java Code:

// Person.java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;

CS251 Object Oriented Programming


}
public int getAge() {
return age;
}
}

The above class has two private attributes: name and age, and a constructor that initializes these
attributes with the values passed as arguments. It also has a getter method to access the attributes.

// Main.java
public class Main {
public static void main(String[] args) {
Person person1 = new Person("Ean Craig", 11);
Person person2 = new Person("Evan Ross", 12);
System.out.println(person1.getName() + " is " + person1.getAge() + " years old.");
System.out.println(person2.getName() + " is " + person2.getAge() + " years old.\n");
}
}

In the above example, we create two instances of the "Person" class, set their attributes with the
constructor, and print their name and age using the getter methods. We also modify the attributes
using the setter methods and print the updated values.

Sample Output:

Ean Craig is 11 years old.


Evan Ross is 12 years old.

Set new age and name:


Ean Craig is now 14 years old.
Lewis Jordan is now 12 years old.

Write a Java program to create a class called "Rectangle" with width and height attributes.
Calculate the area and perimeter of the rectangle.

Sample Solution:

Java Code:

//Rectangle.java
public class Rectangle {
private double width;
private double height;

public Rectangle(double width, double height) {


this.width = width;
this.height = height;

CS251 Object Oriented Programming


}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
}

The above class has two private attributes: ‘width’ and ‘height’, a constructor that initializes these
attributes with the values passed as arguments, and getter and setter methods to access and modify
these attributes. It also has two methods ‘getArea()’ and ‘getPerimeter() ‘ to calculate the area and
perimeter of the rectangle.

//Main.java
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(7, 12);

System.out.println("The area of the rectangle is " + rectangle.getArea());


System.out.println("The perimeter of the rectangle is " + rectangle.getPerimeter());

rectangle.setWidth(6);
rectangle.setHeight(12);

System.out.println("\nThe area of the rectangle is now " + rectangle.getArea());


System.out.println("The perimeter of the rectangle is now " + rectangle.getPerimeter());
}
}

In the Main() function we create an instance of the "Rectangle" class with a width of 7 and a
height of 12, and call its methods to calculate the area and perimeter. We then modify the width
and height using the setter methods and print the updated rectangle area and perimeter.

Sample Output:

The area of the rectangle is 84.0


The perimeter of the rectangle is 38.0

The area of the rectangle is now 72.0

CS251 Object Oriented Programming


The perimeter of the rectangle is now 36.0

Write a Java program to demonstrate method overloading with two methods having
different data types

This Java code demonstrates method overloading, a feature that allows a class to have multiple
methods with the same name but different parameters. In this example, the OverloadExample
class has two print methods, each accepting a different type of parameter: one for int and one for
double.

• OverloadExample class: This is a class definition named OverloadExample.


• print(int num) method: This method takes an integer parameter num and prints "Integer : "
followed by the value of num.
• print(double num) method: This method takes a double parameter num and prints "Double : "
followed by the value of num.
• main method: This is the entry point of the program. It creates an instance of the
OverloadExample class named obj. Then it calls the print method twice, once with an integer
argument 18 and once with a double argument 84.44.

Source Code
class OverloadExample
{
void print(int num)
{
System.out.println("Integer : " + num);
}

void print(double num)


{
System.out.println("Double : " + num);
}

public static void main(String[] args)


{
OverloadExample obj = new OverloadExample();
obj.print(18);
obj.print(84.44);
}
}

Output
Integer : 18
Double : 84.44

Create a Java program to demonstrate method overloading with two methods having
different numbers of parameters

• Class Definition: The class MathOperations is defined.

CS251 Object Oriented Programming


• Method Overloading: In this class, there are two methods named add, but they differ in their
parameter lists. This is called method overloading. Java allows method overloading, where you
can have multiple methods with the same name but different parameters.
o The first add method takes two integer parameters a and b and returns the sum of these
two numbers.
o The second add method takes three integer parameters a, b, and c and returns the sum of
these three numbers.
• Main Method: The main method is the entry point of the program.
• Object Creation: An object math of the class MathOperations is created.
• Method Calls: Two method calls are made:
o math.add(7, 3): This calls the first add method with two integer parameters 7 and 3. The
result (sum of 7 and 3) is printed.
o math.add(5, 9, 3): This calls the second add method with three integer parameters 5, 9,
and 3. The result (sum of 5, 9, and 3) is printed.

Source Code
class MathOperations
{
int add(int a, int b)
{
return a + b;
}

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


{
return a + b + c;
}

public static void main(String[] args)


{
MathOperations math = new MathOperations();
System.out.println("Sum of Two Numbers : " + math.add(7, 3));
System.out.println("Sum of Three Numbers : " + math.add(5, 9, 3));
}
}

Output
Sum of Two Numbers : 10
Sum of Three Numbers : 17

Practical 3: Arrays :

Write a Java program to sort a numeric array and a string array.

Pictorial Presentation:

CS251 Object Oriented Programming


Sample Solution:

Java Code:

// Import the necessary class from the Java utility library.


import java.util.Arrays;

// Define a class named Exercise1.


public class Exercise1 {
// The main method where the program execution starts.
public static void main(String[] args) {

// Declare and initialize an integer array.


int[] my_array1 = {
1789, 2035, 1899, 1456, 2013,
1458, 2458, 1254, 1472, 2365,
1456, 2165, 1457, 2456
};

// Declare and initialize a string array.


String[] my_array2 = {
"Java",
"Python",
"PHP",
"C#",
"C Programming",
"C++"
};

// Print the original numeric array.


System.out.println("Original numeric array : " + Arrays.toString(my_array1));

// Sort the numeric array in ascending order.


Arrays.sort(my_array1);

// Print the sorted numeric array.


System.out.println("Sorted numeric array : " + Arrays.toString(my_array1));

CS251 Object Oriented Programming


// Print the original string array.
System.out.println("Original string array : " + Arrays.toString(my_array2));

// Sort the string array in lexicographical (alphabetical) order.


Arrays.sort(my_array2);

// Print the sorted string array.


System.out.println("Sorted string array : " + Arrays.toString(my_array2));
}
}

Sample Output:

Original numeric array : [1789, 2035, 1899, 1456, 2013, 1458, 2458, 1254, 1472, 2365, 1456, 2165, 1457, 2456]
Sorted numeric array : [1254, 1456, 1456, 1457, 1458, 1472, 1789, 1899, 2013, 2035, 2165, 2365, 2456, 2458]
Original string array : [Java, Python, PHP, C#, C Programming, C++]
Sorted string array : [C Programming, C#, C++, Java, PHP, Python]

1. Adding Two Matrix

Here is the simple program to populate two matrices from the user input. Then add its elements at
the corresponding indices to get the addition of the matrices. Finally, we will print the sum of the
matrices.

package com.journaldev.examples;

import java.util.Scanner;

public class MatrixPrograms {

public static void main(String[] args) {


System.out.println("Please enter the rows in the matrix");
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
System.out.println("Please enter the columns in the matrix");
int column = sc.nextInt();

int[][] first = new int[row][column];


int[][] second = new int[row][column];

for (int r = 0; r < row; r++) {


for (int c = 0; c < column; c++) {
System.out.println(String.format("Enter first[%d][%d] integer", r, c));
first[r][c] = sc.nextInt();
}
}

for (int r = 0; r < row; r++) {


for (int c = 0; c < column; c++) {
System.out.println(String.format("Enter second[%d][%d] integer", r,
c));

CS251 Object Oriented Programming


second[r][c] = sc.nextInt();
}
}

// close the scanner


sc.close();

// print both matrices


System.out.println("First Matrix:\n");
print2dArray(first);

System.out.println("Second Matrix:\n");
print2dArray(second);

// sum of matrices
sum(first, second);
}

// below code doesn't take care of exceptions


private static void sum(int[][] first, int[][] second) {
int row = first.length;
int column = first[0].length;
int[][] sum = new int[row][column];

for (int r = 0; r < row; r++) {


for (int c = 0; c < column; c++) {
sum[r][c] = first[r][c] + second[r][c];
}
}

System.out.println("\nSum of Matrices:\n");
print2dArray(sum);
}

private static void print2dArray(int[][] matrix) {


for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[0].length; c++) {
System.out.print(matrix[r][c] + "\t");
}
System.out.println();
}
}
}

CS251 Object Oriented Programming


CS251 Object Oriented Programming
Adding Two Matrices

1. Adding Two Matrix

Here is the simple program to populate two matrices from the user input. Then add its elements at
the corresponding indices to get the addition of the matrices. Finally, we will print the sum of the
matrices.

package com.journaldev.examples;

import java.util.Scanner;

public class MatrixPrograms {

public static void main(String[] args) {


System.out.println("Please enter the rows in the matrix");
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
System.out.println("Please enter the columns in the matrix");
int column = sc.nextInt();

int[][] first = new int[row][column];


int[][] second = new int[row][column];

for (int r = 0; r < row; r++) {


for (int c = 0; c < column; c++) {
System.out.println(String.format("Enter first[%d][%d] integer", r, c));
first[r][c] = sc.nextInt();
}
}

for (int r = 0; r < row; r++) {


for (int c = 0; c < column; c++) {
System.out.println(String.format("Enter second[%d][%d] integer", r,
c));
second[r][c] = sc.nextInt();
}
}

// close the scanner


sc.close();

// print both matrices


System.out.println("First Matrix:\n");
print2dArray(first);

System.out.println("Second Matrix:\n");
print2dArray(second);

// sum of matrices
sum(first, second);
}

// below code doesn't take care of exceptions

CS251 Object Oriented Programming


private static void sum(int[][] first, int[][] second) {
int row = first.length;
int column = first[0].length;
int[][] sum = new int[row][column];

for (int r = 0; r < row; r++) {


for (int c = 0; c < column; c++) {
sum[r][c] = first[r][c] + second[r][c];
}
}

System.out.println("\nSum of Matrices:\n");
print2dArray(sum);
}

private static void print2dArray(int[][] matrix) {


for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[0].length; c++) {
System.out.print(matrix[r][c] + "\t");
}
System.out.println();
}
}
}

CS251 Object Oriented Programming


CS251 Object Oriented Programming
Adding Two Matrices

2. Subtracting Two Matrices

Here is the function to subtraction second matrix elements from the first matrix and then print the
result matrix.

private static void subtract(int[][] first, int[][] second) {


int row = first.length;
int column = first[0].length;
int[][] sum = new int[row][column];

for (int r = 0; r < row; r++) {


for (int c = 0; c < column; c++) {
sum[r][c] = first[r][c] - second[r][c];
}
}

System.out.println("\nSubtraction of Matrices:\n");
print2dArray(sum);
}

3. Multiplying Two Matrices

Below method will multiply the matrix elements and print the result matrix.

private static void multiply(int[][] first, int[][] second) {


int row = first.length;
int column = first[0].length;
int[][] sum = new int[row][column];

for (int r = 0; r < row; r++) {


for (int c = 0; c < column; c++) {
sum[r][c] = first[r][c] * second[r][c];
}
}

System.out.println("\nMultiplication of Matrices:\n");
print2dArray(sum);
}

Practical 4: Strings :

Write a Java program to get the character at the given index within the string.

Visualal Presentation:

CS251 Object Oriented Programming


Sample Solution:

Java Code:

// Define a public class named Exercise1.


public class Exercise1 {
// Define the main method.
public static void main(String[] args) {
// Declare and initialize a string variable "str" with the value "Java Exercises!".
String str = "Java Exercises!";
// Print the original string.
System.out.println("Original String = " + str);

// Get the character at positions 0 and 10.


int index1 = str.charAt(0); // Get the ASCII value of the character at position 0.
int index2 = str.charAt(10); // Get the ASCII value of the character at position 10.

// Print out the results.


System.out.println("The character at position 0 is " +
(char)index1); // Print the character at position 0 by converting ASCII value to char.
System.out.println("The character at position 10 is " +
(char)index2); // Print the character at position 10 by converting ASCII value to char.
}
}

Sample Output:

Original String = Java Exercises!


The character at position 0 is J

CS251 Object Oriented Programming


The character at position 10 is i

Write a Java program to test if a given string contains the specified sequence of char values.

Visual Presentation:

Sample Solution:

Java Code:

// Define a public class named Exercise8.


public class Exercise8 {
// Define the main method.
public static void main(String[] args) {
// Declare and initialize two string variables, str1 and str2.
String str1 = "PHP Exercises and Python Exercises";
String str2 = "and";

// Print the original string.


System.out.println("Original String: " + str1);
// Print the specified sequence of char values.
System.out.println("Specified sequence of char values: " + str2);

// Check if str1 contains the sequence specified in str2 and print the result.
System.out.println(str1.contains(str2));
}
}

CS251 Object Oriented Programming


Sample Output:

Original String: PHP Exercises and Python Exercises


Specified sequence of char values: and
true

Given a String, the task is to insert another string in between the given String at a particular
specified index in Java.

Examples:

Input: originalString = "GeeksGeeks",


stringToBeInserted = "For",
index = 4
Output: "GeeksForGeeks"

Input: originalString = "Computer Portal",


stringToBeInserted = "Science ",
index = 8
Output: "Computer Science Portal"

The various methods to do this are as follows:

1. Without using any pre-defined method

CS251 Object Oriented Programming


Approach:

1. Get the Strings and the index.


2. Create a new String
3. Traverse the string till the specified index and copy this into the new String.
4. Copy the String to be inserted into this new String
5. Copy the remaining characters of the first string into the new String
6. Return/Print the new String

Below is the implementation of the above approach:

Program:

// Java program to insert a string into another string

// without using any pre-defined method

import java.lang.*;

class GFG {

// Function to insert string

public static String insertString(

String originalString,

String stringToBeInserted,

int index)

// Create a new string

String newString = new String();

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

// Insert the original string character

// into the new string

newString += originalString.charAt(i);

CS251 Object Oriented Programming


if (i == index) {

// Insert the string to be inserted

// into the new string

newString += stringToBeInserted;

// return the modified String

return newString;

// Driver code

public static void main(String[] args)

// Get the Strings

String originalString = "GeeksGeeks";

String stringToBeInserted = "For";

int index = 4;

System.out.println("Original String: "

+ originalString);

System.out.println("String to be inserted: "

+ stringToBeInserted);

System.out.println("String to be inserted at index: "

+ index);

// Insert the String

System.out.println("Modified String: "

CS251 Object Oriented Programming


+ insertString(originalString,

stringToBeInserted,

index));

Output:

Original String: GeeksGeeks


String to be inserted: For
String to be inserted at index: 4
Modified String: GeeksForGeeks

2. Using String.substring() method

Approach:

1. Get the Strings and the index.


2. Create a new String
3. Insert the substring from 0 to the specified (index + 1) using substring(0, index+1)
method. Then insert the string to be inserted into the string. Then insert the remaining part
of the original string into the new string using substring(index+1) method.
4. Return/Print the new String

Below is the implementation of the above approach:

Program:

// Java program to insert a string into another string

// without using any pre-defined method

import java.lang.*;

class GFG {

// Function to insert string

public static String insertString(

String originalString,

String stringToBeInserted,

CS251 Object Oriented Programming


int index)

// Create a new string

String newString = originalString.substring(0, index + 1)

+ stringToBeInserted

+ originalString.substring(index + 1);

// return the modified String

return newString;

// Driver code

public static void main(String[] args)

// Get the Strings

String originalString = "GeeksGeeks";

String stringToBeInserted = "For";

int index = 4;

System.out.println("Original String: "

+ originalString);

System.out.println("String to be inserted: "

+ stringToBeInserted);

System.out.println("String to be inserted at index: "

+ index);

// Insert the String

System.out.println("Modified String: "

+ insertString(originalString,

CS251 Object Oriented Programming


stringToBeInserted,

index));

Output:

Original String: GeeksGeeks


String to be inserted: For
String to be inserted at index: 4
Modified String: GeeksForGeeks

3. Using StringBuffer.insert() method

Approach:

1. Get the Strings and the index.


2. Create a new StringBuffer
3. Insert the stringToBeInserted into the original string using StringBuffer.insert() method.
4. Return/Print the String from the StringBuffer using StringBuffer.toString() method.

Below is the implementation of the above approach:

Program:

// Java program to insert a string into another string

// without using any pre-defined method

import java.lang.*;

class GFG {

// Function to insert string

public static String insertString(

String originalString,

String stringToBeInserted,

int index)

CS251 Object Oriented Programming


// Create a new StringBuffer

StringBuffer newString

= new StringBuffer(originalString);

// Insert the strings to be inserted

// using insert() method

newString.insert(index + 1, stringToBeInserted);

// return the modified String

return newString.toString();

// Driver code

public static void main(String[] args)

// Get the Strings

String originalString = "GeeksGeeks";

String stringToBeInserted = "For";

int index = 4;

System.out.println("Original String: "

+ originalString);

System.out.println("String to be inserted: "

+ stringToBeInserted);

System.out.println("String to be inserted at index: "

+ index);

// Insert the String

System.out.println("Modified String: "

CS251 Object Oriented Programming


+ insertString(originalString,

stringToBeInserted,

index));

Output:

Original String: GeeksGeeks


String to be inserted: For
String to be inserted at index: 4
Modified String: GeeksForGeeks

Practical 5: Inheritance concepts:


Write a Java program to Implement multilevel inheritance

This Java program demonstrates multilevel inheritance, which is a concept in object-oriented


programming where a class inherits properties and behaviors from a parent class (superclass), and
then another class inherits from that derived class. In this program, there are three classes:
Animal, Dog, and Puppy, forming a multilevel inheritance hierarchy. Here's an explanation of the
program:

• public class MultilevelInheritance: This is the main class that contains the main method, the entry
point of the program.
• public static void main(String[] args): The main method is the starting point of the program. It
creates an instance of the Puppy class and demonstrates multilevel inheritance by calling methods
from the Animal, Dog, and Puppy classes.
• Puppy puppy = new Puppy("Buddy");: This line creates an object of the Puppy class named
"Buddy." The constructor of the Puppy class is called, which, in turn, calls the constructor of the
Dog class (its parent class), which in turn calls the constructor of the Animal class (its grandparent
class).
• puppy.eat();: This line calls the eat method of the Puppy object, which is inherited from the Animal
class. The output will be "Buddy is Eating."
• puppy.bark();: This line calls the bark method of the Puppy object, which is inherited from the Dog
class. The output will be "Buddy is Barking."
• puppy.play();: This line calls the play method of the Puppy object, which is specific to the Puppy
class. The output will be "Buddy is Playing."
• class Animal: This is the grandparent class (superclass) that represents generic animal properties
and behaviors. It has an instance variable name and a parameterized constructor that initializes the
name.
• public void eat(): The eat method of the Animal class simply prints a message indicating that the
animal is eating, including its name.

CS251 Object Oriented Programming


• class Dog extends Animal: This is the parent class (subclass) that inherits from the Animal class. It
represents a specific type of animal, a dog. The Dog class has its own method, bark, which is not
present in the Animal class.
• public Dog(String name): The constructor of the Dog class takes a name as a parameter and calls
the constructor of the Animal class (its grandparent class) using super(name) to initialize the name
property.
• public void bark(): The bark method of the Dog class prints a message indicating that the dog is
barking, including its name.
• class Puppy extends Dog: This is the child class (subclass) that inherits from the Dog class. It
represents a specific type of dog, a puppy. The Puppy class has its own method, play, which is not
present in the Animal or Dog classes.
• public Puppy(String name): The constructor of the Puppy class takes a name as a parameter and
calls the constructor of the Dog class (its parent class) using super(name) to initialize the name
property.
• public void play(): The play method of the Puppy class prints a message indicating that the puppy
is playing, including its name.

This program demonstrates multilevel inheritance, where the Puppy class inherits properties and
methods from the Dog class, which, in turn, inherits from the Animal class. When an instance of
the Puppy class is created, it can access the behavior of all three classes in the hierarchy.

Source Code
public class MultilevelInheritance // Main class
{
public static void main(String[] args)
{
Puppy puppy = new Puppy("Buddy"); // Create an instance of Puppy

puppy.eat(); // Call methods from Animal class


puppy.bark(); // Call methods from Dog class
puppy.play(); // Call methods from Puppy class
}
}
class Animal // Grandparent class
{
protected String name;

public Animal(String name)


{
this.name = name;
}

public void eat()


{
System.out.println(name + " is Eating");
}
}
class Dog extends Animal // Parent class inheriting from Animal
{
public Dog(String name)
{

CS251 Object Oriented Programming


super(name);
}

public void bark()


{
System.out.println(name + " is Barking");
}
}
class Puppy extends Dog // Child class inheriting from Dog
{
public Puppy(String name)
{
super(name);
}

public void play()


{
System.out.println(name + " is Playing");
}
}

Output
Buddy is Eating
Buddy is Barking
Buddy is Playing

Write a Java program to Demonstrate the protected access specifier

This Java program demonstrates method overriding, a concept in object-oriented programming


where a subclass provides a specific implementation of a method that is already defined in its
superclass. In this program, there are two classes: Vehicle (the base class) and Car (the derived
class), and the display method in the Car class overrides the display method in the Vehicle class.
Here's an explanation of the program:

• public class OverrideMethod: This is the main class that contains the main method, the entry point
of the program.
• public static void main(String[] args): The main method is the starting point of the program. It
creates an object of the Car class and demonstrates method overriding by calling the display
method on this object.
• Car car = new Car();: This line creates an object of the Car class.
• car.display();: This line calls the display method on the car object. Because the Car class has
overridden the display method, the specific implementation in the Car class is executed. Therefore,
the output will be "This is a Car" instead of "This is a Vehicle" that is defined in the Vehicle class.
• class Vehicle: This is the base class that represents generic vehicle properties and behaviors.
• void display(): The display method of the Vehicle class simply prints a message indicating that it is
a vehicle.
• class Car extends Vehicle: This is the derived class (subclass) that inherits from the Vehicle class.
It represents a specific type of vehicle, a car.

CS251 Object Oriented Programming


• @Override void display(): This line indicates that the display method in the Car class is intended
to override the display method in the Vehicle class. The @Override annotation is not mandatory
but is good practice to indicate that you are intentionally overriding a method from the superclass.
• The overridden display method in the Car class provides a specific implementation, which is
different from the implementation in the Vehicle class. It prints a message indicating that it is a car,
and this specific implementation is executed when the display method is called on an object of the
Car class.

This program demonstrates method overriding, where a method in the derived class (Car)
provides its own implementation of a method that is already defined in the base class (Vehicle).
When the overridden method is called on an object of the derived class, the specific
implementation in the derived class is executed.

Source Code
public class AccessSpecifier // Main class
{
public static void main(String[] args)
{
Car car = new Car(); // Create an object of the child class
car.setBrand("Toyota"); // Set the brand using the public method
car.displayBrand(); // Access the protected member and method
}
}
class Vehicle // Parent class
{
protected String brand;

protected void displayBrand()


{
System.out.println("Brand : " + brand);
}
}
class Car extends Vehicle // Child class
{
public void setBrand(String brand)
{
this.brand = brand;
}
}

Output
Brand : Toyota

Write a Java program to Call a superclass constructor from sub/child class

This Java program demonstrates constructor chaining and the use of the super keyword to call a
constructor from a superclass when creating an object of a subclass. In this program, there are two
classes: Super and Sub, where Sub inherits from Super. Here's an explanation of the program:

CS251 Object Oriented Programming


• public class Constructor: This is the main class that contains the main method, the entry point of
the program.
• public static void main(String[] args) : The main method is where the program execution starts. It
creates an object of the Sub class, which triggers the constructors in both the Super and Sub
classes due to inheritance.
• Sub obj = new Sub();: This line creates an object of the Sub class, which triggers the constructor of
the Sub class and, because of the super(); statement within the Sub constructor, also triggers the
constructor of the Super class. The constructors print messages indicating that they have been
called.
• class Super: This is the superclass, which has a constructor.
• Super(): The constructor of the Super class prints a message, "Super class Constructor called."
• class Sub extends Super: This is the subclass, which inherits from the Super class. It also has a
constructor that calls the super() constructor from the superclass using the super keyword.
• Sub(): The constructor of the Sub class starts by calling the constructor of the Super class using
super(). After that, it prints its own message, "Sub class Constructor called."

This program demonstrates constructor chaining, where the constructor of a subclass (Sub) can
call the constructor of its superclass (Super) using the super keyword. When an object of the
subclass is created, both constructors are called in order: first, the constructor of the superclass,
and then the constructor of the subclass. This behavior is due to the inheritance relationship
between the two classes.

Source Code
public class Constructor
{
public static void main(String[] args)
{
Sub obj = new Sub();
}
}
class Super
{
Super()
{
System.out.println("Super class Constructor called");
}
}
class Sub extends Super
{
Sub()
{
super();
System.out.println("Sub class Constructor called");
}
}

Output
Super class Constructor called
Sub class Constructor called

CS251 Object Oriented Programming


Write a Java program to Method Overloading and Inheritance

This Java program demonstrates method overloading, a concept in object-oriented programming


where a class can have multiple methods with the same name but different parameter lists. In this
program, there are two classes: Vehicle (the parent class) and Car (the child class), and the Car
class overloads the start method. Here's an explanation of the program:

• public class MethodOverloading: This is the main class that contains the main method, the entry
point of the program.
• public static void main(String[] args) : The main method is where the program execution starts. It
creates an object of the Car class and demonstrates method overloading by calling two different
versions of the start method.
• Car car = new Car();: This line creates an object of the Car class.
• car.start();: This line calls the start method on the car object. Since the Car class does not override
the start method of the parent class, the method from the parent class (Vehicle) is called. The
output will be "Vehicle starting ..."
• car.start(3); : This line calls the overloaded start method in the Car class, which takes an integer
parameter. This version of the method prints a message indicating the number of cars starting. The
output will be "Starting 3 Cars ..."
• class Vehicle: This is the parent class, which has a method named start.
• void start(): The start method of the Vehicle class simply prints "Vehicle starting ..."
• class Car extends Vehicle: This is the child class that inherits from the Vehicle class.
• void start(int count): The Car class overloads the start method by defining a new version that takes
an integer parameter, count. This version of the method prints a message indicating the number of
cars starting.

This program demonstrates method overloading, where the child class (Car) defines a method
with the same name as the one in the parent class (Vehicle) but with a different parameter list.
The appropriate version of the method is called based on the number and types of arguments
provided when the method is invoked.

Source Code
public class MethodOverloading // Main class
{
public static void main(String[] args)
{
Car car = new Car();
car.start(); // Accessing parent class method
car.start(3); // Accessing overloaded method in child class
}
}
class Vehicle // Parent class
{
void start()
{
System.out.println("Vehicle starting ...");
}

CS251 Object Oriented Programming


}
class Car extends Vehicle // Child class
{
void start(int count)
{
System.out.println("Starting " + count + " Cars ...");
}
}

Output
Vehicle starting ...
Starting 3 Cars ...

Practical 6: Method overriding :

Write a Java program to create a class called Animal with a method called makeSound(). Create a
subclass called Cat that overrides the makeSound() method to bark.

This exercise shows how inheritance works in Java programming language. Inheritance allows
you to create new classes based on existing classes, inheriting their attributes and behaviors. In
this case, the 'Cat' class is a more specific implementation of the 'Animal' class, adding quarrel
behavior.

Sample Solution:

Java Code:

// Animal.java
public class Animal {
public void makeSound() {
System.out.println("The animal makes a sound.");
}
}

// Cat.java
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("The cat quarrels.");
}
}
// Main.java
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
Cat cat = new Cat();
animal.makeSound();
cat.makeSound();
}
}

CS251 Object Oriented Programming


Sample Output:

The animal makes a sound.


The cat quarrels.

Write a Java program to create a class called Animal with a method named move(). Create a
subclass called Cheetah that overrides the move() method to run.

Sample Solution:

Java Code:

// Animal.java
// Parent class Animal

public class Animal {


public void move() {
System.out.println("Animal moves");
}
}

// Cheetah.java
// Child class Cheetah
public class Cheetah extends Animal {
@Override
public void move() {
System.out.println("This cheetah is running!");
}
}
// Main.java
// Main class
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
animal.move();
Cheetah cheetah = new Cheetah();
cheetah.move();
}
}

Sample Output:

Animal moves
This cheetah is running!

Practical 7: Exception-handling Fundamentals:

Write a Java program to create a method that takes an integer as a parameter and throws an
exception if the number is odd.

CS251 Object Oriented Programming


Sample Solution:

Java Code:

public class Exception_OddNumber {


public static void main(String[] args) {
int n = 18;
trynumber(n);
n = 7;
trynumber(n);
}

public static void trynumber(int n) {


try {
checkEvenNumber(n);
System.out.println(n + " is even.");
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}

public static void checkEvenNumber(int number) {


if (number % 2 != 0) {
throw new IllegalArgumentException(number + " is odd.");
}
}
}

Sample Output:

18 is even.
Error: 7 is odd.

Write a Java program that reads a list of integers from the user and throws an exception if any
numbers are duplicates.

Sample Solution:

Java Code:

import java.util.*;

public class Duplicate_Number_Check {


public static void main(String[] args) {
try {
List < Integer > numbers = readNumbersFromUser();
checkDuplicates(numbers);
System.out.println("No duplicate numbers!");
} catch (Duplicate_Number_Exception e) {
System.out.println("Error: " + e.getMessage());
}

CS251 Object Oriented Programming


}

public static List < Integer > readNumbersFromUser() {


List < Integer > numbers = new ArrayList < > ();
Scanner scanner = new Scanner(System.in);

System.out.print("How many numbers do you want to input? ");


int count = scanner.nextInt();

System.out.println("Input the integers:");


for (int i = 0; i < count; i++) {
int num = scanner.nextInt();
numbers.add(num);
}

scanner.close();
return numbers;
}

public static void checkDuplicates(List < Integer > numbers) throws Duplicate_Number_Exception {
Set < Integer > uniqueNumbers = new HashSet < > ();

for (int num: numbers) {


if (uniqueNumbers.contains(num)) {
throw new Duplicate_Number_Exception("Duplicate number found: " + num);
}
uniqueNumbers.add(num);
}
}
}
class Duplicate_Number_Exception extends Exception {
public Duplicate_Number_Exception(String message) {
super(message);
}
}

Sample Output:

How many numbers do you want to input? 5


Input the integers:
1
2
3
4
5
No duplicate numbers!
How many numbers do you want to input? 6
Input the integers:
1
2
3
3
4
5

CS251 Object Oriented Programming


Error: Duplicate number found: 3

Write a Java program to create a method that takes a string as input and throws an exception if the
string does not contain vowels.

Sample Solution:

Java Code:

public class Vowel_Check {


public static void main(String[] args) {
try {
String text = "Java handling and managing exceptions ";
// String text = "Typy gyps fly.";
System.out.println("Original string: " + text);
checkVowels(text);
System.out.println("String contains vowels.");
} catch (NoVowelsException e) {
System.out.println("Error: " + e.getMessage());
}
}

public static void checkVowels(String text) throws NoVowelsException {


boolean containsVowels = false;
String vowels = "aeiouAEIOU";

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


char ch = text.charAt(i);
if (vowels.contains(String.valueOf(ch))) {
containsVowels = true;
break;
}
}
if (!containsVowels) {
throw new NoVowelsException("String does not contain any vowels.");
}
}
}
class NoVowelsException extends Exception {
public NoVowelsException(String message) {
super(message);
}
}

Sample Output:

Original string: Java handling and managing exceptions


String contains vowels.
Original string: Typy gyps fly.
Error: String does not contain any vowels

CS251 Object Oriented Programming


Write a Java program that reads a file and throws an exception if the file is empty.

Sample Solution:

Java Code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Empty_File_Check {


public static void main(String[] args) {
try {
checkFileNotEmpty("test1.txt");
System.out.println("File is not empty.");
} catch (FileNotFoundException e) {
System.out.println("Error: " + e.getMessage());
} catch (EmptyFileException e) {
System.out.println("Error: " + e.getMessage());
}
}

public static void checkFileNotEmpty(String fileName) throws FileNotFoundException, EmptyFileException {


File file = new File(fileName);
Scanner scanner = new Scanner(file);

if (!scanner.hasNextLine()) {
scanner.close();
throw new EmptyFileException("File is empty.");
}

scanner.close();
}
}

class EmptyFileException extends Exception {


public EmptyFileException(String message) {
super(message);
}
}

Sample Output:

Content of the file (test1.txt):


0
0
0

File is not empty.


Content of the file (test1.txt):

Error: File is empty.

CS251 Object Oriented Programming


Practical 8: Collection & Generics :

Write a Java program to create an array list, add some colors (strings) and print out the collection.

Pictorial Presentation:

CS251 Object Oriented Programming


CS251 Object Oriented Programming
Sample Solution:-

Java Code:

import java.util.*;
public class Exercise1 {
public static void main(String[] args) {
List<String> list_Strings = new ArrayList<String>();
list_Strings.add("Red");
list_Strings.add("Green");
list_Strings.add("Orange");
list_Strings.add("White");
list_Strings.add("Black");
System.out.println(list_Strings);
}
}

Sample Output:

Note: Exercise1.java uses unchecked or unsafe operations.


Note: Recompile with -Xlint:unchecked for details.
[Red, Green, Orange, White, Black]

Write a Java program to iterate through all elements in a linked list.

Sample Solution:-

Java Code:

import java.util.LinkedList;
public class Exercise2 {
public static void main(String[] args) {
// create an empty linked list
LinkedList<String> l_list = new LinkedList<String>();
// use add() method to add values in the linked list
l_list.add("Red");
l_list.add("Green");
l_list.add("Black");
l_list.add("White");
l_list.add("Pink");
// Print the linked list
for (String element : l_list) {
System.out.println(element);
}
}
}

Sample Output:

Red
Green

CS251 Object Oriented Programming


Black
White
Pink

Write a Java program to create a tree set, add some colors (strings) and print out the tree set.

Sample Solution:

Java Code:

import java.util.TreeSet;
public class Exercise1 {
public static void main(String[] args) {
TreeSet<String> tree_set = new TreeSet<String>();
tree_set.add("Red");
tree_set.add("Green");
tree_set.add("Orange");
tree_set.add("White");
tree_set.add("Black");
System.out.println("Tree set: ");
System.out.println(tree_set);
}
}

Sample Output:

Tree set:
[Black, Green, Orange, Red, White]

Write a generic method to count the number of elements in a collection that have a specific
property (for example, odd integers, prime numbers, palindromes).

Answer:
public final class Algorithm {
public static <T> int countIf(Collection<T> c, UnaryPredicate<T> p) {

int count = 0;
for (T elem : c)
if (p.test(elem))
++count;
return count;
}
}
where the generic UnaryPredicate interface is defined as follows:
public interface UnaryPredicate<T> {
public boolean test(T obj);
}
For example, the following program counts the number of odd integers in an integer list:
import java.util.*;

CS251 Object Oriented Programming


class OddPredicate implements UnaryPredicate<Integer> {
public boolean test(Integer i) { return i % 2 != 0; }
}

public class Test {


public static void main(String[] args) {
Collection<Integer> ci = Arrays.asList(1, 2, 3, 4);
int count = Algorithm.countIf(ci, new OddPredicate());
System.out.println("Number of odd integers = " + count);
}
}
The program prints:
Number of odd integers = 2

Practical 9: Event-handling :
AWTCounter

Write an AWT GUI application (called AWTCounter) as shown in the Figure. Each time the
"Count" button is clicked, the counter value shall increase by 1.

The program has three components:

1. a java.awt.Label "Counter";
2. a non-editable java.awt.TextField to display the counter value; and
3. a java.awt.Button "Count".

The components are placed inside the top-level AWT container java.awt.Frame, arranged in
FlowLayout.

1 import java.awt.*; // Using AWT container and component classes


2 import java.awt.event.*; // Using AWT event classes and listener interfaces
3
4 // An AWT program inherits from the top-level container java.awt.Frame
5 public class AWTCounter extends Frame {
6 private Label lblCount; // Declare a Label component
7 private TextField tfCount; // Declare a TextField component
8 private Button btnCount; // Declare a Button component

CS251 Object Oriented Programming


9 private int count = 0; // Counter's value
10
11 // Constructor to setup GUI components and event handlers
12 public AWTCounter () {
13 setLayout(new FlowLayout());
14 // "super" Frame, which is a Container, sets its layout to FlowLayout to arrange
15 // the components from left-to-right, and flow to next row from top-to-bottom.
16
17 lblCount = new Label("Counter"); // construct the Label component
18 add(lblCount); // "super" Frame container adds Label component
19
20 tfCount = new TextField(count + "", 10); // construct the TextField component with initial text
21 tfCount.setEditable(false); // set to read-only
22 add(tfCount); // "super" Frame container adds TextField component
23
24 btnCount = new Button("Count"); // construct the Button component
25 add(btnCount); // "super" Frame container adds Button component
26
27 BtnCountListener listener = new BtnCountListener();
28 btnCount.addActionListener(listener);
29 // "btnCount" is the source object that fires an ActionEvent when clicked.
30 // The source object adds an instance of BtnCountListener as an ActionEvent listener,
31 // which provides an ActionEvent handler called actionPerformed().
32 // Clicking "Count" button calls back actionPerformed().
33
34 setTitle("AWT Counter"); // "super" Frame sets its title
35 setSize(300, 100); // "super" Frame sets its initial window size
36
37 // For inspecting the Container/Components objects
38 // System.out.println(this);
39 // System.out.println(lblCount);
40 // System.out.println(tfCount);
41 // System.out.println(btnCount);
42 setVisible(true); // "super" Frame shows
43 // System.out.println(this);
44 // System.out.println(lblCount);
45 // System.out.println(tfCount);
46 // System.out.println(btnCount);
47 }
48
49 // The entry main() method
50 public static void main(String[] args) {
51 // Invoke the constructor to setup the GUI, by allocating an instance
52 AWTCounter app = new AWTCounter();
53 // or simply "new AWTCounter();" for an anonymous instance
54 }
55
56 // Define an inner class to handle the "Count" button-click
57 private class BtnCountListener implements ActionListener {
58 // ActionEvent handler - Called back upon button-click.
59 @Override
60 public void actionPerformed(ActionEvent evt) {
61 ++count; // Increase the counter value
62 // Display the counter value on the TextField tfCount
63 tfCount.setText(count + ""); // Convert int to String

CS251 Object Oriented Programming


64 }
65 }
66 }

You have to use control-c, or "close" the CMD shell, or hit the "terminate" button on Eclipse's
Console to terminate the program. This is because the program does not process the WindowEvent
fired by the "window-close" button.

Practical 10: JDBC:

Performing Database Operations in Java | SQL CREATE,


INSERT, UPDATE, DELETE and SELECT
Connecting to the Database
The Oracle Database server listens on the default port 1521 at localhost. The following code
snippet connects to the database name userid by the user login1 and password pwd1.

// Java program to illustrate

// Connecting to the Database

import java.sql.*;

public class connect

public static void main(String args[])

try

Class.forName("oracle.jdbc.driver.OracleDriver");

// Establishing Connection

Connection con = DriverManager.getConnection(

"jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");

if (con != null)

System.out.println("Connected");

CS251 Object Oriented Programming


else

System.out.println("Not Connected");

con.close();

catch(Exception e)

System.out.println(e);

Output :
Connected

Note: Here oracle in database URL in getConnection() method specifies SID of Oracle Database.
For Oracle database 11g it is orcl and for oracle database 10g it is xe.

1. Implementing Insert Statement:


// Java program to illustrate

// inserting to the Database

import java.sql.*;

public class insert1

public static void main(String args[])

String id = "id1";

String pwd = "pwd1";

String fullname = "geeks for geeks";

String email = "geeks@geeks.org";

try

CS251 Object Oriented Programming


Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con = DriverManager.getConnection("

jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");

Statement stmt = con.createStatement();

// Inserting data in database

String q1 = "insert into userid values('" +id+ "', '" +pwd+

"', '" +fullname+ "', '" +email+ "')";

int x = stmt.executeUpdate(q1);

if (x > 0)

System.out.println("Successfully Inserted");

else

System.out.println("Insert Failed");

con.close();

catch(Exception e)

System.out.println(e);

Output :
Successfully Registered

2. Implementing Update Statement:


// Java program to illustrate

// updating the Database

import java.sql.*;

public class update1

CS251 Object Oriented Programming


public static void main(String args[])

String id = "id1";

String pwd = "pwd1";

String newPwd = "newpwd";

try

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con = DriverManager.getConnection("

jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");

Statement stmt = con.createStatement();

// Updating database

String q1 = "UPDATE userid set pwd = '" + newPwd +

"' WHERE id = '" +id+ "' AND pwd = '" + pwd + "'";

int x = stmt.executeUpdate(q1);

if (x > 0)

System.out.println("Password Successfully Updated");

else

System.out.println("ERROR OCCURRED :(");

con.close();

catch(Exception e)

System.out.println(e);

Output :
Password Successfully Updated

CS251 Object Oriented Programming


3. Implementing Delete Statement:
// Java program to illustrate

// deleting from Database

import java.sql.*;

public class delete

public static void main(String args[])

String id = "id2";

String pwd = "pwd2";

try

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con = DriverManager.getConnection("

jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");

Statement stmt = con.createStatement();

// Deleting from database

String q1 = "DELETE from userid WHERE id = '" + id +

"' AND pwd = '" + pwd + "'";

int x = stmt.executeUpdate(q1);

if (x > 0)

System.out.println("One User Successfully Deleted");

else

System.out.println("ERROR OCCURRED :(");

con.close();

CS251 Object Oriented Programming


catch(Exception e)

System.out.println(e);

Output :
One User Successfully Deleted

4. Implementing Select Statement:


// Java program to illustrate

// selecting from Database

import java.sql.*;

public class select

public static void main(String args[])

String id = "id1";

String pwd = "pwd1";

try

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con = DriverManager.getConnection("

jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");

Statement stmt = con.createStatement();

// SELECT query

String q1 = "select * from userid WHERE id = '" + id +

"' AND pwd = '" + pwd + "'";

ResultSet rs = stmt.executeQuery(q1);

if (rs.next())

CS251 Object Oriented Programming


{

System.out.println("User-Id : " + rs.getString(1));

System.out.println("Full Name :" + rs.getString(3));

System.out.println("E-mail :" + rs.getString(4));

else

System.out.println("No such user id is already registered");

con.close();

catch(Exception e)

System.out.println(e);

Output
User-Id : id1
Full Name : geeks for geeks
E-mail :geeks@geeks.org

Practical 11: Clients & Servers:

Write a Socket program using Java

CS251 Object Oriented Programming


Let's see a sample of Java socket programming where client sends a text and server receives and
prints it.

File: MyServer.java

1. import java.io.*;
2. import java.net.*;
3. public class MyServer {
4. public static void main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(6666);
7. Socket s=ss.accept();//establishes connection
8. DataInputStream dis=new DataInputStream(s.getInputStream());
9. String str=(String)dis.readUTF();
10. System.out.println("message= "+str);
11. ss.close();
12. }catch(Exception e){System.out.println(e);}
13. }

CS251 Object Oriented Programming


14. }

File: MyClient.java

1. import java.io.*;
2. import java.net.*;
3. public class MyClient {
4. public static void main(String[] args) {
5. try{
6. Socket s=new Socket("localhost",6666);
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. dout.writeUTF("Hello Server");
9. dout.flush();
10. dout.close();
11. s.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }

Practical 12: Java Threads :

Write a Java program to create a basic Java thread that prints "Hello, World!" when executed.

Sample Solution:

Java Code:

public class Hello_world_thread extends Thread {


@Override
public void run() {
System.out.println("Hello, World!");
}
public static void main(String[] args) {
Hello_world_thread thread = new Hello_world_thread();
thread.start();
}
}

Sample Output:

Hello, World!

Write a Java program that creates two threads to find and print even and odd numbers from 1 to
20.

CS251 Object Oriented Programming


Sample Solution:

Java Code:

public class Find_Even_Odd_Number {


private static final int MAX_NUMBER = 20;
private static Object lock = new Object();
private static boolean isEvenTurn = true;

public static void main(String[] args) {


Thread evenThread = new Thread(() -> {
for (int i = 2; i <= MAX_NUMBER; i += 2) {
synchronized(lock) {
while (!isEvenTurn) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Even Number from evenThread: " + i);
isEvenTurn = false;
lock.notify();
}
}
});

Thread oddThread = new Thread(() -> {


for (int i = 1; i <= MAX_NUMBER; i += 2) {
synchronized(lock) {
while (isEvenTurn) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Odd Number from oddThread: " + i);
isEvenTurn = true;
lock.notify();
}
}
});

evenThread.start();
oddThread.start();
}
}

Sample Output:

Even Number from evenThread: 2


Odd Number from oddThread: 1

CS251 Object Oriented Programming


Even Number from evenThread: 4
Odd Number from oddThread: 3
Even Number from evenThread: 6
Odd Number from oddThread: 5
Even Number from evenThread: 8
Odd Number from oddThread: 7
Even Number from evenThread: 10
Odd Number from oddThread: 9
Even Number from evenThread: 12
Odd Number from oddThread: 11
Even Number from evenThread: 14
Odd Number from oddThread: 13
Even Number from evenThread: 16
Odd Number from oddThread: 15
Even Number from evenThread: 18
Odd Number from oddThread: 17
Even Number from evenThread: 20
Odd Number from oddThread: 19

Write a Java program that sorts an array of integers using multiple threads.

The program divides the sorting task among multiple threads and perform parallel sorting to
improve the performance of sorting large arrays.

Sample Solution:

Java Code:

import java.util.Arrays;

public class ParallelSort {


private static final int ARRAY_SIZE = 400;
private static final int NUM_THREADS = 4;

public static void main(String[] args) {


int[] array = createArray();
System.out.println("Before sorting: " + Arrays.toString(array));

Thread[] threads = new Thread[NUM_THREADS];


int segmentSize = ARRAY_SIZE / NUM_THREADS;

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


int startIndex = i * segmentSize;
int endIndex = (i == NUM_THREADS - 1) ? ARRAY_SIZE - 1 : (startIndex + segmentSize - 1);
threads[i] = new Thread(new SortTask(array, startIndex, endIndex));
threads[i].start();
}

for (Thread thread: threads) {


try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();

CS251 Object Oriented Programming


}
}

mergeSort(array, 0, ARRAY_SIZE - 1);

System.out.println("After sorting: " + Arrays.toString(array));


}

private static int[] createArray() {


int[] array = new int[ARRAY_SIZE];
for (int i = 0; i < ARRAY_SIZE; i++) {
array[i] = (int)(Math.random() * 400); // Generate random numbers between 0 and 400
}
return array;
}

private static void mergeSort(int[] array, int left, int right) {


if (left < right) {
int mid = (left + right) / 2;
mergeSort(array, left, mid);
mergeSort(array, mid + 1, right);
merge(array, left, mid, right);
}
}

private static void merge(int[] array, int left, int mid, int right) {
int[] temp = new int[right - left + 1];
int i = left, j = mid + 1, k = 0;

while (i <= mid && j <= right) {


if (array[i] <= array[j]) {
temp[k++] = array[i++];
} else {
temp[k++] = array[j++];
}
}

while (i <= mid) {


temp[k++] = array[i++];
}

while (j <= right) {


temp[k++] = array[j++];
}

System.arraycopy(temp, 0, array, left, temp.length);


}

static class SortTask implements Runnable {


private int[] array;
private int startIndex;
private int endIndex;

public SortTask(int[] array, int startIndex, int endIndex) {


this.array = array;
this.startIndex = startIndex;

CS251 Object Oriented Programming


this.endIndex = endIndex;
}

@Override
public void run() {
Arrays.sort(array, startIndex, endIndex + 1);
}
}
}

Sample Output:

Before sorting: [317, 153, 98, 262, 171, 100, 371, 350, 386, 162, 139, 160, 69, 59, 331, 305, 12, 312, 190, 385, 355,
259, 9, 96, 217, 340, 313, 46, 47, 213, 200, 121, 94, 79, 64, 47, 91, 113, 192, 268, 135, 362, 256, 72, 299, 181, 22,
174, 360, 217, 149, 238, 67, 226, 261, 91, 26, 17, 292, 300, 107, 314, 389, 75, 222, 322, 129, 186, 133, 356, 129, 134,
313, 276, 376, 133, 352, 95, 205, 50, 152, 303, 296, 4, 281, 328, 282, 110, 16, 359, 70, 266, 143, 226, 353, 69, 395,
291, 197, 395, 171, 188, 346, 177, 179, 146, 319, 202, 71, 105, 399, 182, 367, 398, 396, 30, 170, 251, 390, 361, 75,
127, 39, 334, 294, 92, 157, 272, 120, 112, 323, 383, 122, 29, 397, 291, 392, 290, 87, 390, 39, 359, 299, 223, 88, 325,
35, 232, 46, 264, 69, 247, 392, 147, 56, 39, 345, 138, 223, 299, 114, 207, 74, 27, 160, 234, 0, 125, 44, 101, 49, 263,
216, 351, 169, 341, 346, 316, 27, 318, 27, 154, 389, 109, 141, 351, 73, 100, 17, 230, 184, 374, 214, 152, 387, 48, 235,
74, 309, 68, 185, 337, 23, 138, 281, 130, 146, 32, 82, 337, 322, 114, 399, 253, 129, 258, 256, 123, 74, 183, 158, 328,
229, 195, 177, 54, 332, 385, 88, 26, 84, 340, 252, 319, 68, 87, 76, 8, 31, 238, 196, 304, 21, 392, 86, 171, 0, 117, 310,
344, 110, 341, 37, 245, 145, 297, 185, 19, 365, 274, 168, 145, 367, 177, 198, 25, 161, 234, 141, 365, 389, 350, 102, 2,
282, 193, 15, 30, 167, 257, 293, 336, 32, 170, 330, 304, 75, 310, 248, 116, 98, 16, 245, 151, 51, 318, 322, 280, 384,
358, 362, 354, 147, 131, 382, 305, 129, 253, 179, 194, 270, 135, 92, 103, 126, 57, 214, 93, 155, 130, 107, 54, 149, 63,
128, 9, 354, 399, 392, 253, 13, 394, 306, 311, 289, 122, 338, 96, 367, 128, 8, 301, 347, 334, 269, 278, 250, 134, 158,
121, 265, 373, 39, 145, 107, 183, 83, 212, 190, 33, 83, 254, 296, 229, 66, 259, 56, 159, 45, 84, 385, 219, 32, 393, 258,
98, 139, 167, 266, 122, 14, 377, 280, 146, 157, 376, 190, 342, 145, 161, 44, 4, 296, 222, 142, 10, 1, 117, 40, 382]
After sorting: [0, 0, 1, 2, 4, 4, 8, 8, 9, 9, 10, 12, 13, 14, 15, 16, 16, 17, 17, 19, 21, 22, 23, 25, 26, 26, 27, 27, 27, 29, 30,
30, 31, 32, 32, 32, 33, 35, 37, 39, 39, 39, 39, 40, 44, 44, 45, 46, 46, 47, 47, 48, 49, 50, 51, 54, 54, 56, 56, 57, 59, 63,
64, 66, 67, 68, 68, 69, 69, 69, 70, 71, 72, 73, 74, 74, 74, 75, 75, 75, 76, 79, 82, 83, 83, 84, 84, 86, 87, 87, 88, 88, 91,
91, 92, 92, 93, 94, 95, 96, 96, 98, 98, 98, 100, 100, 101, 102, 103, 105, 107, 107, 107, 109, 110, 110, 112, 113, 114,
114, 116, 117, 117, 120, 121, 121, 122, 122, 122, 123, 125, 126, 127, 128, 128, 129, 129, 129, 129, 130, 130, 131,
133, 133, 134, 134, 135, 135, 138, 138, 139, 139, 141, 141, 142, 143, 145, 145, 145, 145, 146, 146, 146, 147, 147,
149, 149, 151, 152, 152, 153, 154, 155, 157, 157, 158, 158, 159, 160, 160, 161, 161, 162, 167, 167, 168, 169, 170,
170, 171, 171, 171, 174, 177, 177, 177, 179, 179, 181, 182, 183, 183, 184, 185, 185, 186, 188, 190, 190, 190, 192,
193, 194, 195, 196, 197, 198, 200, 202, 205, 207, 212, 213, 214, 214, 216, 217, 217, 219, 222, 222, 223, 223, 226,
226, 229, 229, 230, 232, 234, 234, 235, 238, 238, 245, 245, 247, 248, 250, 251, 252, 253, 253, 253, 254, 256, 256,
257, 258, 258, 259, 259, 261, 262, 263, 264, 265, 266, 266, 268, 269, 270, 272, 274, 276, 278, 280, 280, 281, 281,
282, 282, 289, 290, 291, 291, 292, 293, 294, 296, 296, 296, 297, 299, 299, 299, 300, 301, 303, 304, 304, 305, 305,
306, 309, 310, 310, 311, 312, 313, 313, 314, 316, 317, 318, 318, 319, 319, 322, 322, 322, 323, 325, 328, 328, 330,
331, 332, 334, 334, 336, 337, 337, 338, 340, 340, 341, 341, 342, 344, 345, 346, 346, 347, 350, 350, 351, 351, 352,
353, 354, 354, 355, 356, 358, 359, 359, 360, 361, 362, 362, 365, 365, 367, 367, 367, 371, 373, 374, 376, 376, 377,
382, 382, 383, 384, 385, 385, 385, 386, 387, 389, 389, 389, 390, 390, 392, 392, 392, 392, 393, 394, 395, 395, 396,
397, 398, 399, 399, 399]

CS251 Object Oriented Programming

You might also like