0% found this document useful (0 votes)
35 views31 pages

Oop Lab Manual (Cspc2203)

Uploaded by

mahantasuman8908
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)
35 views31 pages

Oop Lab Manual (Cspc2203)

Uploaded by

mahantasuman8908
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/ 31

LAB MANUAL

Course: B.Tech

Branch: Computer Science and Engineering

Semester: 3rd Semester

Subject: Object Oriented Programming Lab

Sub. Code: CSPC2203

Prepared By: Tarini Prasad Pattanaik


LABORATORY MANUAL
ON
OBJECT ORIENTED PROGRAMMING

Name: ………………………………………
Registration No: .………………………….
Roll No: …………………………………….
Branch: …………………………………….

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


Nalanda Institute of Technology
Bhubaneswar
(Approved by AICTE, New Delhi & Affiliated to BPUT, Odisha )
CONTENTS
EXPT. NO. NAME OF THE EXPERIMENT PAGE NO.

1. Write a JAVA Program for printing “Hello World!”. 4

2. Program to define the data types, variable, operators, 6


arrays and control structures.

3. Program to define class and constructors. Demonstrate 11


constructors.

4. Program to define class, methods and objects. 15


Demonstrate method overloading.

5. Program to define inheritance and show method 19


overriding.

6. Program to demonstrate Packages. 21

7. Program to demonstrate Exception Handling. 22

8. Program to demonstrate Multithreading. 24

9. Program to demonstrate Applet structure and event 26


handling.

10. Program to demonstrate Layout managers 29


EXPERIMENT - 1
Name Of The Experiment:
Introduction, Compiling & executing a java program to print “Hello World”
Aim of The Experiment:
To study about Introduction, Compiling & executing a java program.
Software Requirement:
Windows 8
Notepad
JDK 8
Hardware Requirement:
Intel Processor
512 GB SSD
4 GB RAM

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.

Installation of Java Software:

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

Steps for set PATH & CLASSPATH:


1. Right Click on the My Computer and Select the properties
2. Click on advanced system settings
3. Click on Environment Variables
4. Click on new Button of User variables
5. Type PATH in the Variable name.
6. Copy the path of bin folder which is installed in JDK folder.
7. Paste Path of bin folder in Variable value and click on OK Button.
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

We can follow a similar process to set CLASSPATH


Note: In case java installation does not work after installation, change classpath to-
CLASSPATH = <JDK installation directory>\lib\tools.jar;

Creation and Running of first Java Program:

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

Control flow diagram :

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

2.2 Program to check a leap year for demonstrate If-else statement:


public class LeapYearExp {
public static void main(String[] args) {
int year=2020;
if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){
System.out.println("LEAP YEAR");
}
else{
System.out.println("COMMON YEAR");
}
}
}
Output: LEAP YEAR

2.3 Program to demonstrate the use of If else-if ladder


Program of grading system for fail, D grade, C grade, B grade, A grade and A+

public class Exp2 {


public static void main(String[] args) {
int marks=65;

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

2.4 Program to demonstrate the use of Nested If Statement

public class Exp2 {


public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}
Output: You are eligible to donate blood
2.5 Program to print 1 table to demonstrate the use of For Loop
public class ForExp3 {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.print(i);
}
}
}
Output: 1 2 3 4 5 6 7 8 9 10

2.6 Program to print 1 to 10 to demonstrate the use of while Loop


public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.print(i);

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

3.1 Program to demonstrate how to define a class and fields


class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Output: 0
Null
3.2 Program to demonstrate how to create an object and initialize it with reference

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();
}
}

Output: 331 Kalia


332 Tapu
3.4 Program to demonstrate how to create an object and initialize it with Constructor

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.

2. Runtime polymorphism: 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.

4.1 Program to define class, methods and objects

File Name: Person.Java


// Define a class named Person
public class Person {
// Fields (attributes) of the class
private String name;
private int age;
// Constructor to initialize the fields
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display the person's information
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}

// Method to set a new age


public void setAge(int age) {
if (age > 0) { // Simple validation
this.age = age;
} else {
System.out.println("Age must be positive.");
}
}

// Method to get the person's name


public String getName() {
return name;
}

// Method to get the person's age


public int getAge() {
return age;
}
}

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);

// Call methods on the object


person1.displayInfo();
// Update the age and display the updated info
person1.setAge(31);
System.out.println("Updated Age: " + person1.getAge());

// Create another object of the Person class


Person person2 = new Person("Alok", 25);
person2.displayInfo();
}
}

Output:
Name: Ashok
Age: 30
Updated Age: 31
Name: Alok
Age: 25

4.2 Demonstrate method overloading.

// Define a class named MethodOverload


public class MethodOverload{

// Method to add two integers


public int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers


public int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method to add two double values


public double add(double a, double b) {
return a + b;
}

public static void main(String[] args) {


// Create an object of the MethodOverload class
MethodOverload mo = new MethodOverload();

// Call the overloaded methods


System.out.println("Sum of 2 and 3 (int): " + mo.add(2, 3));
System.out.println("Sum of 1, 2, and 3 (int): " + mo.add(1, 2, 3));
System.out.println("Sum of 2.5 and 3.5 (double): " + mo.add(2.5, 3.5));

}
}

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.

5.1 Program to define inheritance.


File Name: Calculation.java
class Calculation {
int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y) {
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}

File Name: Calculation.java


public class My_Calculation extends
Calculation { public void
multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]) {
int a = 20, b = 10;
My_Calculation demo = new
My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
Compile the above class : javac My_Calculation.java
java My_Calculation
Output:
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

5.2 Program to demonstrate the Method Overriding in Polymorphism

File Name: Parent.java


class Parent {
void Print(){
System.out.println("parent class");
}
}
class subclass1 extends Parent {
void Print(){
System.out.println("subclass1");
}
}
class subclass2 extends Parent{
void Print(){
System.out.println("subclass2");
}
}
File Name: TestPolymorphism.java
class TestPolymorphism {
public static void main(String[] args){

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.

// Create the Package and Class in Package1


// File Name : Package1/Hello.java

package Package1;
public class Hello {
public void sayHello() {
System.out.println("Hello from Package1!");
}
}

//Create the Package and Class in Package2


// File: Package2/Example.java

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

Output: Hello from Package1!


Conclusion:
From the above experiment we can know about the Package and its implementation.
EXPERIMENT - 7
Name Of The Experiment:
Program to demonstrate Exception Handling.
Aim of The Experiment:
To study about Exception handling.
Software Requirement:
Windows 8
Notepad
JDK 8
Hardware Requirement:
Intel Processor
512 GB SSD
4 GB RAM
Theory:
Exception Handling:
The Exception Handling in Java is one of the powerful mechanisms to handle the runtime errors so that normal
flow of the application can be maintained.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at
runtime.
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked
exception. According to Oracle, there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1. Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as checked
exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile- time.
2. Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
Java Exception Keywords
1. try : The "try" keyword is used to specify a block where we should place exception code. The try block
must be followed by either catch or finally. It means, we can't use try block alone.
2. catch : The "catch" block is used to handle the exception. It must be preceded by try block which means
we can't use catch block alone. It can be followed by finally block later.
3. finally : The "finally" block is used to execute the important code of the program. It is executed whether
an exception is handled or not.
4. throw : The "throw" keyword is used to throw an exception.
5. throws : The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that
there may occur an exception in the method. It is always used with method signature.

Program to demonstrate the Exception Handling Program


File Name: TryCatchExample.java
public class TryCatchExample {
public static void main(String[] args) {
try {
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute

System.out.println("rest of the code");


}
// handling the exception
catch(ArithmeticException e){
System.out.println(e);
}

}
}

Compile the above class : javac TryCatchExample.java


java TryCatchExample
Output: java.lang.ArithmeticException: / by zero

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.

Commonly used Constructors of Thread class:


1. Thread()
2. Thread(String name)
3. Thread(Runnable r)
4. Thread(Runnable r,String name)
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be executed by a
thread. Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.

Program to demonstrate the threading using Thread class

Java Thread Example by extending Thread class File


Name: Multi.java
class Multi extends Thread{ public
void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi(); t1.start();
}
}
Compile the above class : javac Multi.java

java Multi
Output: thread is running...

Program to demonstrate the threading implementing Runnable interface


Java Thread Example by implementing Runnable interface

File Name: Multi1.java


class Multi1 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi1 m1=new Multi1(); Thread
t1 =new Thread(m1); t1.start();
}
}
Compile the above class : javac Multi1.java

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.

How to run an applet:


1. An applet can be executed by using browser (By html file).
In this case we have to define an html page with <applet code > ……… </applet>. This tag will link the applet
program and the size of its window. When this html file is opened using browser then the applet is executed.

2. By appletViewer tool ( for Testing purpose)


Program to demonstrate the applet
File Name: First.java
import java.awt.*;
import java.applet.*;
public class First extends Applet{
public void paint(Graphics g){
g.drawString(“Welcome to applet”,150,150);
}
}
/* <applet code= “First.class” width=”300” height=”300”>
</applet>
*/
Compile the above applet : Write in command prompt
C:\> javac First.java
C:]> appletviewer First.java
Output: Welcome to applet

Program on Event Handling:

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:

1. Create the Frame: Set up a JFrame to hold the GUI components.


2. Add Components: Include a JButton and a JLabel.
3. Handle Events: Attach an ActionListener to the button to handle click events.

File Name: SimpleEventHandling.java


Program to demonstrate Event Handling:

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SimpleEventHandling {


public static void main(String[] args) {
// Create the frame
JFrame frame = new JFrame("Event Handling Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 150);
frame.setLayout(null);

// 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);

// Add ActionListener to the button


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("Button clicked!");
}
});

// Set the frame visibility


frame.setVisible(true);
}
}

Compile the Program: javac EventHandlingExample.java


Java EventHandlingExample

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).

Program to demonstrate Layout managers:

import javax.swing.*;
import java.awt.*;

public class LayoutExample {


public static void main(String[] args) {
// Create the main frame
JFrame frame = new JFrame("Layout Managers Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setLayout(new GridLayout(1, 3)); // Set main layout to GridLayout

// Panel with FlowLayout


JPanel flowPanel = new JPanel();
flowPanel.setLayout(new FlowLayout());
flowPanel.add(new JButton("Button 1"));
flowPanel.add(new JButton("Button 2"));
flowPanel.add(new JButton("Button 3"));
flowPanel.add(new JButton("Button 4"));

// Panel with BorderLayout


JPanel borderPanel = new JPanel();
borderPanel.setLayout(new BorderLayout());
borderPanel.add(new JButton("North"), BorderLayout.NORTH);
borderPanel.add(new JButton("South"), BorderLayout.SOUTH);
borderPanel.add(new JButton("East"), BorderLayout.EAST);
borderPanel.add(new JButton("West"), BorderLayout.WEST);
borderPanel.add(new JButton("Center"), BorderLayout.CENTER);

// Panel with GridLayout


JPanel gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(2, 2));
gridPanel.add(new JButton("1"));
gridPanel.add(new JButton("2"));
gridPanel.add(new JButton("3"));
gridPanel.add(new JButton("4"));
// Add panels to the frame
frame.add(flowPanel);
frame.add(borderPanel);
frame.add(gridPanel);
// Make the frame visible
frame.setVisible(true);
}
}

Compile the program: javac LayoutExample.java


Java LayoutExample
Output:

Conclusion:
From the above experiment we can know about the different types of Layout managers.

You might also like