0% found this document useful (0 votes)
5 views

Lab manual OOP with Java

The document outlines the practical curriculum for Object Oriented Programming (Java) at Priyadarshini College of Engineering for the 2024-25 academic year. It includes a list of practical exercises focusing on key concepts such as classes, objects, constructors, inheritance, polymorphism, and interfaces. Each practical is mapped to specific course outcomes (CO) to ensure alignment with learning objectives.

Uploaded by

sohamsgsg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lab manual OOP with Java

The document outlines the practical curriculum for Object Oriented Programming (Java) at Priyadarshini College of Engineering for the 2024-25 academic year. It includes a list of practical exercises focusing on key concepts such as classes, objects, constructors, inheritance, polymorphism, and interfaces. Each practical is mapped to specific course outcomes (CO) to ensure alignment with learning objectives.

Uploaded by

sohamsgsg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

PRIYADARSHINI COLLEGE OF ENGINEERING,NAGPUR

Department Of Artificial Intelligence & Data Science


Session: 2024-25
Semester:III
Subject: Object Oriented Programming (Java)
(24UAI-303P)
Index

Sr.no List of Practical’s CO


Mapping
1 Write a Programs to create Objects and Classes in Java. CO1

2 Write a Java Programs using constructor and destructor. CO1

3 Write a Java Programs to find the largest and smallest of n numbers CO1
stored in an Array.

4 Write a Java programs using function overloading. CO2

5 Write a Java Programs using inheritance. CO2

6 Write a Java program to demonstrate Polymorphism. CO2

7 Write a Java programs on interfaces. CO3

8 Write a Java programs on packages. CO3

9 Write a Java Programs using IO streams. CO4

10 Write a Java program using Files. CO4

Sr. No. Name of Innovative Experiment CO


Mapping
1 Write a Java Programs using AWT CO5

Practical Teacher Lab Incharge HOD


Practical No:01
Aim: Write a Programs to create Objects and Classes in Java.
Theory: An entity that has state and behavior is known as an object.
An object has three characteristics:
oState: represents the data (value) of an object.

oBehavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.

oIdentity: An object identity is typically implemented via a unique ID.

An object is an instance of a class. A class is a template or blueprint from which objects are created.

So, an object is the instance(result) of a class.

Object Definitions:

oAn object is a real-world entity.

oAn object is a runtime entity.

oThe object is an entity which has state and behavior.

oThe object is an instance of a class.

A class is a group of objects which have common properties. It is a template or blueprint from which

objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

oFields

oMethods

oConstructors

oBlocks

oNested class and interface

3 Ways to initialize object

There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor

1) Object and Class Example: Initialization through reference


Initializing an object means storing data into the object.

Here we are going to initialize the object through a reference variable.

Program:

class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);
}
}

Output:

101 Sonoo
102 Amit

2) Object and Class Example: Initialization through method


we are creating the two objects of Student class and initializing the value to these objects by invoking
the insertRecord method.
class Student
{
int rollno;
String name;
vod insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}

Output:

111 Karan
222 Aryan

Result: We successfully perform the given Java Programs for Creation of classes and Objects.
Practical No:02

Aim: Write a Java Programs using constructor and destructor.

Theory: In Java

 A constructor is a block of codes similar to the method. It is called when an instance of the
class is created. At the time of calling constructor, memory for the object is allocated in the memory.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new() keyword, at least one constructor is called.
 It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.

Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Program:

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time

of object creation.

Example of default constructor


class Main { int

a;
boolean b;

public static void main(String[] args) {

// A default constructor is called Main


obj = new Main();

System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}

Out Put:

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can
have any number of parameters in the constructor.

Example 4: Parameterized constructor

class Main {

String languages;

// constructor accepting single value Main(String


lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}

public static void main(String[] args) {

// call constructor by passing a single value


Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}

Out Put:

Part-II

Theory: The destructor is the opposite of the constructor. Remember that there is no concept of
destructor in Java. In place of the destructor, Java provides the garbage collector that works the same as the
destructor. The garbage collector is a program (thread) that runs on
the JVM. It automatically deletes the unused objects (objects that are no longer used) and free- up the
memory. The programmer has no need to manage memory, manually. It can be error- prone, vulnerable, and
may lead to a memory leak.

Program: Example of Destructor

DestructorExample.java
public class Dest_java {

public static void main(String[] args) {

Dest_java des = new Dest_java(); des.finalize();

des = null;

System.gc();

System.out.print("main() method ");


}

protected void finalize() {

System.out.print("Destroyed ");

Output:

Destroyed main() method Destroyed

Result: : we successfully perform the given Java Programs using constructor and destructor.
Practical No:03

Aim: Write a Java Programs to find the largest and smallest of n numbers stored in an Array.
Theory:
Java array is an object which contains elements of a similar data type.
The elements of an array are stored in a contiguous memory location.
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 1st index and so on.
We can store primitive values or objects in an array in Java.
Advantages
oCode Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.

oRandom access: We can get any data located at an index position.

This Java program shows how to find the largest and the smallest number from within an array. Here in
this program, a Java class name FindLargestSmallestNumber is declared which is having the main()
method. Inside the main(), the integer type array is declared and initialized. The integer type array is used
to store consecutive values all of them having type integer.
Then two integer type variable, name smallest and largest are declared and initialized with
the 0th index value of the array.

Then a 'for loop' is used which goes from 1 to the array length. Within this loop the largest and the
smallest value is detected and initialized to the smallest and largest value uisng if()

Program:
public class FindLargestSmallestNumber {

public static void main(String[] args) {

//numbers array
int numbers[] = new int[]{55,32,45,98,82,11,9,39,50};

//assign first element of an array to largest and smallest


int smallest = numbers[0];
int largetst = numbers[0];

for (int i = 1; i < numbers.length; i++) {


if (numbers[i] > largetst)
largetst = numbers[i];
else if (numbers[i] < smallest)
smallest = numbers[i];
}

System.out.println("Largest Number is : " + largetst);


System.out.println("Smallest Number is : " + smallest);
}}
Output:

Practical No:04
Aim: Write a Java programs using function overloading.

Theory: In Java, two or more methods may have the same name if they differ in parameters (different
number of parameters, different types of parameters, or both). These methods are called overloaded
methods and this feature is called method overloading. For example

void func() { ... }

void func(int a) { ... }

float func(double a) { ... }

float func(int a, float b) { ... }


Here, the func() method is overloaded. These methods have the same name
but accept different arguments.

Program:

1. Overloading by changing the number of parameters

class MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}

private static void display(int a, int b){


System.out.println("Arguments: " + a + " and " + b);
}

public static void main(String[] args) {


display(1);
display(1, 4);
}
}

Out-Put:

Arguments: 1
Arguments: 1 and 4
2. Method Overloading by changing the data type of parameters

class MethodOverloading {

// this method accepts int


private static void display(int a){
System.out.println("Got Integer data.");
}

// this method accepts String object


private static void display(String a){
System.out.println("Got String object.");
}

public static void main(String[] args) {


display(1);
display("Hello");
}
}

Output:

Got Integer data.


Got String object.

Result: We successfully perform the given Java programs using function overloading.

Practical No:05
Aim: Write a Java Programs using inheritance.

Theory: Inheritance is one of the key features of OOP that allows us to create a new class from an existing
class.

The new class that is created is known as subclass (child or derived class) and the existing class from where
the child class is derived is known
as superclass (parent or base class).
The extends keyword is used to perform inheritance in Java
class Animal {
// methods and fields
}

// use of extends keyword


// to perform inheritance
class Dog extends Animal {

// methods and fields of Animal


// methods and fields of Dog
}

In the above example, the Dog class is created by inheriting the methods and fields from the
Animal class.
Here, Dog is the subclass and Animal is the superclass.
Program:
Example 1: Java Inheritance

class Animal {

// field and method of the parent class


String name;
public void eat() {
System.out.println("I can eat");
}
}

// inherit from Animal


class Dog extends Animal {

// new method in subclass public


void display() {
System.out.println("My name is " + name);
}
}
class Main {
public static void main(String[] args) {

// create an object of the subclass


Dog labrador = new Dog();

// access field of superclass


labrador.name = "Rohu";
labrador.display();

// call method of superclass


// using object of subclass
labrador.eat();

}
}

Output:

My name is Rohu
I can eat

Result: We successfully perform the given Java programs using Inheritance.

Practical No:06
Aim: Write a Java program to demonstrate Polymorphism.
Theory: Polymorphism means "many forms", and it occurs when we have many classes that are related
to each other by inheritance.
Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those
methods to perform different tasks.
Types of Java Polymorphism
In Java Polymorphism is mainly divided into two types:
 Compile-time Polymorphism
 Runtime Polymorphism
Compile-Time Polymorphism in Java
It is also known as static polymorphism. This type of polymorphism is achieved by function overloading
or operator overloading.
Note: But Java doesn’t support the Operator Overloading.
Runtime Polymorphism in Java
It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden
method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding. Method
overriding, on the other hand, occurs when a derived class has a definition for one of the member functions
of the base class. That base function is said to be overridden.

Advantages of Polymorphism in Java

1. Increases code reusability by allowing objects of different classes to be treated as objects of a


common class.
2. Improves readability and maintainability of code by reducing the amount of code that needs to be
written and maintained.
3. Supports dynamic binding, enabling the correct method to be called at runtime, based on the actual
class of the object.
4. Enables objects to be treated as a single type, making it easier to write generic code that can handle
objects of different types.

Program:

class Parent {

// Method of parent class


void Print()
{

// Print statement
System.out.println("parent class");
}
}
// Class 2
// Helper class
class subclass1 extends Parent {

// Method
void Print() { System.out.println("subclass1"); }
}

// Class 3
// Helper class
class subclass2 extends Parent {

// Method
void Print()
{

// Print statement
System.out.println("subclass2");
}
}

// Class 4
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating object of class 1


Parent a;

// Now we will be calling print methods


// inside main() method

a = new subclass1();
a.Print();

a = new subclass2();
a.Print();
}
}

Output:
subclass1
subclass2
Result: We successfully perform the given Java programs using Polymorhism.
Practical No:07
Aim: Write a Java programs on interfaces.

Theory: Another way to achieve abstraction in Java, is with interfaces.

An interface is a completely "abstract class" that is used to group related methods with empty bodies:

To access the interface methods, the interface must be "implemented" (kinda


like inherited) by another class with the implements keyword (instead of extends). The body of the
interface method is provided by the "implement" class:

Program-I:

interface Animal {

public void animalSound(); // interface method (does not have a body) public void sleep(); // interface
method (does not have a body)
}

class Pig implements Animal { public void animalSound() {


System.out.println("The pig says: wee wee");

public void sleep() {

System.out.println("Zzz");

}
class Main {

public static void main(String[] args) { Pig myPig = new Pig();


myPig.animalSound(); myPig.sleep();
}

OutPut:

Prog-II: To implement multiple interfaces, separate them with a comma:

interface FirstInterface {

public void myMethod(); // interface method

interface SecondInterface {

public void myOtherMethod(); // interface method

}
// DemoClass "implements" FirstInterface and SecondInterface class DemoClass implements FirstInterface,
SecondInterface { public void myMethod() {
System.out.println("Some text..");

public void myOtherMethod() { System.out.println("Some other text...");


}

class Main {

public static void main(String[] args) { DemoClass myObj = new DemoClass(); myObj.myMethod();
myObj.myOtherMethod();

Out-Put
Result: we successfully perform the given Java Programs on interfaces.

Practical No.08
Aim: Write a Java programs on packages.

Theory: A package in Java is used to group related classes. Think of it as a folder in a file directory. We
use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two
categories:
 Built-in Packages (packages from the Java API)
 User-defined Packages (create your own packages)

Built-in Packages

The Java API is a library of prewritten classes, that are free to use, included in the Java Development
Environment.

The library contains components for managing input, database programming, and much much more. The
complete list can be found at Oracles
website: https://docs.oracle.com/javase/8/docs/api/.

The library is divided into packages and classes. Meaning you can either import a single class (along with
its methods and attributes), or a whole
package that contain all the classes that belong to the specified package.

To use a class or a package from the library, you need to use the import keyword:

Program: import java.util.Scanner; // import the Scanner class

class Main {
public static void main(String[] args) { Scanner
myObj = new Scanner(System.in); String
userName;

// Enter username and press Enter


System.out.println("Enter username");
userName = myObj.nextLine();

System.out.println("Username is: " + userName);


}
}
Out-Put:

Part-II: package mypack;

class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}

Output:

Result: : we successfully perform the given Java programs on packages.


Practical No.09
Aim: Write a Java Programs using IO streams.
Theory: Java brings various Streams with its I/O package that helps the user to perform all the
input-output operations. These streams support all the types of objects, data-types, characters, files etc to fully
execute the I/O operations.

Types of Streams:
 Depending on the type of operations, streams can be divided into two primary classes:
1. Input Stream: These streams are used to read data that must be taken as an input from a source
array or file or any peripheral device. For eg., FileInputStream, BufferedInputStream, ByteArrayInputStream
etc.
2. Output Stream: These streams are used to write data as outputs into an array or file or any output
peripheral device. For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc.

 Depending on the types of file, Streams can be divided into two primary classes which can be further
divided into other classes as can be seen through the diagram below followed by the explanations.

1. ByteStream: This is used to process data byte by byte (8 bits). Though it has many classes, the
FileInputStream and the FileOutputStream are the most popular ones. The FileInputStream is used to read
from the source and FileOutputStream is used to write to the destination. Here is the list of various
ByteStream Classes:
Stream class Description

BufferedInputStream It is used for Buffered Input Stream.

DataInputStream It contains method for reading java standard datatypes.

FileInputStream This is used to reads from a file

InputStream This is an abstract class that describes stream input.

PrintStream This contains the most used print() and println() method

BufferedOutputStream This is used for Buffered Output Stream.

DataOutputStream This contains method for writing java standard data types.

FileOutputStream This is used to write to a file.

OutputStream This is an abstract class that describe stream output.

Example:

// Java Program illustrating the


// Byte Stream to copy
// contents of one file to another file.
import java.io.*;
public class BStream {
public static void main(
String[] args) throws IOException
{

FileInputStream sourceStream = null;


FileOutputStream targetStream = null;

try {
sourceStream
= new FileInputStream("sorcefile.txt");
targetStream
= new FileOutputStream("targetfile.txt");

// Reading source file and writing


// content to target file byte by byte
int temp;
while ((
temp = sourceStream.read())
!= -1)
targetStream.write((byte)temp);
}
finally {
if (sourceStream != null)
sourceStream.close();
if (targetStream != null)
targetStream.close();
}
}
}

Output:
Shows contents of file test.txt
CharacterStream: In Java, characters are stored using Unicode conventions (Refer this for details).
Character stream automatically allows us to read/write data character by character. Though it has many
classes, the FileReader and the FileWriter are the most popular ones. FileReader and FileWriter are character
streams used to read from the source and write to the destination respectively. Here is the list of various
CharacterStream Classes:
Stream class Description

BufferedReader It is used to handle buffered input stream.

FileReader This is an input stream that reads from file.

InputStreamReader This input stream is used to translate byte to character.

OutputStreamReade
This output stream is used to translate character to byte.
r

Reader This is an abstract class that define character stream input.

PrintWriter This contains the most used print() and println() method

Writer This is an abstract class that define character stream output.

BufferedWriter This is used to handle buffered output stream.


Stream class Description

FileWriter This is used to output stream that writes to file.

Example:

// Java Program illustrating that


// we can read a file in a human-readable
// format using FileReader

// Accessing FileReader, FileWriter,


// and IOException
import java.io.*;
public class GfG {
public static void main(
String[] args) throws IOException
{
FileReader sourceStream = null;
try {
sourceStream
= new FileReader("test.txt");

// Reading sourcefile and


// writing content to target file
// character by character.
int temp;
while ((
temp = sourceStream.read())
!= -1)
System.out.println((char)temp);
}
finally {
// Closing stream as no longer in use
if (sourceStream != null)
sourceStream.close();
}
}
}

Result: We successful perform the given Java Programs using IO Stream.


Practical No:10
Aim: Write a Java Programs using files.

Theory: The File class of the java.io package is used to perform various operations on files and directories.
There is another package named java.nio that can be used to work with files. However, in this tutorial, we
will focus on the java.io package.
A file is a named location that can be used to store related information. For example,

main.java is a Java file that contains information about the Java program.
A directory is a collection of files and subdirectories. A directory inside a directory known as

subdirectory.

To create an object of File, we need to import the java.io.File package first. Once we import the package,
here is how we can create objects of file.

Java File Operation Methods

Operation Method Package


To create file createNewFile() java.io.File

To read file read() java.io.FileReader

To write file write() java.io.FileWriter

To delete file delete() java.io.File

Program: Example: Create a new File

// importing the File class


import java.io.File;

class Main {
public static void main(String[] args) {

// create a file object for the current location File


file = new File("newFile.txt");

try {

// trying to create a file based on the object boolean


value = file.createNewFile();
if (value) {
System.out.println("The new file is created.");
}
else {
System.out.println("The file already exists.");
}
}
catch(Exception e) { e.getStackTrace();
}
}
}
If newFile.txt doesn't exist in the current location, the file is created and this
message is shown.

However, if newFile.txt already exists, we will see this message.

Example: Read a file using FileReader

Suppose we have a file named input.txt with the following content.

This is a line of text inside the file.

Now let's try to read the file using Java FileReader.

// importing the FileReader class


import java.io.FileReader;

class Main {
public static void main(String[] args) {

char[] array = new char[100]; try


{
// Creates a reader using the FileReader
FileReader input = new FileReader("input.txt");

// Reads characters
input.read(array);
System.out.println("Data in the file:");
System.out.println(array);

// Closes the reader


input.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}

Output:

Java write to files

To write data to the file, we can use subclasses of


either OutputStream or Writer.
Example: Write to file using FileWriter

// importing the FileWriter class


import java.io.FileWriter;

class Main {
public static void main(String args[]) {

String data = "This is the data in the output file"; try


{
// Creates a Writer using FileWriter
FileWriter output = new FileWriter("output.txt");

// Writes string to the file


output.write(data);
System.out.println("Data is written to the file.");

// Closes the writer


output.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}

Example: Delete a file

import java.io.File;

class Main {
public static void main(String[] args) {

// creates a file object


File file = new File("file.txt");

// deletes the file


boolean value = file.delete();
if(value) {
System.out.println("The File is deleted.");
}
else {
System.out.println("The File is not deleted.");
}
}
}

Result: We successfully perform the given Java Programs using files.


Practical No:11

Aim: Write a Java Programs using AWT

Theory: AWT stands for Abstract window toolkit is an Application programming interface (API) for
creating Graphical User Interface (GUI) in Java. It allows Java programmers to develop window-based
applications.

AWT provides various components like button, label, checkbox, etc. used as objects inside a Java Program.
AWT components use the resources of the operating system, i.e., they are
platform-dependent, which means, component's view can be changed according to the view of the operating
system. The classes for AWT are provided by the Java.awt package for various AWT components.

The following image represents the hierarchy for Java AWT.

Program: Consider the following program in which we have created a user's form GUI, which has three
fields, i.e., first name, last name, and date of birth.

1.import java.awt.*;
2.public class AwtApp extends Frame { 3.
4. AwtApp(){
5. Label firstName = new Label("First Name");
6. firstName.setBounds(20, 50, 80, 20);
7.
8. Label lastName = new Label("Last Name");
9. lastName.setBounds(20, 80, 80, 20);
10.
11. Label dob = new Label("Date of Birth");
12. dob.setBounds(20, 110, 80, 20);
13.
14. TextField firstNameTF = new TextField();
15. firstNameTF.setBounds(120, 50, 100, 20);
16.
17. TextField lastNameTF = new TextField();
18. lastNameTF.setBounds(120, 80, 100, 20);
19.
20. TextField dobTF = new TextField();
21. dobTF.setBounds(120, 110, 100, 20);
22.
23. Button sbmt = new Button("Submit");
24. sbmt.setBounds(20, 160, 100, 30);
25.
26. Button reset = new Button("Reset");
27. reset.setBounds(120,160,100,30); 28.
29. add(firstName);
30. add(lastName);
31. add(dob);
32. add(firstNameTF);
33. add(lastNameTF);
34. add(dobTF);
35. add(sbmt);
36. add(reset);
37.
38. setSize(300,300);
39. setLayout(null);
40. setVisible(true);
41. }
42. public static void main(String[] args) {
43. // TODO Auto-generated method stub
44. AwtApp awt = new AwtApp();
45. }
46. }

Output:

Result: we successfully perform the given Java practical using AWT.

You might also like