Lab manual OOP with Java
Lab manual OOP with Java
3 Write a Java Programs to find the largest and smallest of n numbers CO1
stored in an Array.
oBehavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
An object is an instance of a class. A class is a template or blueprint from which objects are created.
Object Definitions:
A class is a group of objects which have common properties. It is a template or blueprint from which
oFields
oMethods
oConstructors
oBlocks
1. By reference variable
2. By method
3. By constructor
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
Output:
111 Karan
222 Aryan
Result: We successfully perform the given Java Programs for Creation of classes and Objects.
Practical No:02
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.
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.
a;
boolean b;
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Out Put:
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.
class Main {
String languages;
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.
DestructorExample.java
public class Dest_java {
des = null;
System.gc();
System.out.print("Destroyed ");
Output:
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.
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 {
//numbers array
int numbers[] = new int[]{55,32,45,98,82,11,9,39,50};
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
Program:
class MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}
Out-Put:
Arguments: 1
Arguments: 1 and 4
2. Method Overloading by changing the data type of parameters
class MethodOverloading {
Output:
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
}
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 {
}
}
Output:
My name is Rohu
I can eat
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.
Program:
class Parent {
// 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 {
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.
An interface is a completely "abstract class" that is used to group related methods with empty bodies:
Program-I:
interface Animal {
public void animalSound(); // interface method (does not have a body) public void sleep(); // interface
method (does not have a body)
}
System.out.println("Zzz");
}
class Main {
OutPut:
interface FirstInterface {
interface SecondInterface {
}
// DemoClass "implements" FirstInterface and SecondInterface class DemoClass implements FirstInterface,
SecondInterface { public void myMethod() {
System.out.println("Some 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:
class Main {
public static void main(String[] args) { Scanner
myObj = new Scanner(System.in); String
userName;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
Output:
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
PrintStream This contains the most used print() and println() method
DataOutputStream This contains method for writing java standard data types.
Example:
try {
sourceStream
= new FileInputStream("sorcefile.txt");
targetStream
= new FileOutputStream("targetfile.txt");
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
OutputStreamReade
This output stream is used to translate character to byte.
r
PrintWriter This contains the most used print() and println() method
Example:
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.
class Main {
public static void main(String[] args) {
try {
class Main {
public static void main(String[] args) {
// Reads characters
input.read(array);
System.out.println("Data in the file:");
System.out.println(array);
Output:
class Main {
public static void main(String args[]) {
import java.io.File;
class Main {
public static void main(String[] args) {
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.
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: