OOP-I Experiment 1
OOP-I Experiment 1
B.E. Semester4th
(Computer Engineering)
Certificate
This is to certify thatMr./Ms. ___Arasi ukani_____ Enrollment No.
_220210107072___ of B.E. Semester __4th_Computer Engineering of this
Institute (GTU Code: ___021__ )has satisfactorily completed the Practical /
Tutorial work for the subject Object Oriented Programming-I(3140705)
for the academic year 2023-24.
Place:Bhavnagar
Date: __________
Preface
Main motto of any laboratory/practical/field work is for enhancing required skills as well as
creating ability amongst students to solve real time problem by developing relevant
competencies in psychomotor domain.By keeping in view, GTU has designed competency
focused outcome-based curriculum for engineering degree programs where sufficient weightage
is given to practical work. It shows importance of enhancement of skills amongst the students
and it pays attention to utilize every second of time allotted for practical amongst students,
instructors and faculty members to achieve relevant outcomes by performing the experiments
rather than having merely study type experiments. It is must for effective implementation of
competency focused outcome-basedcurriculum that every practical is keenly designed to serve
as a tool to develop and enhance relevant competency required by the various industry among
every student. These psychomotor skills are very difficult to develop through traditional chalk
and board content delivery method in the classroom. Accordingly, this lab manual is designed
to focus on the industry defined relevant outcomes, rather than old practice of conducting
practical to prove concept and theory.
By using this lab manual students can go through the relevant theory and procedure in advance
before the actual performance which createsan 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 manual also provides guidelines to faculty members to facilitate studentcentric lab
activities through each experiment by arranging and managing necessary resources in order that
the students follow the procedures with required safety and necessary precautions to achieve the
outcomes. It also gives an idea that how students will be assessed by providing rubrics.
Utmost care has been taken while preparing this lab manual however always there is chances of
improvement. Therefore, we welcome constructive suggestions for improvement and removal
of errors if any.
Object Oriented Programming-I (3140705)
Index
(Progressive Assessment Sheet)
Sr. No. Objective(s) of Experiment Page Date of Date of Assessme Sign. of Remar
No. perform submiss nt Teacher ks
ance ion Marks with date
Total
Object Oriented Programming-I (3140705)
1. COURSE OUTCOMES
Reference Books:
1. Intro to Java Programming, 10th edition, Y.Daniel Liang, Pearson
2. Object oriented programming with Java ,RajkumarBuyya,SThamaraiSelvi, Xingchen
Chu, McGrawHill
3. Programming in Java, SachinMalhotra, SaurabhChoudhary, Oxford
4. Programming with JAVA , E Balagurusamy, McGrawHill
5. CORE JAVA volume -I Cay Horstmann, Pearson
Major Equipment: Computer, Laptop
List of Open Source Software/learning website:
https://docs.oracle.com/javase/tutorial/java/index.html
https://www.tutorialspoint.com/JAVA/
https://dev.java/learn/
https://www.codecademy.com/learn/learn-java
https://www.w3schools.com/java/
Object Oriented Programming-I (3140705)
Java:
Java is a high-level, class-based, object-oriented programming language that is designed to have
as few implementation dependencies as possible. It is a general-purpose programming language
intended to let programmers write once, run anywhere (WORA), meaning that compiled Java
code can run on all platforms that support Java without the need for recompilation. Java
applications are typically compiled to bytecode that can run on any Java virtual machine (JVM)
regardless of the underlying computer architecture.
OpenJDK:
OpenJDK (Open Java Development Kit) is a free and open-source implementation of the Java
Platform, Standard Edition (Java SE). It is the result of an effort Sun Microsystems began in 2006.
The implementation is licensed under the GPL-2.0-only with a linking exception. Were it not for
the GPL linking exception, components that linked to the Java class library would be subject to
the terms of the GPL license. OpenJDK is the official reference implementation of Java SE since
version 7.
JVM:
The Java Virtual Machine, or JVM, executes live Java applications. Every JRE includes a default
JRE, but developers are free to choose another that meets the specific resource needs of their
applications.
JRE:
The Java Virtual Machine, or JVM, executes live Java applications. Every JRE includes a default
JRE, but developers are free to choose another that meets the specific resource needs of their
applications. The Java Virtual Machine, or JVM, executes live Java applications. Every JRE
includes a default JRE, but developers are free to choose another that meets the specific resource
needs of their applications.
JAVA IDEs:
IDEs typically provide a code editor, a compiler or interpreter and a debugger that the developer
accesses through a unified graphical user interface (GUI). Here are a few popular Java IDEs:
Eclipse: a Java-based open source platform that enables the creation of highly customized IDEs
from plug-in components built by Eclipse members. The platform is user-friendly for beginners
and also suitable for the creation of more sophisticated applications. Eclipse includes a lot of plug-
ins that allow developers to develop and test code written in other languages.
NetBeans: a Java-based IDE and underlying application platform framework. In addition to Java,
JavaScript and JavaFX, NetBeans supports C/C++, PHP, Groovy, and HTML5.
Object Oriented Programming-I (3140705)
Following are the steps on how to install Java in Windows 10 for JDK 8 free download for 32 bit
or JDK8 download for Windows 64 bit and installation
Step 2) Next,
Step 3) When you click on the Installation link the popup will be open. Click on I reviewed and
accept the Oracle Technology Network License Agreement for Oracle Java SE development kit
and you will be redirected to the login page. If you don’t have an oracle account you can easily
sign up by adding basics details of yours.
Object Oriented Programming-I (3140705)
Step 4) Once the Java JDK 8 download is complete, run the exe for install JDK. Click Next
Step 5) Select the PATH to install Java in Windows… You can leave it Default. Click next.
Object Oriented Programming-I (3140705)
The PATH variable gives the location of executables like javac, java etc. It is possible to run a
program without specifying the PATH but you will need to give full path of executable like C:\
Program Files\Java\jdk1.8.0_271\bin\javac A.java instead of simple javac A.java
The CLASSPATH variable gives location of the Library Files.
Let’s look into the steps to set the PATH and CLASSPATH
Step 6) Copy the path of bin folder which is installed in JDK folder.
Object Oriented Programming-I (3140705)
Note: In case you already have a PATH variable created in your PC, edit the PATH variable to
PATH = <JDK installation directory>\bin;%PATH%;
Here, %PATH% appends the existing path variable to our new value
Experiment No: 1
Date:
CO mapped: CO-1
Objectives: (a) To learn and understand the different basic structures in java, such as syntax,
logics, libraries and proper indentation.
Background:
Java Variables
A variable is a container that holds the value while the Java program is executed. A variable is
assigned with a data type. Variable is a name of a memory location. There are three types of
variables in java: local, instance, and static.
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
● Unary Operator,
● Arithmetic Operator,
● Shift Operator,
● Relational Operator,
● Bitwise Operator,
● Logical Operator,
● Ternary Operator and
● Assignment Operator.
Object Oriented Programming-I (3140705)
Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be used
to control the flow of Java code. Such statements are called control flow statements. It is one of
the fundamental features of Java, which provides a smooth flow of program.
Java provides three types of control flow statements.
● Decision Making statements
○ if statements
○ switch statement
● Loop statements
○ do while loop
○ while loop
○ for loop
○ for-each loop
● Jump statements
○ break statement
○ continue statement
Practical questions:
1. Install JDK and IDE in your system. Write down the steps of installation with
screenshots.
Open the command prompt and enter the command “java –version”, and if it runs
2.Write a Program that displays Welcome to Java, Learning Java Now and Programming is fun.
Answer :
class pract1_2
{
public static void main(String args[])
{
System.out.println("============================================");
System.out.println("Enrollment Number: (220210107072)");
System.out.println("Name: (Ukani Arasi Sanjaybhai)");
System.out.println("Date and Time: "+new java.util.Date());
System.out.println("============================================");
Output :
3.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 )
Answer :
import java.util.Scanner;
class pract1_3
{
public static void main(String[] args)
{
System.out.println("============================================");
System.out.println("Enrollment Number: (220210107072)");
System.out.println("Name: (Ukani Arasi Sanjaybhai)");
System.out.println("Date and Time: "+new java.util.Date());
System.out.println("============================================");
float a = 3.4F;
float b = 50.2F;
float e = 44.5F;
float c = 2.1F;
float d = 0.55F;
float f = 5.9F;
float x=((e*d)-(b*c))/((a*d)-(b*c));
float y=((a*f)-(e*c))/((a*d)-(b*c));
System.out.println("The value of x is "+x+"& y is "+y);
}
}
Output :
Object Oriented Programming-I (3140705)
4.Write a program that reads a number in meters, converts it to feet, and displays the result.
Answer :
import java.util.Scanner;
public class pract1_4{
public static void main(String args[]){
System.out.println("============================================");
System.out.println("Enrollment Number: (220210107072)");
System.out.println("Name: (Ukani Arasi Sanjaybhai)");
System.out.println("Date and Time: "+new java.util.Date());
System.out.println("============================================");
Output :
5.Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your
weight in kilograms and dividing it by the square of your height in meters. Write a program that
prompts the user to enter weight in pounds and height in inches and displays the BMI.Note:- 1
Object Oriented Programming-I (3140705)
Answer:
import java.util.Scanner;
}
}
Output:
6 .Write a program that prompts the user to enter three integers and display the integers in
decreasing order.
Answer:
import java.util.Scanner;
public class prac1_6
{
Object Oriented Programming-I (3140705)
System.out.println("============================================");
System.out.println("Enrollment Number: (220210107072)");
System.out.println("Name: (Ukani Arasi Sanjaybhai)");
System.out.println("Date and Time: "+new java.util.Date());
System.out.println("============================================");
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number:");
int n1 = Integer.parseInt(sc.nextLine());
System.out.println(n1);
}
}
}
}
Output:
7.Write a program that prompts the user to enter a letter and check whether a letter is a vowel or
constant.
Answer:
import java.util.Scanner;
class pract1_7
{
public static void main(String[] args)
{
System.out.println("============================================");
System.out.println("Enrollment Number: (220210107072)");
System.out.println("Name: (Ukani Arasi Sanjaybhai)");
System.out.println("Date and Time: "+new java.util.Date());
System.out.println("============================================");
else
{
System.out.println("The entered alphabet is consonant");
}
}
}
Output:
Additional programs:
8.A cashier has currency notes of denominations 1, 2, 5, 10, 50 and 100. If the amount to be
withdrawn is input through the keyboard, find the total number of currency notes of each
denomination the cashier will have to give to the withdrawer.
Answer:
Output:
9.If a five-digit number is input through the keyboard, write a program to print a new number by
adding one to each of its digits. For example, if the number that is input is 12391 then the output
should be displayed as 23502.
Answer :
Output :
10.If lengths of three sides of a triangle are input through the keyboard, write a program to print
the area of the triangle.
Answer:
Object Oriented Programming-I (3140705)
Output:
**** 1234
*** 123
** 12
* 1
1234 *
567 ***
89 *****
0 *******
*****
***
*
static: The main method belongs to the class itself, rather than any particular instance of
the class.
void: The main method does not return any value.
main: The name of the method.
String[] args: The parameter args is an array of strings, which can be used to pass
command-line arguments to the Java program.
In summary, the main method serves as the starting point for the execution of a Java
program, and it's where the program begins its execution.
Java Virtual Machine (JVM): The JVM is responsible for interpreting and executing Java
bytecode. It abstracts away the underlying hardware and operating system,
providing a consistent runtime environment for Java programs across different
platforms.
WORA Principle: Java follows the principle of "Write Once, Run Anywhere" (WORA),
which means that Java code written on one platform can run on any other platform
with a compatible JVM without modification. This is facilitated by the use of
bytecode and the JVM.
Standard Libraries: Java provides a comprehensive set of standard libraries (Java Standard
Edition or Java SE) that abstract away platform-specific details. These libraries
provide cross-platform APIs for tasks such as I/O operations, networking, GUI
development, and more, ensuring consistent behavior across different platforms.
Platform-specific Implementations: While the core Java language and libraries are
platform-independent, certain APIs allow developers to access platform-specific
features when necessary. These platform-specific implementations are encapsulated
in separate libraries or packages, enabling developers to write platform-independent
code while still leveraging platform-specific functionality when needed.
JRE is a package of software tools that provides the environment for running Java
applications.
It includes the JVM, along with Java class libraries (such as core libraries, networking
libraries, and graphical user interface libraries), and other supporting files required
to run Java applications.
JRE does not include development tools such as compilers and debuggers. It is meant for
end-users who need to run Java applications rather than develop them.
JRE is available as a standalone installation package that users can download and install on
their systems to run Java applications.
Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Signature of Faculty:
Experiment No: 2
Date:
CO mapped: CO-1
Objectives:
a) Array manipulation: Learn how to create, populate, access, and modify arrays in Java.
c) Array and String methods: Explore common array and string methods available in Java's
standard library.
Background:
Java array is an object which contains elements of a similar data type. Additionally, The elements
of an array are stored in a contiguous memory location. It is a data structure where we store
similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on the 1st index, and so on.
There are two types of array.
● Single Dimensional Array
● Multidimensional Array
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
Practical questions:
1. Write a program that generate 6*6 two-dimensional matrix, filled with 0’s and 1’s ,
display the matrix, check every raw and column have an odd number’s of 1’s.
Answer:
import java.util.Scanner;
import java.util.Random;
System.out.println("============================================");
int sum=0;
for(int i=0;i<6;i++)
for(int j=0;j<6;j++)
arr[i][j]=r.nextInt(2);
for(int i=0;i<6;i++)
for(int j=0;j<6;j++)
System.out.print(arr[i][j]+" ");
System.out.println();
for(int i=0;i<6;i++)
{
for(int j=0;j<6;j++)
sum=sum+arr[i][j];
if(sum%2!=0)
sum=0;
for(int j=0;j<6;j++)
for(int i=0;i<6;i++)
sum=sum+arr[i][j];
if(sum%2!=0)
sum=0;
Output:
2. Write a generic method that returns the minimum elements and their indices in a two
dimensional array.
Answer:
import java.util.Scanner;
System.out.println("============================================");
System.out.println("============================================");
int r=sc.nextInt();
int c=sc.nextInt();
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
arr[i][j]=sc.nextInt();
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
System.out.print(arr[i][j]+" ");
System.out.println();
int a=0,b=0;
int min=arr[0][0];
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
min = arr[i][j];
a = i;
b = j;
System.out.print("Minimum element is " + min + " at position (" + a + ", " + b + ")\n");
sc.close();
}
Output:
3.Write a method that returns a new array by eliminating the duplicate values in the array.
Answer:
import java.util.Scanner;
System.out.println("============================================");
System.out.println("Enrollment Number: (220210107072)");
System.out.println("Name: (Ukani Arasi Sanjaybhai)");
System.out.println("Date and Time: "+new java.util.Date());
System.out.println("============================================");
}
System.out.print("Original array is:");
for (int j = 0; j < r; j++) {
System.out.print(+arr[j]+" ");
}
System.out.print("\nArray with only unique elements:");
for(int i=0;i<arr.length;i++){
int flag=0;
for(int j=i+1;j<arr.length; j++){
if(arr[i]==arr[j]){
flag=1;
break;
}
}
if(flag!=1){
System.out.print(arr[i]+" ");
}
}
sc.close();
}
}
Output :
4. Write a program to add, subtract or multiply two 3*3 integer arrays as per choice of user.
Sample Input:
Array 1:
123
456
789
Array 2:
567
120
432
Symbol: +
Sample Output:
6 8 10
576
11 11 11
Answer :
import java.util.Scanner;
public class pract2_4{
public static void main(String[] args) {
System.out.println("============================================");
System.out.println("Enrollment Number: (220210107072)");
System.out.println("Name: (Ukani Arasi Sanjaybhai)");
System.out.println("Date and Time: "+new java.util.Date());
System.out.println("============================================");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
arr1[i][j]=sc.nextInt();
}
System.out.println();
}
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.print(arr1[i][j]+" ");
}
System.out.println();
}
System.out.println("sum of two array");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.print(arr[i][j]+arr1[i][j]+" ");
}
System.out.println();
}
System.out.println("subtraction of two array");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.print(arr[i][j]-arr1[i][j]+" ");
}
System.out.println();
}
int sum = 0;
System.out.println("multiplication of two array");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++) {
for (int k = 0; k < r; k++)
{
sum = sum + arr[i][k] * arr1[k][j];
}
System.out.print(" " +sum);
sum = 0;
}
System.out.println();
}
}
}
Output:
Answer:
import java.util.Scanner;
System.out.println("============================================");
System.out.println("Enrollment Number: (220210107072)");
System.out.println("Name: (Ukani Arasi Sanjaybhai)");
System.out.println("Date and Time: "+new java.util.Date());
System.out.println("============================================");
}
for(int i=0; i<arr.length; i++) {
System.out.print(" " + arr[i]);
}
System.out.println();
}
}
Output:
6.Write a program that prompts the user to enter a string and displays the number of vowels and
consonants in the string.
Answer:
import java.util.Scanner;
public class pract2_6
{
public static void main(String[] args) {
System.out.println("============================================");
System.out.println("Enrollment Number: (220210107072)");
System.out.println("Name: (Ukani Arasi Sanjaybhai)");
System.out.println("Date and Time: "+new java.util.Date());
System.out.println("============================================");
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
{
vowel++;
}
else con++;
}
System.out.println(+vowel+" vowel");
System.out.println(con);
}
}
Output:
7.Write a program that prompts the user to enter two strings and displays the largest common
prefix of the two strings.
Answer:
import java.util.Scanner;
import java.util.Random;
public class pract2_1 {
public static void main(String[] args) {
System.out.println("============================================");
System.out.println("Enrollment Number: (220210107072)");
System.out.println("Name: (Ukani Arasi Sanjaybhai)");
System.out.println("Date and Time: "+new java.util.Date());
System.out.println("============================================");
int sum=0;
Scanner sc= new Scanner (System.in);
int arr[][]=new int[12][12];
Random r= new Random();
for(int i=0;i<6;i++)
{
for(int j=0;j<6;j++)
{
arr[i][j]=r.nextInt(2);
}
}
for(int i=0;i<6;i++)
{
for(int j=0;j<6;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
for(int i=0;i<6;i++)
{
for(int j=0;j<6;j++)
{
sum=sum+arr[i][j];
}
if(sum%2!=0)
System.out.printf("row number %d has odd number of 1's \n",i+1);
sum=0;
}
for(int j=0;j<6;j++)
{
for(int i=0;i<6;i++)
{
sum=sum+arr[i][j];
}
if(sum%2!=0)
System.out.printf("column number %d has odd number of 1's \n",j+1);
sum=0;
}
}
}
Output:
9. Some websites impose certain rules for passwords. Write a method that checks whether a
string is a valid password. Suppose the password rules are as follows: A password must
have at least eight characters. A password consists of only letters and digits. A password
must contain at least two digits. Write a program that prompts the user to enter a password
and displays Valid Password if the rules are followed or Invalid Password otherwise.
Answer:
import java.util.Scanner;
public class pract2_8 {
public static void main(String[] args) {
System.out.println("============================================");
System.out.println("Enrollment Number: (220210107072)");
System.out.println("Name: (Ukani Arasi Sanjaybhai)");
System.out.println("Date and Time: "+new java.util.Date());
System.out.println("============================================");
Scanner sc= new Scanner(System.in);
System.out.println("enter password");
String pass =sc.next();
int f=0;
char ch;
int digit=0;
for(int i=0;i<pass.length();i++)
{
ch =pass.charAt(i);
if(ch>=0&&ch<=9)
digit++;
}
if(pass.length()>=8)
{
for(int i=0;i<pass.length();i++) {
ch=pass.charAt(i);
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')&&digit>=2)
{
f=1;
}
}
}
if(f==1)
{
System.out.println("valid password");
}else
{
System.out.println("invalid password");
}
}
}
Output:
1. What are ragged arrays in java and how are they implemented?
In Java, a ragged array is a two-dimensional array in which the lengths of the rows are not
necessarily the same. This is in contrast to a regular two-dimensional array, where all
rows have the same length. Ragged arrays are also known as "jagged arrays" in some
contexts.
To implement a ragged array in Java, you can create an array of arrays, where each sub-
array can have a different length.
Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Experiment No: 3
Date:
CO mapped: CO-2
Objectives:
Background:
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It
simplifies software development and maintenance by providing some concepts:
● Object: Any entity that has a state and behavior is known as an object. For example, a
chair, pen, table, keyboard, bike, etc. It can be physical or logical. An Object can be
defined as an instance of a class. An object contains an address and takes up some space in
memory. Objects can communicate without knowing the details of each other's data or
code. The only necessary thing is the type of message accepted and the type of response
returned by the objects.
● Class: Collection of objects is called class. It is a logical entity. A class can also be defined
as a blueprint from which you can create an individual object. Class doesn't consume any
space.
● Inheritance: When one object acquires all the properties and behaviors of a parent object,
it is known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
● Polymorphism: If one task is performed in different ways, it is known as polymorphism.
For example: to convince the customer differently, to draw something, for example, shape,
triangle, rectangle, etc. In Java, we use method overloading and method overriding to
achieve polymorphism. Another example can be to speak something; for example, a cat
speaks meow, dog barks woof, etc.
● Abstraction: Hiding internal details and showing functionality is known as abstraction. For
example, phone call, we don't know the internal processing. In Java, we use abstract class
and interface to achieve abstraction.
● Encapsulation: Binding (or wrapping) code and data together into a single unit are known
as encapsulation. For example, a capsule, it is wrapped with different medicines. A java
class is an example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
Practical questions:
1. Write a Java application which takes several command line arguments, which are supposed
to be names of students and prints output as given below: (Suppose we enter 3 names then
output should be as follows):
Number of arguments = 3
(Hint: An array may be used for converting from numeric values from 1 to 20 into String.)
2. Design a class named Rectangle to represent a rectangle. The class contains: Two double
data fields named width and height that specify the width and height of the rectangle. The
default values are 1 for both width and height.
A constructor that creates a rectangle with the specified width and height.
Write a test program that creates two Rectangle objects—one with width 4 and height 40 and
the other with width 3.5 and height 35.9. Display the width, height, area, and perimeter of
each rectangle in this order.
3. Define a class called Cartesian Point, which has two instance variables, x and y. Provide
the methods get X() and get Y() to return the values of the x and y values respectively, a
method called move() which would take two integers as parameters and change the values
of x and y respectively, a method called display() which would display the current values
of x and y. Now overload the method move() to work with single parameter, which would
set both x and y to the same values,provide constructors with two parameters and overload
to work with one parameter as well. Now define a class called Test Cartesian Point, with
the main method to test the various methods in the Cartesian Point class.
4. Create a class Employee which has two private data members name and salary and it has
two public member functions named as getData() and putData() where getData() gets
name and salary from the user putData() displays name and salary for any user.
5. Define a class Time with hours and minutes astwo data members, add necessary member
functions to initialize and display data of class. Do not use constructors in a class. Define a
member function sum () which adds two Time objects. (Use the statements like T3.sum
(T1, T2)).
6. Define Class named Point which represents 2-D Point, i.e P (x, y). Define
Defaultconstructor to initialize both data member value 5, Parameterized constructor to
initialize member according to value supplied by user and Copy Constructor. Define
Necessary Function and Write a program to test class Point.
7. Create a class Account. It has three data member account id, name and balance. Define
function to assign value and display value. Define function that search account number
given by the user. If account number exists, print detail of that account. Write a program
using array of object. Declare at least 5 account and print details.
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Experiment No: 4
Date:
CO mapped: CO-2
Objectives:
Background:
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects.
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object. It is an important part of OOPs (Object Oriented programming system). The
idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
Terms used in Inheritance
Practical questions:
1. A set of 5 words (strings) will be taken as command line arguments. Write a program to
reverse each word and check whether it is palindrome or not using method.
2. Define the class BankAccount to represent an account we open with bank. Define the
subclasses SavingAccount and FixedDepositAccount. Implement the operations like
openAccount(), deposit(), checkBalance(), withdraw() and calInterest() for these classes.
3. Write a program that finds area of any shape by overloading area () method for Square,
Rectangle, Triangle and Square.
4. Write a program that finds Volume of any shape by overloading volume () method for
Cube, Rectangular Cube and Sphere.
5. Write a Program to maintain employee’s information. Program should illustrate
Inheritance concept. (Use your imagination to create class or subclass used for employee).
6. Create a base class Shape. Use this class to store two double type values that could be used
to compute area of any shape. Derive two specific classes called Triangle and Rectangle
from the base shape. Add to the base a member function getdata() to initialize base class
data member and another member function display_area() to compute and display the area
of figures. (Use Method Overriding).
1. What is inheritance in java? Explain different types of inheritance with proper example.
2. Explain the use of final and Super keyword in JAVA
3. Define polymorphism with its need.
4. Explain about Encapsulation, Abstraction.
Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Date:
CO mapped: CO-2
Objectives:
a) To understand the purpose and usage of abstract classes and interfaces in object-oriented
programming. Develop the ability to design and implement abstract classes and interfaces
effectively to promote code reusability, ensure consistent behavior in class hierarchies, and
facilitate the development of flexible and extensible software systems.
b) Abstract classes and interfaces are important OOP concepts that allow you to define
common contracts and behaviors for classes. Achieving this objective will enable you to
use these tools to create more modular and maintainable software, especially when dealing
with class hierarchies and multiple implementations.
Background:
A class that is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
● An abstract class must be declared with an abstract keyword.
● It can have abstract and non-abstract methods.
● It cannot be instantiated.
● It can have constructors and static methods also.
● It can have final methods which will force the subclass not to change the body of the
method.
An interface in Java is a blueprint of a class. It has static constants and abstract methods. The
interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the
Java interface, not the method body. It is used to achieve abstraction and multiple inheritance in
Java. In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
Practical questions:
1. Describe abstract class called Shape which has three subclasses say Triangle, Rectangle,
Circle. Define one method area() in the abstract class and override this area() in these three
subclasses to calculate for specific object, i.e., area() of Triangle subclass should calculate
area of triangle etc. Same for Rectangle and Circle.
2. Write a program that demonstrates the instance of operator. Declare interfaces I1 and I2.
Interface I3 extends both of these interfaces. Also declare interface I4. Class X implements
I3. Class W extends X and implements I4. Create an object of class W. Use the instance of
operator to test if that object implements each of the interfaces and is of type X.
3. Write a java program to implement an interface called Exam with a method Pass (int
mark) that returns a boolean. Write another interface called Classify with a method
Division (int average) which returns a String. Write a class called Result which
implements both Exam and Classify. The Pass method should return true if the mark is
greater than or equal to 50 else false. The Division method must return "First" when the
parameter average is 60 or more, "Second" when average is 50 or more but below 60, "No
division" when average is less than 50.
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Signature of Faculty:
Experiment No: 6
Date:
CO mapped: CO-3
Objectives:
Background:
A java package is a group of similar types of classes, interfaces, and sub-packages. Package in
java can be categorized in two forms, built-in package, and user-defined package. There are many
built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Here, we will have the
detailed learning of creating and using user-defined packages.
Exception Handling in Java is one of the powerful mechanisms to handle runtime errors so that
the normal flow of the application can be maintained. In this practical, we will learn about Java
exceptions, their types, and the difference between checked and unchecked exceptions.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Practical questions:
1. Write a program in Java to develop user defined exception for “Divide by Zero” error.
2. Write a program in Java to demonstrate throw, throws, finally, multiple try block and
multiple catch exception.
3. Write a small application in Java to develop Banking Application in which user deposits
the amount Rs 1000.00 and then start withdrawing ofRs 400.00, Rs 300.00 and it throws
exception "Not Sufficient Fund" when user withdraws Rs 500 thereafter.
4. Write an application that contains a method named average () has one argument that is an
array of strings. It converts these to double values and returns their average. The method
generates a NullPointerException,if an array elements is null or a
NumberFormatException, if an element is incorrectly formatted. Include throws statement
in method declaration.
5. Write an application that generates custom exception if first argument from command line
argument is 0.
6. A marklist containing reg.no and marks for a subject is given.if the marks are <0,user-
defined IllegalMarkException is thrown out and handled with the message "Illegal Mark".
For all valid marks, the candidate will be declared as "PASS" if the marks are equal to or
greater than 40, otherwise it will be declared as "FAIL".Write a class called
IllegalMarkException.
7. Assume that there are two packages, student and exam. A student package contains
Student class and the exam package contains Result class. Write a program that generates
mark sheet for students.
8. Define a class A in package a pack. In class A, three variables are defined of access
modifiers protected, private and public. Define class B in package bpack which extends A
and write display method which accesses variables of class A. Define class C in package
cpack which has one method display() in that create one object of class A and display its
variables. Define class ProtectedDemo in package dpack in which write main() method.
Create objects of class B and C and class display method for both these objects.
Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Signature of Faculty:
Experiment No: 7
Date:
CO mapped: CO-4
Objectives:
To showcase proficiency in reading data from and writing data to files in various formats
using programming languages, demonstrating the ability to implement reliable and
efficient file I/O operations, which are essential for tasks such as data storage, retrieval,
and processing in software applications.
Background:
Java I/O (Input and Output) is used to process the input and produce the output. Java uses the
concept of a stream to make I/O operations fast. The java.io package contains all the classes
required for input and output operations.
Practical questions:
1. Write a program that removes all the occurrences of a specified string from a text file. For
example, invoking java Practical7_1 John filename removes the string John from the
specified file. Your program should read the string as an input.
2. Write a program that will count the number of characters, words, and lines in a file. Words
are separated by whitespace characters. The file name should be passed as a command-line
argument.
3. Write a program to create a file named Practical7.txt if it does not exist. Write 100 integers
created randomly into the file. Integers are separated by spaces in the file. Read the data
back from the file and display the data in increasing order.
Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
References used by the students: (Sufficient space to be provided)
Signature of Faculty:
Experiment No: 8
Date:
CO mapped: CO-5
Objectives:
Background:
Every user interface considers the following three main aspects –
UI elements These are the core visual elements that the user eventually sees and interacts with. JavaFX prov
Layouts They define how UI elements should be organized on the screen and provide a final look and feel to
Behavior These are events that occur when the user interacts with UI elements.
JavaFX provides several classes in the package javafx.scene.control. To create various GUI
components (controls), JavaFX supports several controls such as date picker, button text field, etc.
Each control is represented by a class; you can create a control by instantiating its respective
class.
btn.setOnAction(new ClickHandler(label));
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
Practical questions:
1. Write a program that displays five texts vertically, as shown in Figure. Set a random color
and opacity for each text and set the font of each text to Times Roman, bold, italic, and 22
pixels.
2. Write a program that uses a bar chart to display the percentages of the overall grade
represented by projects, quizzes, midterm exams, and the final exam, as shown in Figure
b. Suppose that projects take 20 percent and are displayed in red, quizzes take 10 percent
and are displayed in blue, midterm exams take 30 percent and are displayed in green, and
the final exam takes 40 percent and is displayed in orange. Use the Rectangle class to
display the bars. Interested readers may explore the JavaFXBarChart class for further
study.
3. Write a program that displays a rectanguloid, as shown in Figure a. The cube should grow
and shrink as the window grows or shrinks.
1. Explain the evolution of Java GUI technologies since awt,swing and JavaFX.
2. What is the purpose of a TextField control, and how can it be used to collect user input?
3. How to create an ImageView from an Image, or directly from a file or a URL?.
4. What are the primary layout controls in JavaFX, and how do they impact the arrangement
of UI components?
5. What is CSS, and how is it used for styling JavaFX UI controls?
Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Signature of Faculty:
Experiment No: 9
Date:
CO mapped: CO-5
Objectives:
Background:
2. Write a program that displays a moving text, as shown in Figure. The text moves from left
to right circularly. When it disappears in the right, it reappears from the left. The text
freezes when the mouse is pressed and moves again when the button is released.
3. Create animation in Figure to meet the following requirements:
■ Get the number of iamges and image’s file-name prefix from the user. For example, if the
user enters n for the number of images and L for the image prefix, then the files are L1.gif,
L2.gif, and so on, to Ln.gif. Assume that the images are stored in the image directory, a
subdirectory of the program’s class directory. The animation displays the images one after the
other.
■ Allow the user to specify an audio file URL. The audio is played while the animation runs.
1. How does event handling work in Java, and what is the event-driven programming model?
2. What is the role of the java.awt.event and javafx.event packages in Java event handling?
3. Explain: MouseEvent, KeyEvent, ActionEvent
4. What are the primary libraries or frameworks for creating animations in Java, and which
one do you prefer?
5. How to set the cycle count of an animation to infinite?
Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Signature of Faculty:
Experiment No: 10
Date:
CO mapped: CO-4
Objectives:
b) Learning recursion and generics is crucial for building efficient algorithms and writing
more versatile and type-safe code in software development. Achieving this objective will
help you become a more proficient and well-rounded programmer.
Background:
Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called the recursive method.
Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the
code stable by detecting the bugs at compile time. Before generics, we can store any type of
object in the collection, i.e., non-generic. Now generics force the java programmer to store a
specific type of object.
Practical questions:
1. Write a recursive method that converts a decimal number into a binary number as a string.
The method header is: public static String dec2Bin(int value)
Write a test program that prompts the user to enter a decimal number and displays its binary
equivalent.
2. Write the following method that returns a new ArrayList. The new list contains the non-
duplicate elements from the original list.
1. What is recursion in Java, and how does it differ from iteration in solving problems?
2. What are the advantages and disadvantages of using recursion in Java?
3. What are generics in Java, and why are they used for creating parameterized types?
4. How to define Generic class? What are restrictions of generic programming?
5. Can you provide an example of a generic class in Java, such as a generic ArrayList?
Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Signature of Faculty:
Experiment No: 11
Date:
CO mapped: CO-4
Objectives:
b) Mastery of the Java Collection framework is essential for managing and organizing data
efficiently in Java applications. This objective focuses on understanding the core
collection interfaces and using them to build versatile data structures to meet various
application needs.
Background:
The Collection in Java is a framework that provides architecture to store and manipulate a group
of objects. Java Collections can achieve all the operations that you perform on data such as
searching, sorting, insertion, manipulation, and deletion. Java Collection means a single unit of
objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and
classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
Practical questions:
1. Write a program that lets the user enter numbers from a graphical user interface and
displays them in a text area, as shown in Figure. Use a linked list to store the numbers. Do
not store duplicate numbers. Add the buttons Sort, Shuffle, and Reverse to sort, shuffle,
and reverse the list.
2. Create two priority queues, {"George", "Jim", "John", "Blake", "Kevin", "Michael"} and
{"George", "Katie", "Kevin", "Michelle", "Ryan"}, and find their union, difference, and
intersection.
3. Store pairs of 10 states and its capital in a map. Your program should prompt the user to
enter a state and should display the capital for the state.
Observations: Put Output of the program
1. Write a note on ‘Collection in JAVA’. Also discuss List and Enumeration Interface.
2. Differentiate between Enumeration and Iterator.
3. Compare List, Set and Map interfaces. Also compare ArrayList, TreeSet and HashMap
classes in java.
4. Explain the unique features of Map interface.
5. How do you perform common operations like sorting, searching, or filtering on
Collections?
Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Signature of Faculty:
Experiment No: 12
Date:
CO mapped: CO-3
Objectives:
b) Demonstrating the use of multithreading is crucial for building responsive and efficient
software applications, and this objective emphasizes understanding the concepts and
practical implementation of multithreading to achieve these goals.
Background:
Practical questions:
1. Write a program to create a thread extending Thread class and demonstrate the use of
slip() method.
2. Write a program to create a thread implementing Runnable interface and demonstrate the
use of join() method.
3.Write a program that launches 10 threads. Each thread adds 1 to a variable sum that initially
is 0. Define an Integer wrapper object to hold sum. Run the program with and without
synchronization to see its effect.
1. Can you explain the difference between a process and a thread in the context of
multithreading?
2. What are the different states in the lifecycle of a Java thread, and how does a thread
transition between them?
3. What is runnable interface? How can you use this interface in creating thread?
4. Explain the concept of thread synchronization and the role of the synchronized keyword.
5. Explain: wait, sleep, notify and notify all.
Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Signature of Faculty: