Oop Manual 220173107016
Oop Manual 220173107016
Oop Manual 220173107016
(GTU Code: 07) has satisfactorily completed the Practical / Tutorial work for the subject Object
Preface
Gujarat Technological University (GTU) offers a range of technical courses across various
engineering and technology disciplines. These courses are designed to provide students with a
comprehensive understanding of theoretical concepts and practical applications in their respective
fields. The practicals of courses at GTU involve hands-on experiments, projects, and assignments
that allow students to apply theoretical knowledge to real-world situations. Students work in
laboratory settings to develop their problem-solving and critical thinking skills while gaining
practical experience in their field of study.
GTU has a well-designed curriculum that includes both practical and theory in technical courses.
The curriculum is regularly updated to ensure that it stays relevant and provides students with the
skills they need to succeed in their careers. The practical and theory of technical courses are
structured in a way that allows students to apply theoretical knowledge to practical situations,
providing a holistic approach to learning.
In conclusion, GTU offers a comprehensive curriculum that includes practical and theory across
various engineering and technology disciplines. The practical provide students with hands-on
experience and allow them to apply theoretical knowledge to real-world situations, while the theory
provide students with a strong foundation in fundamental concepts and theoretical knowledge in
their respective fields. Together, the Computer Engineering Course in GTU provide students with
a well-rounded education and prepare them for successful careers in their chosen field.
By using this lab manual students can go through the relevant theory and procedure in advance
before the actual performance which creates an interest and students can have basic idea prior to
performance. This in turn enhances pre-determined outcomes amongst students. Each experiment
in this manual begins with competency, industry relevant skills, course outcomes as well as
practical outcomes (objectives). The students will also achieve safety and necessary precautions
to be taken while performing practical.
This lab manual is organized in a way that makes it easy for students to follow along with the
exercises and examples. Each lab contains a set of objectives, detailed theory/instructions, and
exercises to practice the concepts learned. The labs also include review questions to help reinforce
key concepts and prepare students for exams.
Java is one of the most popular programming languages in the world, and it is widely used in a
variety of industries, including software development, web development, and mobile app
development. By learning Core Java in this subject, students will gain a solid foundation in
programming concepts and develop the skills they need to build robust, efficient, and scalable
applications.
This lab manual covers a wide range of topics, including basic syntax, object-oriented programming
concepts, data structures, and exception handling, multi threading etc. It also includes an
introduction to GUI programming with javafx.
Object Oriented Programming 1 (3140705) Enrollment Number:
DTE’s Vision
Institute’s Vision
Institute’s Mission
Department’s Vision
Department’s Mission
The following industry relevant competency are expected to be developed in the student by
undertaking the practical work of this laboratory.
1. Will be able to start primary JAVA programming.
2. Will be able to use various IDEs like Netbeans/Ecllipse.
3. Will be able to create GUI based small application using javafx
4. Will be able to understand Advance java in future semester.
1. Students are expected to carefully listen to all the theory classes delivered by the faculty
members and understand the COs, content of the course, teaching and examination scheme,
skill set to be developed etc.
2. Students shall understand basic concept and then implement it in program.
3. Students shall develop logical skill as expected by IT industries.
4. Student shall attempt to develop Programming skills and build confidence.
5. Student shall develop the habits of evolving more ideas, innovations, skills etc. apart from
those included in scope of manual.
6. Student should develop a habit of submitting the experimentation work as per the schedule
and s/he should be well prepared for the same.
7. Student should develop a habit of working in team.
Index
(Progressive Assessment Sheet)
Total
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Practical No: 1
Aim:
1.1.Write a Program that displays Welcome to Java, Learning Java Now and
Programming is fun.
1.2. Write a program that solves the following equation and displays the value x and y:
1) 3.4x+50.2y=44.5 2) 2.1x+.55y=5.9
(Assume Cramer’s rule to solve equation
ax+by=e x=ed-bf/ad-bc
cx+dy=f y=af-ec/ad-bc )
1.3.Write a program that reads a number in meters, converts it to feet, and displays the
result.
1.4.Write a program that prompts the user to enter three integers and display the integers
in decreasing order.
1.1. Write a Program that displays Welcome to Java, Learning Java Now and
Programming is fun.
Date: 28-3-2023
Objectives: (a) To understand java’s byte code and method of running java program by setting
environment variables ‘path’ and ‘classpath’ in command prompt.
Theory:
Java's bytecode is a set of instructions that is generated by the Java compiler when it compiles a
Java program. These instructions are machine-readable and platform-independent, meaning they
can be executed on any platform that has a Java Virtual Machine (JVM) installed.
When you write a Java program, you write it in the Java programming language, which is a high-
level language. The Java compiler takes your high-level code and translates it into bytecode, which
is a low-level, machine-readable code. This bytecode can be executed on any platform that has a
JVM installed, making Java a platform-independent language.
The JVM is responsible for interpreting the bytecode and executing the instructions. It takes the
bytecode, interprets it, and executes the instructions on the underlying hardware. This means that
the same Java program can be run on any platform that has a JVM installed, without any changes
to the code.
Java bytecode is often used in server-side applications, web applications, and mobile applications.
It is also used in the development of desktop applications, games, and other software.
13
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Java is the executable that runs Java programs. When you execute a Java program, the Java virtual
machine (JVM) reads the bytecode generated by the Java compiler and executes the instructions on
the underlying hardware.
Javac, on the other hand, is the executable that compiles Java programs. It takes the source code
written in Java and translates it into bytecode that can be executed by the JVM.
To compile a Java program using Javac, you need to open a command prompt or terminal, navigate
to the directory where the Java file is located, and run the Javac command followed by the name of
the Java file. For example:
javac myfirstprg.java
This will compile the MyProgram.java file and generate a bytecode file named myfirstprg.class.
You can then run the program using the Java command:
java myfirstprg
Program:
class myfirstprg
{
Public static void main(String arg[])
{
System.out.println(“Welcome to java”);
System.out.println(“Learning Java Now”);
System.out.println(“Programming is fun”);
}
}
Observations:
Output:
Welcome to java
Learning Java Now
Programming is fun
14
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
1.2 Write a program that solves the following equation and displays the value x and y:
1) 3.4x+50.2y=44.5 2) 2.1x+.55y=5.9
(Assume Cramer’s rule to solve equation
ax+by=e x=ed-bf/ad-bc
cx+dy=f y=af-ec/ad-bc )
Date: : 28-3-2023
Objectives:
(a) To understand java’s Data type and operators.
Theory:
Data types: Java has two categories of data types: primitive data types and reference data types.
Primitive data types are built-in data types that are part of the Java language. There are eight
primitive data types in Java:
Reference data types are objects that are created from classes. They are more complex than primitive
data types, and they require more memory to store. Examples of reference data types include:
In addition to the primitive and reference data types, Java also has a special data type called "void."
This data type is used to indicate that a method does not return a value.
It's important to note that Java is a strongly-typed language, which means that each variable and
expression must have a declared data type. This helps prevent common errors that can occur when
working with data.
15
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Java has several operators that can be used to perform different operations on variables and values.
Some of the most commonly used operators in Java include:
1. Arithmetic Operators: These are used to perform arithmetic operations on variables and
values. The arithmetic operators in Java include + (addition), - (subtraction), *
(multiplication), / (division), and % (modulus).
2. Assignment Operators: These are used to assign values to variables. The assignment
operators in Java include = (simple assignment), += (add and assign), -= (subtract and
assign), *= (multiply and assign), /= (divide and assign), and %= (modulus and assign).
3. Comparison Operators: These are used to compare values and variables. The comparison
operators in Java include == (equal to), != (not equal to), > (greater than), < (less than), >=
(greater than or equal to), and <= (less than or equal to).
4. Logical Operators: These are used to combine multiple conditions and return a boolean
value. The logical operators in Java include && (logical AND), || (logical OR), and ! (logical
NOT).
5. Bitwise Operators: These are used to perform bitwise operations on binary values. The
bitwise operators in Java include & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~
(bitwise NOT), << (left shift), >> (right shift), and >>> (unsigned right shift).
6. Ternary Operator: This operator is used to assign a value to a variable based on a condition.
The ternary operator in Java is represented by the ? : symbol.
Procedure:
import java.util.Scanner;
class oop1_2 {
16
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
}
}
Observations:
17
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
1.3 Write a program that reads a number in meters, converts it to feet, and displays the
result.
1.4 Write a program that prompts the user to enter a letter and check whether a letter is
vowel or constant.
Date: 28-3-2023
Objectives:
(a) To understand input in java.
Theory:
In Java, the Scanner class is used to read input from the user through the console. Here are the
basic steps to read input using Scanner in Java:
1. Import the Scanner class at the beginning of your program using the following line of
code:
import java.util.Scanner;
2. Create an instance of the Scanner class by using the following line of code:
3. Use the various methods of the Scanner class to read input from the user. The most
commonly used methods include:
• nextLine(): Reads a line of text entered by the user until they press the Enter key.
Returns the input as a String.
• nextInt(): Reads an integer entered by the user. Returns the input as an int.
• nextDouble(): Reads a floating-point number entered by the user. Returns the input as a
double.
Procedure:
❖ 1.3
import java.util.Scanner;
class oop1_3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Value in Meters :");
double meter = input.nextDouble();
double feet = meter * 3.28084;
System.out.print(meter + " Meters = " + feet + " Feets");
}
}
18
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
❖ 1.4
import java.util.Scanner;
class oop1_4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Character : ");
char ch = input.next().charAt(0);
switch (Character.toLowerCase(ch)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
System.out.print(ch + " is vowel");
break;
default:
System.out.print(ch + " is constant");
}
}
}
Observations:
❖ 1.3
❖ 1.4
19
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
1.5 Write a program that prompts the user to enter three integers and display the integers in
decreasing order.
Date: : 28-3-2023
Competency and Practical Skills: Programming
Objectives
(a) To understand java’s Control Statements.
Theory:
Control statements are used to control flow of code. Basic control statements in java are almost
similar ti c/c++.
Selection statements:
if ..else,switch etc.
Iteration statements:
For,while,do…while etc
Jump statements:
Break,break with lable,continue and continue with lable.
Procedure:
import java.util.Scanner;
class oop1_5 {
public static void main(String[] args) {
int temp;
Scanner input = new Scanner(System.in);
System.out.print("1st Integer :");
int a = input.nextInt();
System.out.print("2nd Integer :");
int b = input.nextInt();
if (a < b) {
temp = a;
a = b;
b = temp;
}
System.out.print("3rd Integer :");
int c = input.nextInt();
if (c > b) {
if (c > a) {
temp = c;
c = b;
b = a;
a = temp;
20
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
} else {
temp = c;
c = b;
b = temp;
}
}
System.out.print("Decreasing Order :" + a + " " + b + " " + c);
}
}
Observations:
Conclusion: This experiment is used to understand basic structure of core java. And student can
start programming in java.
Quiz:
Suggested Reference:
1. Intro to Java Programming, 10th edition, Y.Daniel Liang, Pearson
2. Complete reference Core JAVA by Herbert Schildt. MC Graw Hill.
Problem Completeness
Knowledge Logic
Recognition( and accuracy Ethics (2)
Rubrics (2) Building (2) Total
2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks
21
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Practical -2
Aims:
2.1. Write a program for sorting an elements in array, and enter elements by command line
argument.
2.2.write a program to implement grow able stack.
2.3. Write a Program to print:
0
12
345
6789
Using two dimension array.
Theory:
Array:
Java support single dimension and multi dimension arrays.
Single dimension array:
Syntax:
type vari_name[];
var_name=new type[size];
Or combine
type var_name[]=new type[];
For Ex:
String myString = "this is a test";
System.out.println(myString);
Basic methods :
Programs:
2.1. Write a program for sorting an elements in array, and enter elements by command line
argument.
Date: : 04-04-2023
Procedure:
import java.util.Scanner;
class oop2_1 {
static void show(int arr[]) {
for (int i = 0; i < arr.length; i++) {
System.out.println("\tNumber " + (i + 1) + " = " + arr[i]);
}
}
System.out.println("\nInput Numbers:");
for (int i = 0; i < intArr.length; i++) {
intArr[i] = Integer.parseInt(ar[i]);
System.out.println("\tNumber " + (i + 1) + " = " + intArr[i]);
}
if (choice == 1) {
System.out.println("\nNumbers in Ascending Order:");
for (int i = 0; i < intArr.length; i++) {
for (int j = 0; j < i; j++) {
if (intArr[i] < intArr[j]) {
intArr[i] += intArr[j];
intArr[j] = intArr[i] - intArr[j];
intArr[i] -= intArr[j];
}
23
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
}
}
show(intArr);
} else if (choice == 2) {
System.out.println("\nNumbers in Descending Order:");
for (int i = 0; i < intArr.length; i++) {
for (int j = 0; j < i; j++) {
if (intArr[i] > intArr[j]) {
intArr[i] += intArr[j];
intArr[j] = intArr[i] - intArr[j];
intArr[i] -= intArr[j];
}
}
}
show(intArr);
} else {
System.out.println("\tInvalid Choice...!");
}
}
}
Observations:
24
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
2.2 write a program to implement grow able stack.
Date: :04-04-2023
Procedure:
import java.util.Scanner;
class pr2_2{
static int MAX = 5;
static int stack[] = new int[MAX];
static int top = -1;
static int LEN = 0;
static void push(int num){
if(top == LEN - 1){
stack = resizeArray(stack);
}
top++;
stack[top] = num;
}
static void pop(){
if (top == -1){
System.out.println("\t--> Stack is empty...");
}
else{
int item;
item = stack[top];
top--;
System.out.println("\t--> " + item +" was popped from the stack...");
}
}
static void displayStack(){
if(top == -1){
System.out.println("\t--> Stack is empty...");
}
else{
int i;
for(i = 0; i <= top; i++){
System.out.println("\tElement = " + (i+1) + " | Index = " + i + " | Value = " + stack[i]);
}
}
}
static int[] resizeArray(int stack[]){
int[] newStack = new int[LEN + MAX];
for(int i = 0; i < LEN; i++){
newStack[i] = stack[i];
}
LEN += MAX;
return newStack;
}
public static void main(String ar[]){
int choice;
25
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Scanner s = new Scanner(System.in);
do{
System.out.print("\nStack Operations:\n1. Press 1 for Push\n2. Press 2 for Pop\n3. Press 3 for
Display\n4. Exit\n\nEnter your choice: ");
choice = s.nextInt();
switch (choice){
case 1: System.out.println("(Push operation selected)");
System.out.print("\tPlease enter a number: ");
int num = s.nextInt();
push(num);
System.out.println("(Push operation is completed)");
break;
case 2: System.out.println("(Pop operation selected)");
pop();
System.out.println("(Pop operation is completed)");
break;
case 3: System.out.println("(Display operation selected)");
displayStack();
break;
case 4: System.out.println("Stack operations menu is closed...!");
break;
default: System.out.println("Please select an appropriate choice...!");
}
}while(choice != 4);
}
}
Observations:
26
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
2.3 Write a Program to print:
0
12
345
6789
Using two dimension array.
Date: : 04-04-2023
Procedure:
public class oop2_2 {
public static void main(String[] args) {
int rows = 4;
int[][] arr = new int[rows][];
int count = 0;
2.4. Write a program for calculator to accept an expression as a string in which the
27
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Operands and operator are separated by spaces. For ex: 3 + 4.
Date: :04-04-2023
Procedure:
import java.util.Scanner;
class oop2_4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Equation : ");
String string = input.nextLine();
String a = string.replaceAll(" ", "");
if (a.length() < 3) {
System.out.println(
"Minimum 2 Opearator and 1 Opearand Required");
System.exit(0);
}
int result = 0;
int i = 0;
while (a.charAt(i) != '+' && a.charAt(i) != '-' && a.charAt(i) != '*' && a.charAt(i) != '/') {
i++;
}
switch (a.charAt(i)) {
case '+':
result = Integer.parseInt(a.substring(0, i)) + Integer.parseInt(a.substring(i + 1, a.length()));
break;
case '-':
result = Integer.parseInt(a.substring(0, i)) - Integer.parseInt(a.substring(i + 1, a.length()));
break;
case '*':
result = Integer.parseInt(a.substring(0, i)) * Integer.parseInt(a.substring(i + 1, a.length()));
break;
case '/':
result = Integer.parseInt(a.substring(0, i)) / Integer.parseInt(a.substring(i + 1, a.length()));
break;
}
Observations:
28
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Quiz:
2. Describe two dimension Array in java.
3. Describe Short Circuit Operators in java( && and ||)
4. Describe >> and << operators.
5. Describe any five methods of String class.
Suggested Reference:
Problem Completeness
Knowledge Logic
Recognition( and accuracy Ethics (2)
Rubrics (2) Building (2) Total
2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks
29
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Practical- 3
Aims:
3.1. Write a program to perform method overloading of area method to find area of rectangle and
square
3.2. Do above program using constructor overloading
3.3. Create a class student with necessary properties, methods and constructor. Overload a
function name search in this class which allows us to search student based on roll number,
name and city.
Objectives:
To understand and implement method class, object , Method overloading , constructor overloading
Theory:
Syntax:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
Object:
The new operator dynamically allocates memory for an object. It has this general form:
Constructor:
A constructor initializes an object immediately upon creation. It has the same name as the class in
which it resides and is syntactically similar to a method. Once defined, the constructor is
automatically called immediately after the object is created, before the new operator completes.
30
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Constructors look a little strange because they have no return type, not even void. This is because
the implicit return type of a class’ constructor is the class type itself.
Syntax:
classname()
{
//Body of Constructor;
}
For ex:
Here mybox1 is class box object. new Box( ) is calling the Box( ) constructor. When you do not
explicitly define a constructor for a class, then Java creates a default constructor for the class.
For ex:
class Box
{
double depth;
Box(double d)
{
depth=d;
}
}
Overloading:
Method overloading is an example of Polymorphism. Methods can have same name but it differ in
terms of arguments either number of arguments are different or types of arguments are different.
For Ex:
void test(int a)
{
}
void test(int a,int b)
{
}
Programs:
3.1. Write a program to perform method overloading of area method to find area of
rectangle and square
Date: 04-04-2023
Procedure:
import java.util.Scanner;
32
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
3.2. Do above program using constructor overloading
Date: 04-04-2023
Procedure:
import java.util.Scanner;
Observations:
33
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
3.3. Create a class student with necessary properties, methods and constructor. Overload a
function name search in this class which allows us to search student based on roll
number, name and city.
Date: 04-04-2023
Procedure:
class Student {
String name, enrNo, branch, city, contact;
Student(String name, String enrNo, String branch, String city, String contact) {
this.name = name;
this.enrNo = enrNo;
this.branch = branch;
this.city = city;
this.contact = contact;
}
String getName() {
return this.name;
}
String getEnrNo() {
return this.enrNo;
}
String getBranch() {
return this.branch;
}
String getCity() {
return this.city;
}
String getContact() {
return this.contact;
}
void showData() {
System.out.println("\n\n~~~~~~:: Student Data ::~~~~~~");
System.out.println("Name\t\t: " + this.getName());
System.out.println("Enrollment No.\t: " + this.getEnrNo());
System.out.println("Branch\t\t: " + this.getBranch());
System.out.println("City\t\t: " + this.getCity());
System.out.println("Contact\t\t: " + this.getContact());
}
34
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
this.showData();
} else {
System.out.println("\n\nSorry, Could not find data...!");
}
}
class oop3_3 {
public static void main(String ar[]) {
Student st1 = new Student("Parth Bhavsar", "220173107001", "CE", "Ahmedabad",
"7621088674");
Student st2 = new Student("Jeet Rathod", "220173107029", "CE", "Gandhinagar",
"7894561230");
Student st3 = new Student("Kavish Panchal", "220173107016", "CE", "Ahmedabad",
"9876543210");
st1.search("Parth Bhavsar");
st2.search("Jeet Rathod", "220173107029");
st3.search("Kavish Panchal", "220173107016", "Ahmedabad");
st2.search("Kavish Panchal");
st3.search("Parth Bhavsar", "220173107016");
st1.search("Jeet Rathod", "220173107016", "Ahmedabad");
}
}
35
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Observations:
36
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Conclusion: This experiment is used to understand and implement class,object ,
constructor,Method and constructor Overloading.
Quiz:
1. Describe Method Overloading in java.
2. Describe class and object in java
Suggested Reference:
Problem Completeness
Knowledge Logic
Recognition( and accuracy Ethics (2)
Rubrics (2) Building (2) Total
2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks
37
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Practical- 4
Aims:
4.1 write a program that create following : a inherited by b ,b inherited by c and c is inherited
by d. a has one variable b has two and c has 3 variables. Use constructor and super to
initialized the variables of classes.
4.2 Write a Java program that combine several classes and interfaces the abstract class robot
has subclass name robotA, robotB, robotC. Class robotA1 extends robotA. Class robotB1
and robotB2 extends robotB. Class robotC1 extends robotC. The locomotion interface
declares three methods has forward , reverse and stop. It is implemented by class robotB
and robotC. The sound interface declares one method named beep and it is implemented
by robotA1,robotB1 and robotC. Defined all class and implement interface as specified
than invoked beep method of all class object that are of type sound.
4.3 write a program that has abstract class dim which has a two variable dim1,dim2. triangle
and rectangle are subclass of dim. implement dynamic method dispatch by creating
reference of dim.
Objectives:
To understand and implement Inheritance, abstract class ,Method Overriding and Dynamic method
dispatched and interface.
Theory:
Inheritance:
Object-oriented programming allows you to define new classes from existing classes.This is called
inheritance. it allows the creation of hierarchical classifications. Using inheritance, you can create
a general class that defines traits common to a set of related items. This class can then be inherited
by other, more specific classes, each adding those things that are unique to it. In the terminology of
Java, a class that is inherited is called a superclass. The class that does the inheriting is called a
subclass. Therefore, a subclass is a specialized version of a superclass. ‘extends’ keyword is used
for inheriting super class.
Use of ‘super’:
1. Used to call super class constructor.
2. Used to access variables of super class(like this)
Syntax:
Class subclassname extends superclassname
{
}
Method Overrriding:
A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to modify
the implementation of a method defined in the superclass. This is referred to as method overriding.
So subclass has method with same name and signature as in superclass but the code is different. It
is different than Method overloading.
38
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Overloading means to define multiple methods with the same name but different
signatures.Overriding means to provide a new implementation for a method in the subclass.
Superclass reference variable can refer to subclass object. This fact is used to implement runtime
polymorphism. We can create superclass object and assign subclass object to it. When we call
overridden method using super class object , it will call the version of method written in that
subclass which object is assigned to superclass object.
Sometimes Methods written in superclass may not have meanings. But we have to write it in super
class in order to override it. Such method can be declared as abstract method abstract method has
no body in super class. The class that contains at least a abstract method must be declared as an
abstract class. We can not create object of abstract class but we can create reference of it.
For Ex:
abstract class Dimension
{
abstract double area();
}
Interface:
In Java, an interface is a type that defines a set of method signatures that a class must implement if
it wants to use that interface. An interface is similar to a class, but it cannot be instantiated on its
own, and all of its methods must be implemented by a class that implements the interface.
To define an interface in Java, the "interface" keyword is used, followed by the name of the interface
and the method signatures that it defines.
For example:
Classes that implement an interface must use the "implements" keyword and provide an
implementation for all of the methods defined in the interface.
For example:
public class MyClass implements MyInterface
{
public void myMethod() {
// Implementation goes here
}
39
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Interfaces can also be used to achieve polymorphism, allowing multiple classes that implement the same
interface to be used interchangeably.
Programs:
Procedure:
class A {
int aVal;
class B extends A {
int bVal1;
int bVal2;
class C extends B {
int cVal1;
int cVal2;
int cVal3;
public C(int aVal, int bVal1, int bVal2, int cVal1, int cVal2, int cVal3) {
super(aVal, bVal1, bVal2);
this.cVal1 = cVal1;
this.cVal2 = cVal2;
this.cVal3 = cVal3;
}
}
class D extends C {
public D(int aVal, int bVal1, int bVal2, int cVal1, int cVal2, int cVal3) {
super(aVal, bVal1, bVal2, cVal1, cVal2, cVal3);
}
}
40
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
D d = new D(1, 2, 3, 4, 5, 6);
System.out.println("D.aVal = " + d.aVal);
System.out.println("D.bVal1 = " + d.bVal1);
System.out.println("D.bVal2 = " + d.bVal2);
System.out.println("D.cVal1 = " + d.cVal1);
System.out.println("D.cVal2 = " + d.cVal2);
System.out.println("D.cVal3 = " + d.cVal3);
}
}
Observations:
41
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
4.2. Write a Java program that combine several classes and interfaces the abstract class robot
has subclass name robotA, robotB, robotC. Class robotA1 extends robotA. Class robotB1 and
robotB2 extends robotB. Class robotC1 extends robotC. The locomotion interface declares
three methods has forward , reverse and stop. It is implemented by class robotB and robotC.
The sound interface declares one method named beep and it is implemented by
robotA1,robotB1 and robotC. Defined all class and implement interface as specified than
invoked beep method of all class object that are of type sound.
Procedure:
interface Locomotion {
void forward();
void reverse();
void stop();
}
interface Sound {
void beep();
}
@Override
public void forward() {
System.out.println("Moving forward as RobotB");
}
@Override
public void reverse() {
System.out.println("Moving reverse as RobotB");
}
@Override
public void stop() {
42
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
System.out.println("Stopping as RobotB");
}
@Override
public void beep() {
System.out.println("Beeping as RobotB");
}
}
@Override
public void forward() {
System.out.println("Moving forward as RobotC");
}
@Override
public void reverse() {
System.out.println("Moving reverse as RobotC");
}
@Override
public void stop() {
System.out.println("Stopping as RobotC");
}
@Override
public void beep() {
System.out.println("Beeping as RobotC");
}
}
robotA1.beep();
robotB1.beep();
robotB2.beep();
robotC1.beep();
}
}
Observations:
44
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
4.3. write a program that has abstract class dim which has a two variable dim1,dim2. triangle
and rectangle are subclass of dim. implement dynamic method dispatch by creating
reference of dim.
Procedure:
import java.util.Scanner;
double area() {
return 0.5 * dim1 * dim2;
}
}
double area() {
return dim1 * dim2;
}
}
if (shapeType.equals("triangle")) {
System.out.println("Enter the base of the triangle: ");
double base = scanner.nextDouble();
System.out.println("Enter the height of the triangle: ");
double height = scanner.nextDouble();
45
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
shape = new Triangle(base, height);
System.out.println("Area of triangle is " + shape.area());
} else if (shapeType.equals("rectangle")) {
System.out.println("Enter the width of the rectangle: ");
double width = scanner.nextDouble();
System.out.println("Enter the height of the rectangle: ");
double height = scanner.nextDouble();
shape = new Rectangle(width, height);
System.out.println("Area of rectangle is " + shape.area());
} else {
System.out.println("Invalid shape type.");
}
scanner.close();
}
}
Observations:
46
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Quiz:
1. Compare Method Overloading and Method Overriding.
2. Describe Dynamic Method Dispatched.
3. Write about abstract Class and Method.
Suggested Reference:
Javapoint.com
W3school.com
Problem Completeness
Knowledge Logic
Recognition( and accuracy Ethics (2)
Rubrics (2) Building (2) Total
2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks
47
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Practical- 5
Aims:
5.7 Write a java program to find solution of quadratic equation. Take care of divide by
zero error and other arithmetic exceptions
5.8 Write a program in which main() call a(),a() call b(),b() call c(),c() call d(),d()
genarates ArrayIndexOutOfBoundException. c and d catch throw the Exception. b()
handle an Exception. Each method contain finally.
5.9 Write a program to get value of radius through keyboard and calculate area of circle.
Take care of InputMismatchException.
5.10 Write a program to create an array of 10 integers. Get value of those 10 integers
using console. Now ask for an index of array through keyboard then divide the array
into two from that index. Take care of array index out of bound exception. Also handle
InputMismatchException.
5.11 Create a class name student which stores information like roll number, name,
phone number, address, course etc. Write a function which accepts an object of student
to add a new student in existing list of student. While adding check for roll number.
The roll number should be in 3 digit. Implement this check using user define exception
class
5.12 Write the bin2Dec (string binary String) method to convert a binary string into a
decimal number. Implement the bin2Dec method to throw a NumberFormatException
if the string is not a binary string.
Theory:
An exception is a run-time error. A Java exception is an object that describes an exceptional (that
is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an
object representing that exception is created and thrown in the method that caused the error. That
method may choose to handle the exception itself, or pass it on. Either way, at some point, the
exception is caught and processed.
Java exception handling is managed via five keywords: try, catch, throw, throws,and finally
Program statements that you want to monitor for exceptions are contained within a try block. If an
exception occurs within the try block, it is thrown. Your code can catch this exception (using catch)
and handle it in some rational manner. System-generated exceptions are automatically thrown by
the Java run-time system. To manually throw an exception, use the keyword throw. Any exception
that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely
must be executed before a method returns is put in
a finally block.
Syntax:
48
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
finally {
// block of code to be executed before try block ends
}
Programs:
5.1 Write a java program to find solution of quadratic equation. Take care of divide by zero
error and other arithmetic exceptions
Procedure:
import java.util.Scanner;
double discriminant = b * b - 4 * a * c;
if (a == 0) {
System.out.println("The given equation is not a quadratic equation.");
} else if (discriminant < 0) {
System.out.println("The given equation has no real solutions.");
} else {
try {
double x1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double x2 = (-b - Math.sqrt(discriminant)) / (2 * a);
scanner.close();
}
}
Observations:
50
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
5.2. Write a program in which main() call a(),a() call b(),b() call c(),c() call d(),d() genarates
ArrayIndexOutOfBoundException. c and d catch throw the Exception. b() handle an
Exception. Each method contain finally.
Procedure:
public class oop5_2{
public static void main(String[] args) {
try {
a();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught in main(): " + e.getMessage());
}
}
Observations:
52
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
5.3 Write a program to get value of radius through keyboard and calculate area of circle.
Take care of InputMismatchException.
Procedure:
import java.util.InputMismatchException;
import java.util.Scanner;
try {
System.out.print("Enter the radius of the circle: ");
double radius = scanner.nextDouble();
scanner.close();
}
}
Observations:
53
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
5.4 Write a program to create an array of 10 integers. Get value of those 10 integers using
console. Now ask for an index of array through keyboard then divide the array into two from
that index. Take care of array index out of bound exception. Also handle
InputMismatchException.
Procedure:
import java.util.Scanner;
import java.util.InputMismatchException;
try {
for (int i = 0; i < 10; i++) {
System.out.print("Enter the value for index " + i + ": ");
arr[i] = scanner.nextInt();
}
System.out.println("Subarray 1: ");
for (int i = 0; i < sa1.length; i++) {
System.out.print(sa1[i] + " ");
}
System.out.println("\nSubarray 2: ");
for (int i = 0; i < sa2.length; i++) {
System.out.print(sa2[i] + " ");
54
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid index: " + e.getMessage());
} catch (InputMismatchException e) {
System.out.println("Invalid input: " + e.getMessage());
}
scanner.close();
}
}
Observations:
55
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
5.5 Create a class name student which stores information like roll number, name, phone
number, address, course etc. Write a function which accepts an object of student to add a new
student in existing list of student. While adding check for roll number. The roll number should
be in 3 digit. Implement this check using user define exception class.
Procedure:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Student {
private String rollNumber;
private String name;
private String phoneNumber;
private String address;
private String course;
public Student(String rollNumber, String name, String phoneNumber, String address, String
course) {
this.rollNumber = rollNumber;
this.name = name;
this.phoneNumber = phoneNumber;
this.address = address;
this.course = course;
}
class StudentDatabase {
private List<Student> students = new ArrayList<>();
students.add(student);
System.out.println("Student added successfully.");
}
while (true) {
System.out.print("\nEnter 1 to add a new student, 2 to quit: ");
int choice = scanner.nextInt();
if (choice == 2) {
break;
}
try {
Student student = new Student(rollNumber, name, phoneNumber, address, course);
studentDatabase.addStudent(student);
} catch (InvalidRollNumberException e) {
System.out.println("Error: " + e.getMessage());
}
}
System.out.println("\nStudent list:");
for (Student student : students) {
System.out.println("Roll number: " + student.getRollNumber());
System.out.println("Name: " + student.getName());
System.out.println("Phone number: " + student.getPhoneNumber());
System.out.println("Address: " + student.getAddress());
System.out.println("Course: " + student.getCourse());
System.out.println();
}
scanner.close();
}
}
Observations:
5.6 Write the bin2Dec (string binary String) method to convert a binary string into a decimal
number. Implement the bin2Dec method to throw a NumberFormatException if the string is
not a binary string.
Procedure:
import java.util.Scanner;
try {
int decimalNumber = bin2Dec(binaryString);
System.out.println("Binary string " + binaryString + " is equivalent to decimal number " +
decimalNumber);
} catch (NumberFormatException e) {
System.out.println("Error: " + e.getMessage());
}
scanner.close();
}
59
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Observations:
Quiz:
Suggested Reference:
Javapoint.com
W3school.com
Problem Completeness
Knowledge Logic
Recognition( and accuracy Ethics (2)
Rubrics (2) Building (2) Total
2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks
60
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Practical- 6
Aims:
6.1 Write a Program for multithreading that finds prime number in the range provided by user
in command line argument depending upon range creates sufficient number of child thread.
6.2 Write a program that demonstrate thread priority four threads each with a different priority
level then the other are started objects and not the behave of each Thread
6.3 Write a program that demonstrate use of Executor Framework in mutitasking.
6.4 Write a program for handling producer consumer problem.
Objectives:
Theory:
A program may consist of many tasks that can run concurrently. A thread is the flow of execution,
from beginning to end, of a task.
A thread provides the mechanism for running a task. With Java, you can launch multiple threads
from a program concurrently. These threads can be executed simultaneously in multiprocessor
Systems
Thread pools:
Starting a new thread for each task could limit throughput and cause poor performance. Using a
thread pool is an ideal way to manage the number of tasks executing concurrently. Java provides
the Executor interface for executing tasks in a thread pool and the ExecutorService interface for
managing and controlling tasks. ExecutorService is a subinterface of Executor
Programs:
6.1. Write a Program for multithreading that finds prime number in the range provided by
user in command line argument depending upon range creates sufficient number of child
thread.
Procedure:
//Write program here
Observations:
//Write program output here
61
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
6.2. Write a program that demonstrate thread priority four threads each with a different
priority level then the other are started objects and not the behave of each Thread
Procedure:
//Write program here
Observations:
//Write program output here
Procedure:
//Write program here
Observations:
//Write program output here
Procedure:
//Write program here
Observations:
//Write program output here
Quiz:
Suggested Reference:
62
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Rubric wise marks obtained:
Problem Completeness
Knowledge Logic
Recognition( and accuracy Ethics (2)
Rubrics (2) Building (2) Total
2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks
63
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Practical- 7
Aims:
7.1 Write a program that creates an Array List and adds a Loan object , a Date object , a string,
and a Circle object to the list, and use a loop to display all elements in the list by invoking
the object’s to String() method.
7.2 Using list perform following operation on it in java program. (use ArrayList and
LinkedList )
7.2.1 Creating a new list
7.2.2 Basic operations.
7.2.3 Iterating over a list
7.2.4 Searching for an element in a list
7.2.5 Sorting a list
7.2.6 Copying one list into another
7.2.7 Shuffling elements in a list
7.2.8 Reversing elements in a list
7.2.9 Extracting a portion of a list
7.2.10 Converting between Lists and arrays
7.2.11 List to Stream
7.2.12 Concurrent lists.
7.3 Write a java program to evaluate arithmetic operation using stack.
7.4 Implement a java program to show various operation of queue.
7.5 Define MYPriorityQueue class that extends Priority Queue to implement the Cloneable
interface and implement the clone() method to clone a priority queue
7.6 Create a generic class GenericStack<E> with all methods of stack. And create two object,
first object is for String values and second object is for Double values.
7.7 Create a Generic Method sort which will sort an array of Comparable objects. The objects
are instances of the Comparable interface, and they are compared using the compareTo
method. To test the method, the program sorts an array of integers, an array of double
numbers, an array of characters, and an array of strings.
7.8 In prg 7.7 create a newclass which has method max() that will take GenericStack<> object
as argument using bounded wildcard (? Extends T) where T can be of type Number. And
it will find max number from stack.
Objectives:
To make use of ArrayList class and other classes.
To understand and implements List, Stacks, Queues ,Priority Queues etc
To understand and use Generics.
64
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Theory:
ArrayList:
ArrayList class[1]
Ex:
ArrayList<String> cities = new ArrayList<String>();
Collection :
The Collection interface defines the common operations for lists, vectors, stacks, queues, priority
queues, and sets.
65
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
List of Methods[1]
The Collection interface contains the methods for manipulating the elements in a collection, and
you can obtain an iterator object for traversing elements in the collection.Each collection is Iterable.
You can obtain its Iterator object to traverse all the elements in the collection. Iterator is a classic
design pattern for walking through a data structure without having to expose the details of how data
is stored in the data structure.
66
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
The Collection interface extends the Iterable interface. The Iterable interface defines the iterator
method, which returns an iterator. The Iterator interface provides a uniform way for traversing
elements in various types of collections.
Lists:
The List interface extends the Collection interface and defines a collection for storing elements in
a sequential order. To create a list, use one of its two concrete classes: ArrayList or LinkedList.
List interface[1]
ListIterator interface[1]
LinkedList class:
LinkedList is a linked list implementation of the List interface. In addition to implementing the
List interface, this class provides the methods for retrieving, inserting, and removing elements
from both ends of the list, as shown below[1]:
67
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Comparator can be used to compare the objects of a class that doesn’t implement Comparable.
Several classes in the Java API, such as String, Date, Calendar,BigInteger, BigDecimal, and all the
numeric wrapper classes for the primitive types,implement the Comparable interface. The
Comparable interface defines the compareTo method, which is used to compare two elements of
the same class that implement the Comparable interface.
Returns a negative value if element1 is less than element2, a positive value if element1 is greater
than element2, and zero if they are equal.
Vector is a subclass of AbstractList, and Stack is a subclass of Vector in the Java API.
Vector is the same as ArrayList, except that it contains synchronized methods for accessing and
modifying the vector. Synchronized methods can prevent data corruption when a vector is accessed
and modified by two or more threads concurrently.
68
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Vector class[1]
Stack class:
Stack class[1]
Queue interface:
69
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Queue interface[1]
Priority Queue:
Generics:
Generics enable you to detect errors at compile time rather than at runtime.
Java has allowed you to define generic classes, interfaces, and methods since JDK 1.5. Several
interfaces and classes in the Java API were modified using generics. For example, prior to JDK 1.5
the java.lang.Comparable interface was defined as shown in Figure 19.1a, but since JDK 1.5 it is
modified as shown below:
Here, <T> represents a formal generic type, which can be replaced later with an actual concrete
type. Replacing a generic type is called a generic instantiation. By convention, a single capital letter
such as E or T is used to denote a formal generic type.
Generic class:
A generic type can be defined for a class or interface. A concrete type must be specified when
using the class to create an object or using the class or interface to declare a reference variable.
For ex:
70
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
public E peek() {
return list.get(getSize() - 1);
}
public E pop() {
E o = list.get(getSize() - 1);
list.remove(getSize() - 1);
return o;
}
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public String toString() {
return "stack: " + list.toString();
}
}
Generic Metthod:
A generic type can be defined for a static method.You can define generic interfaces (e.g., the
Comparable interface in Figure 19.1b) and classes (e.g., the GenericStack class in Listing 19.1).
You can also use generic types to define generic methods. For example, Listing 19.2 defines a
generic method print (lines 10–14) to print an array of objects.
To declare a generic method, you place the generic type <E> immediately after the keyword static
in the method header.
You can use unbounded wildcards, bounded wildcards, or lower-bound wildcards to specify a range
for a generic type.
The first form, ?, called an unbounded wildcard, is the same as ? extends Object. The second form,
? extends T, called a bounded wildcard, represents T or a subtype of T. The third form, ? super T,
called a lower-bound wildcard, denotes T or a supertype of T.
Programs:
7.1 Write a program that creates an Array List and adds a Loan object , a Date object , a
string, and a Circle object to the list, and use a loop to display all elements in the list by
invoking the object’s to String() method.
Procedure:
71
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
//Write program here
Observations:
//Write program output here
7.2 Using list perform following operation on it in java program. (use ArrayList and
LinkedList )
Procedure:
//Write program here
Observations:
//Write program output here
Procedure:
//Write program here
Observations:
//Write program output here
Procedure:
//Write program here
Observations:
72
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
//Write program output here
7.5 Define MYPriorityQueue class that extends Priority Queue to implement the Cloneable
interface and implement the clone() method to clone a priority queue
Procedure:
//Write program here
Observations:
//Write program output here
7.6 Create a generic class GenericStack<E> with all methods of stack. And create two object,
first object is for String values and second object is for Double values.
Procedure:
//Write program here
Observations:
//Write program output here
7.7 Create a Generic Method sort which will sort an array of Comparable objects. The
objects are instances of the Comparable interface, and they are compared using the
compareTo method. To test the method, the program sorts an array of integers, an array
of double numbers, an array of characters, and an array of strings.
Procedure:
//Write program here
Observations:
//Write program output here
7.8 In practical 7.7 create a newclass which has method max() that will take GenericStack<>
object as argument using bounded wildcard (? Extends T) where T can be of type
Number. And it will find max number from stack.
Procedure:
73
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
//Write program here
Observations:
//Write program output here
Quiz:
1. Write methods of collection.
2. Describe wildcard Generic types with example.
3. Describe ArrayList class with example.
Suggested Reference:
1. 1.Intro to Java Programming, 10th edition, Y.Daniel Liang, Pearson
2. Complete reference Core JAVA by Herbert Schildt. MC Graw Hill.
Problem Completeness
Knowledge Logic
Recognition( and accuracy Ethics (2)
Rubrics (2) Building (2) Total
2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks
74
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Practical- 8
Aims:
8.1 Demonstrate test time and removed time required for hash set,tree set,an array set,linked
list.
8.2 Write a Java program to find the longest word in a text file.
8.3 Write a program to create a file name 123.txt, if it does not exist. Append a new data to
it if it already exist. write 150 integers created randomly into the file using Text I/O.
Integers are separated by space.
8.4 Write a program that reads words from a text file and displays all the nonduplicate words
in descending order.The text file is passed as a command-line argument .
8.5 Write a program to find whether a String is palindrome or not by using recursive helper
method.
Objectives:
Theory:
Sets:
You can create a set using one of its three concrete classes: HashSet, LinkedHashSet, or TreeSet.
The Set interface extends the Collection interface.It does not introduce new methods or constants,
but it stipulates that an instance of Set contains no duplicate elements. The concrete classes that
implement Set must ensure that no duplicate elements can be added to the set. That is, no two
elements e1 and e2 can be in the set such that e1.equals(e2) is true.
The HashSet class is a concrete class that implements Set. You can create an empty hash set using
its no-arg constructor or create a hash set from an existing collection.
By default,the initial capacity is 16 and the load factor is 0.75. If you know the size of your set, you
can specify the initial capacity and load factor in the constructor. Otherwise, use the default
setting.The load factor is a value between 0.0 and 1.0.
The load factor measures how full the set is allowed to be before its capacity is increased. When
the number of elements exceeds the product of the capacity and load factor, the capacity is
automatically doubled. For example, if the capacity is 16 and load factor is 0.75, the capacity will
be doubled to 32 when the size reaches 12 (16*0.75 = 12). A higher load factor decreases the space
costs but increases the search time. Generally, the default load factor 0.75 is a good tradeoff
between time and space costs.
A HashSet can be used to store duplicate-free elements. For efficiency, objects added to a hash set
need to implement the hashCode method in a manner that properly disperses the hash code.
Linked Hash Set:
75
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
LinkedHashSet extends HashSet with a linked-list implementation that supports an ordering of the
elements in the set. The elements in a HashSet are not ordered, but the elements in a LinkedHashSet
can be retrieved in the order in which they were inserted into the set. A LinkedHashSet can be
created by using one of its four constructors.
TreeSet:
SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted.
Additionally, it provides the methods first() and last() for returning the first and last elements in the
set, and headSet(toElement) and tailSet(fromElement) for returning a portion of the set whose
elements are less than toElement and greater than or equal to fromElement, respectively.
Methods of sets[1]
Maps:
You can create a map using one of its three concrete classes: HashMap, LinkedHashMap, or
TreeMap.
A map is a container object that stores a collection of key/value pairs. It enables fast retrieval,
deletion, and updating of the pair through the key. A map stores the values along with the keys.
The keys are like indexes. In List, the indexes are integers. In Map, the keys can be any objects.
A map cannot contain duplicate keys. Each key maps to one value. A key and its corresponding
value form an entry stored in a map, as shown in Figure a. Figure b shows a map in which each
entry consists of a Social Security number as the key and a name as the value.
76
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Maps[1]
Maps[1]
Text and Binary I/O:
Java provides many classes for performing text I/O and binary I/O.
Text I/O
Java provides many classes for performing text I/O and binary I/O.
Ex:
PrintWriter output = new PrintWriter("temp.txt");
output.print("Java 101"); //used to write in file.
output.close();
An input class contains the methods to read data, and an output class contains the methods to write
data.
77
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Binary I/O:
Recursion is a technique that leads to elegant solutions to problems that are difficult to program
using simple loops.
A recursive method is one that invokes itself. In some cases, recursion enables you to create an
intuitive, straightforward, simple solution to a problem.
Sometimes you can find a solution to the original problem by defining a recursive function to a
problem similar to the original problem. This new method is called a recursive helper method. The
original problem can be solved by invoking the recursive helper method.
Programs:
8.1 Demonstrate test time and removed time required for hash set,tree set,an array
set,linked list.
Procedure:
//Write program here
Observations:
//Write program output here
8.2 Write a Java program to find the longest word in a text file.
Procedure:
//Write program here
Observations:
//Write program output here
78
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
8.3 Write a program to create a file name 123.txt, if it does not exist. Append a new data to it
if it already exist. write 150 integers created randomly into the file using Text I/O. Integers
are separated by space.
Procedure:
//Write program here
Observations:
//Write program output here
8.4 Write a program that reads words from a text file and displays all the nonduplicate words
in descending order.The text file is passed as a command-line argument .
Procedure:
//Write program here
Observations:
//Write program output here
8.5 Write a program to find whether a String is palindrome or not by using recursive helper
method.
Quiz:
1. Differentiate Text I/o and Binary I/O
2. Differentiate Recursion and Iteration.
3. Describe Random access file.
Suggested Reference:
79
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Problem Completeness
Knowledge Logic
Recognition( and accuracy Ethics (2)
Rubrics (2) Building (2) Total
2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks
80
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Practical- 9
Aims:
9.1 Write a program that moves a circle up, down, left or right using arrow keys.
9.2 Write a program that displays the color of a circle as red when the mouse button is pressed and
as blue when the mouse button is released.
9.3 Write a GUI program that use button to move the message to the left and right and use the radio
button to change the color for the message displayed.
Objectives:
Theory:
JavaFX is a Java library used to develop desktop applications with rich graphical user interfaces
(GUIs). It was introduced as a replacement for Swing in Java 8 and is now the standard GUI library
for Java.
JavaFX provides a wide range of GUI controls, including buttons, text fields, labels, menus, ables,
and many others. It also includes support for multimedia and 3D graphics, making it a powerful
platform for developing applications with advanced user interfaces.
One of the key features of JavaFX is its ability to use CSS to style the user interface. This makes it
easy to customize the look and feel of the application to match specific branding or design
requirements.
JavaFX can be used with a variety of development environments, including Eclipse, IntelliJ IDEA,
and NetBeans. It is also supported by many third-party tools and libraries, making it a popular
choice for developing desktop applications in Java.
The abstract javafx.application.Application class defines the essential framework for writing
JavaFX programs.
For Ex:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args)
{
Application.launch(args);
}
}
The launch method (line 22) is a static method defined in the Application class for launching a
stand-alone JavaFX application. The main method (lines 21–23) is not needed if you run the
program from the command line. It may be needed to launch a JavaFX program from an IDE with
a limited JavaFX support. When you run a JavaFX application without a main method, JVM
automatically invokes the launch method to run the application. The main class overrides the start
method defined in javafx.application.Application. The start method normally places UI controls(in
above example it is button) in a scene and displays the scene in a stage. A Stage object is a window.
82
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Color Class:
Color class[1]
Font class:
Font class[1]
Image and ImageView classes:
Image Class[1]
83
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
ImageView class[1]
Layout Panes:
JavaFX provides many types of panes for automatically laying out nodes in a desired location and
size.
JavaFX provides many types of panes for organizing nodes in a container, as shown below [1].
Shapes:
JavaFX provides many shape classes for drawing texts, lines, circles, rectangles,ellipses, arcs,
polygons, and polylines.
The Shape class is the abstract base class that defines the common properties for all shapes.
84
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Event handling in JavaFX refers to the process of responding to user-generated events, such as
mouse clicks, button presses, and key presses, in a JavaFX application.
1. Registering an event handler: An event handler is a piece of code that is executed in response
to a specific event. To register an event handler in JavaFX, you typically use the
setOn<Event>() method of a Node object, where <Event> is the type of event you want to
handle (e.g. setOnMouseClicked() for handling mouse clicks).
2. Implementing the event handling code: Once you have registered an event handler, you need
to implement the code that should be executed when the event occurs. This code typically
resides in a method that takes an event object as its argument.
3. Handling the event: When the event occurs, the registered event handler is invoked, and the
event object is passed to the method that implements the event handling code. The code in
this method should then perform the necessary actions in response to the event.
Some common event types in JavaFX include MouseEvent, KeyEvent, ActionEvent, and
WindowEvent, among others. Additionally, JavaFX provides a variety of convenience methods and
classes for working with events, such as the EventHandler interface, which defines a standard
interface for handling events in JavaFX.
[1]
An event object contains whatever properties are pertinent to the You can identify the source object
of an event using the getSource() instance method in the EventObject class. The subclasses of
EventObject deal with specific types of events, such as action events, window events, mouse events,
and key events etc.
The handler object must be an instance of the corresponding event-handler interface to ensure that
the handler has the correct method for processing the event. JavaFX defines a unified handler
interface EventHandler<T extends Event> for an event T. The handler interface contains the
handle(T e) method for processing the event. The handler object must be registered by the source
object. Registration methods depend on the event type.
JavaFX provides a wide range of UI controls and multimedia features that enable developers to
create rich and interactive user interfaces for their applications.
85
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Some of the key UI controls in JavaFX include:
1. Button: A control that represents a button that can be clicked by the user.
2. Label: A control that displays a piece of text.
3. TextField: A control that allows the user to enter text.
4. ComboBox: A control that displays a drop-down list of items that the user can select from.
5. ListView: A control that displays a list of items.
6. TableView: A control that displays a table of data.
7. WebView: A control that allows the user to display web content within a JavaFX
application.
[1]
In addition to UI controls, JavaFX also provides support for multimedia features such as audio and
video playback, as well as 2D and 3D graphics. Some of the key multimedia features in JavaFX
include:
1. MediaPlayer: A class that provides support for audio and video playback.
2. MediaView: A control that allows the user to display audio and video content within a
JavaFX application.
3. Image: A class that represents an image, which can be loaded from a file or created
dynamically.
4. Canvas: A control that allows the user to draw 2D graphics within a JavaFX application.
5. 3D Graphics: JavaFX provides support for creating and rendering 3D graphics within a
JavaFX application using the Java 3D API.
Overall, JavaFX provides a powerful set of tools for creating rich and interactive user interfaces
that can incorporate multimedia features such as audio and video playback, as well as advanced 2D
and 3D graphics.
Programs:
9.1 Write a program that moves a circle up, down, left or right using arrow keys.
Procedure:
//Write program here
86
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Observations:
//Write program output here
9.2 Write a program that displays the color of a circle as red when the mouse button is pressed
and as blue when the mouse button is released.
Procedure:
//Write program here
Observations:
//Write program output here
9.3 Write a GUI program that use button to move the message to the left and right and use
the radio button to change the color for the message displayed.
Procedure:
//Write program here
Observations:
//Write program output here
Quiz:
1. Describe Property binding in javafx.
2. Write advantages of javafx over AWT.
3.
Suggested Reference:
Problem Completeness
Knowledge Logic
Recognition( and accuracy Ethics (2)
Rubrics (2) Building (2) Total
2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks
87
Object Oriented Programming 1 (3140705) Enrollment Number:220173107016
Practical- 10
10. Develop an simple java application which uses Java FX.
Objectives:
Theory:
Using javafx Students have to develop one small application. The student must work in team. A
team contains minimum 3 members and maximum 4 members.
All team member must have some predefined role in application development.
After successful implementation you have to create small report and power point presentation of
your work.
Date:
//Write date of experiment here
Procedure:
//Place Report here
Problem Communication
Knowledge Team work
identification Skill Ethics (2)
Rubrics (2) (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks
88