Oop Lab Manual (Cspc2203)
Oop Lab Manual (Cspc2203)
Course: B.Tech
Name: ………………………………………
Registration No: .………………………….
Roll No: …………………………………….
Branch: …………………………………….
Theory:
Java is a programming language developed by James Gosling with other team members 1995 for Sun
Microsystems. Java is a high level, robust, object-oriented and secure programming language
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist.
It is a specification that provides a runtime environment in which Java bytecode can be executed. It can also run
those programs which are written in other languages and compiled to Java bytecode.
The JVM performs the following main tasks:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime Environment is
a set of software tools which are used for developing Java applications. It is used to provide the runtime
environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM
uses at runtime.
This Java Development Kit(JDK) allows to code and run Java programs. It's possible that we can install multiple
JDK versions on the same PC.
1. Download latest Java JDK for your version(32 or 64 bit) of java for Windows
2. Once the download is complete, run the exe for install JDK
Once installation is complete set Environment Variables in Java, Path and Classpath
Environment Variable:
Environment variables basically are strings that contain information such as drive, path, or file name. It points
to the directory where the Java Development Kit (JDK) is installed on your computer.
PATH Setting:
The PATH variable gives the location of executables like javac, java etc. It is possible to run a program without
specifying the PATH but we will need to give full path of executable like C:\Program Files\Java\jdk1.8.0_131\bin\javac
A.java instead of simple javac A.java
1. Open Notepad from Start menu by selecting Programs > Accessories > Notepad.
2. Create a Source Code for Program
Declare a class with name A.
Declare the main method public static void main(String args[]){
Now Type the System.out.println("Hello World"); which displays the text Hello World.
class A{
public static void main(String args[]){
System.out.println("Hello World");
}
}
3. Save the file by using classname.java make sure to select file type as all files while saving the file in our
working folder
4. To Compile the java program open command prompt & write javac A.java
5. To execute the java program write java A
Source Code( .java) (compiler) Byte Code( . class) Load into JVM ( class Loader) JVM Machine code
Conclusion:
From the above experiment we can know the creation compilation and execution of java program.
EXPERIMENT - 2
Name Of The Experiment:
Program to define the data types, variable, operators, arrays and control structures.
Aim of The Experiment:
To study about Data types & variables, operators & decision control structures.
Software Requirement:
Windows 8
Notepad
JDK 8
Hardware Requirement:
Intel Processor
512 GB SSD
4 GB RAM
Theory:
Data Type
Data types specify the different sizes and values that can be stored in the variable. There are two types of data types
in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Variables:
A variable is a container which holds the value while the java program is executed. A variable is assigned with
a datatype.
Variable is a name of memory location. There are three types of variables in java:
1. Local
2. instance
3. static.
Dicision Control:
The Java if statement is used to test the condition. It checks boolean condition: true or false. There are
various types of if statement in java.
1. if statement
2. if-else statement
3. if-else-if ladder
4. nested if statement
In programming languages, loops are used to execute a set of instructions/functions repeatedly when some
conditions become true. There are three types of loops in java.
1. for loop
2. while loop
3. do-while loop
For Loop:
In for loop We can initialize the variable, check condition and increment/decrement value. It consists of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize
the variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of the loop. It
continues execution until the condition is false. It must return boolean value either true or false. It is an
optional condition.
3. Statement: The statement of the loop is executed each time until the second condition is false.
4. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
Syntax:
for(initialization;condition;incr/decr){
//statement or code to be executed
}
While Loop:
The Java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.
Syntax: while(condition){
//code to be executed
}
2.1 Program to demonstrate If statement:
public class Exp2 {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
Output: Age is greater than 18
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Output: C grade
i++;
}
}
}
Output: 1 2 3 4 5 6 7 8 9 10
2.7 Program to print 1 to 10 to demonstrate the use of do-while Loop
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.print(i);
i++;
}while(i<=10);
}
}
Output: 1 2 3 4 5 6 7 8 9 10
Conclusion:
From the above experiment we can know about the Data types, variables, decision control structures: if, nested
If & Loop control structures: do.. while , while, for.
EXPERIMENT - 3
Name Of The Experiment:
Program to define class and constructors. Demonstrate constructors.
Aim of The Experiment:
To study about Classes and objects and constructors.
Software Requirement:
Windows 8
Notepad
JDK 8
Hardware Requirement:
Intel Processor
512 GB SSD
4 GB RAM
Theory:
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:
1. Fields
2. Methods
3. Constructors
4. Blocks
5. Nested class and interface
Object: An object is an instance of a class. In Java it is the physical as well as a logical entity.
An object has three characteristics:
1. State: represents the data (value) of an object.
2. Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
3. Identity: An object identity is typically implemented via a unique ID.
There are 3 ways to initialize object in Java.
1. By reference variable
2. By method
3. By constructor
class Student{
int id;
String name;
}
class Student2{
public static void main(String args[]){
Student s1=new Student();
s1.id=331;
s1.name="Tarini";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
Output: 331 Tarini
3.3 Program to demonstrate how to create an object and initialize it with method
class Student{
int rollno;
String name;
void insertData(int r, String n){
rollno=r;
name=n;
}
void displayInfo(){
System.out.println(rollno+" "+name);
}
}
class Student3{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertData(331,"Kalia");
s2.insertData(332,"Tapu");
s1.displayInfo();
s2.displayInfo();
}
}
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){
System.out.println(id+" "+name+" "+salary);
}
}
public class Emp {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(331,"Kalia",45000);
e2.insert(332,"Tapu",25000);
e3.insert(333,"Tapan",55000);
e1.display();
e2.display();
e3.display();
}
}
Output: 331 Kalia 45000.0
332 Tapu 25000.0
333 Tapan 55000.0
Conclusion:
From the above experiment we can know about the class and object creation and initialisation.
EXPERIMENT - 4
Name Of The Experiment:
Program to define class, methods and objects. Demonstrate method overloading.
Aim of The Experiment:
To study about methods and method overloading.
Software Requirement:
Windows 8
Notepad
JDK 8
Hardware Requirement:
Intel Processor
512 GB SSD
4 GB RAM
Theory:
Polymorphism:
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in
OOP occurs when a parent class reference is used to refer to a child class object.
In Java polymorphism is mainly divided into two types:
1. Compile time Polymorphism
2. Runtime Polymorphism
1. Compile time polymorphism: It is also known as static polymorphism. This type of polymorphism is
achieved by function overloading or operator overloading.
Method Overloading: When there are multiple functions with same name but different
parameters then these functions are said to be overloaded. Functions can be overloaded by change
in number of arguments or/and change in type of arguments.
Operator Overloading: Java also provide option to overload operators. For example, we can
make the operator („+‟) for string class to concatenate two strings. We know that this is the
addition operator whose task is to add two operands. So a single operator „+‟ when placed between
integer operands, adds them and when placed between string operands, concatenates them.
FileName: ClassMethod.Java
// Main class to run the program
public class ClassMethod {
public static void main(String[] args) {
// Create an object of the Person class
Person person1 = new Person("Ashok", 30);
Output:
Name: Ashok
Age: 30
Updated Age: 31
Name: Alok
Age: 25
}
}
Output:
Sum of 2 and 3 (int): 5
Sum of 1, 2, and 3 (int): 6
Sum of 2.5 and 3.5 (double): 6.0
Conclusion:
From the above experiment we can know about the Polymorphism and types.
EXPERIMENT - 5
Name Of The Experiment:
Program to define inheritance and show method overriding.
Aim of The Experiment:
To study about inheritance and method overriding.
Software Requirement:
Windows 8
Notepad
JDK 8
Hardware Requirement:
Intel Processor
512 GB SSD
4 GB RAM
Theory:
Inheritance can be defined as the process where one class acquires the properties (methods and fields) of
another. With the use of inheritance the information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose
properties are inherited is known as superclass (base class, parent class).
extends Keyword - extends is the keyword used to inherit the properties of a class.
Parent a;
a = new subclass1();
a.Print();
a = new subclass2();
a.Print();
}
}
Compile the above class : javac TestPolymorphism.java
java TestPolymorphism
Output: subclass1
subclass2
Conclusion:
From the above experiment we can know about the Inheritance & Polymorphism.
EXPERIMENT - 6
Name Of The Experiment:
Program to demonstrate Packages.
Aim of The Experiment:
To study about package.
Software Requirement:
Windows 8
Notepad
JDK 8
Hardware Requirement:
Intel Processor
512 GB SSD
4 GB RAM
Theory:
A java package is a group of similar types of classes, interfaces and sub-packages. Package in java can be
categorized in two form, 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.
Advantage of Java Package
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.
package Package1;
public class Hello {
public void sayHello() {
System.out.println("Hello from Package1!");
}
}
package Package2;
import Package1.Hello; // Importing Hello class from Package1
public class Example {
public static void main(String[] args) {
Hello hello = new Hello();
hello.sayHello();
}
}
Compile the program : javac Package1/Hello.java Package2/Example.java
Run the Program : java Package2.Main
}
}
Conclusion:
From the above experiment we can know about the exception handlings.
EXPERIMENT - 8
Name Of The Experiment:
Program to demonstrate Multithreading.
Aim of The Experiment:
To study about Multithreading.
Software Requirement:
Windows 8
Notepad
JDK 8
Hardware Requirement:
Intel Processor
512 GB SSD
4 GB RAM
Theory:
Thread:
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared
memory area.
Multithreading in java is a process of executing multiple threads simultaneously.We use multithreading than
multiprocessing because threads use a shared memory area. They don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than process.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple operations at the
same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
a. New:
The thread is in new state if you create an instance of Thread class but before the invocation of
start() method
b. Runnable:
The thread is in runnable state after invocation of start() method, but the thread scheduler has
not selected it to be the running thread.
c. Running:
The thread is in running state if the thread scheduler has selected it.
d. Non-Runnable (Blocked):
This is the state when the thread is still alive, but is currently not eligible to run.
e. Terminated:
A thread is in terminated or dead state when its run() method exits.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object
class and implements Runnable interface.
java Multi
Output: thread is running...
java Multi1
Output: thread is running...
Conclusion:
From the above experiment we can know about the Threads and Multithreading.
EXPERIMENT - 9
Name Of The Experiment:
Program to demonstrate Applet structure and event handling.
Aim of The Experiment:
To study about Applet and Event Handling.
Software Requirement:
Windows 8
Notepad
JDK 8
Hardware Requirement:
Intel Processor
512 GB SSD
4 GB RAM
Theory:
APPLET:
Applet is a Java program that can be embedded into a web page. It runs inside the web browser and works at client side.
Applet is embedded in a HTML page using the APPLET or OBJECT tag and hosted on a web server.
Applets are used to make the web site more dynamic and entertaining.
Life cycle of an applet :
When an applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used
for drawing oval, rectangle, arc etc.
This program will use Swing components to create a window with a button. Clicking the button will change the text of a
label. Code Explanation:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Create a label
JLabel label = new JLabel("Click the button!");
label.setBounds(50, 30, 200, 30);
frame.add(label);
// Create a button
JButton button = new JButton("Click Me");
button.setBounds(100, 70, 100, 30);
frame.add(button);
Output:
Conclusion:
From the above experiment we can know about the Applet program and event handling.
EXPERIMENT - 10
Name Of The Experiment:
Program to demonstrate Layout managers
Aim of The Experiment:
To study about Layout Managers.
Software Requirement:
Windows 8
Notepad
JDK 8
Hardware Requirement:
Intel Processor
512 GB SSD
4 GB RAM
Theory:
The LayoutManagers are used to arrange components in a particular manner. The Java LayoutManagers facilitates
us to control the positioning and size of the components in GUI forms. LayoutManager is an interface that is
implemented by all the classes of layout managers.
FlowLayout:
Arranges components in a left-to-right flow, wrapping to the next line when necessary. It Can be aligned to the left,
center, or right.
BorderLayout:
Divides the container into five regions: North, South, East, West, and Center. Components added to the North or South
stretch across the width of the container, while those added to East or West stretch across the height. The Center
component takes up the remaining space.
GridLayout
Arranges components in a grid of equal-sized cells, with a specified number of rows and columns. Each cell is the same
size, and components are added sequentially to each cell.
BoxLayout
Arranges components either vertically or horizontally in a single line. Components are aligned along a single axis
(either X or Y).
import javax.swing.*;
import java.awt.*;
Conclusion:
From the above experiment we can know about the different types of Layout managers.