0% found this document useful (0 votes)
51 views28 pages

Exception Handling-Converted1

This document discusses exception handling in Java. It defines exceptions as problems or errors that disrupt normal program flow. There are three types of exceptions in Java: checked exceptions which must be handled at compile time, unchecked exceptions which occur at runtime, and errors which cannot typically be handled. The try-catch block is used to handle exceptions gracefully and allow code execution to continue normally. Finally blocks are used for cleanup code.

Uploaded by

Madhu Sudhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
51 views28 pages

Exception Handling-Converted1

This document discusses exception handling in Java. It defines exceptions as problems or errors that disrupt normal program flow. There are three types of exceptions in Java: checked exceptions which must be handled at compile time, unchecked exceptions which occur at runtime, and errors which cannot typically be handled. The try-catch block is used to handle exceptions gracefully and allow code execution to continue normally. Finally blocks are used for cleanup code.

Uploaded by

Madhu Sudhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 28

Exception Handling in Java

What is Exception?
An exception (or exceptional event) is a problem/ error that arises during the
execution of a program. When an Exception occurs the normal flow of the
program is disrupted and the program/Application terminates abnormally,
which is not recommended, therefore, these exceptions are to be handled.

An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.

 A user has entered an invalid data.


 The number is divided by zero.
 A file that needs to be opened cannot be found.Etc
Some of these exceptions are caused by user error, others by programmer
error, and others by physical resources that have failed in some manner.
Based on these, we have three categories of Exceptions.

Types of Java Exceptions:


there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

1. Checked exceptions: A checked exception is an exception that is


checked (notified) by the compiler at compilation-time, these are also
called as compile time exceptions. These exceptions cannot simply be
ignored, the programmer should take care of (handle) these exceptions.
E.g: IOException, SQLException,FileNotFoundException etc.

For example, if you use FileReader class in your program to read data
from a file, if the file specified in its constructor doesn't exist, then
a FileNotFoundException occurs, and the compiler prompts the
programmer to handle the exception.
importjava.io.File;
importjava.io.FileReader;

publicclassFilenotFound_Demo{

publicstaticvoid main(Stringargs[]){
Filefile=newFile("E://file.txt");
FileReaderfr=newFileReader(file);
}
}
If you try to compile the above program, you will get the following
exceptions.

Output:
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
FileReaderfr = new FileReader(file);
^
1 error

2. Unchecked exceptions:An unchecked exception is an exception that


occurs at the time of execution. These are also called as Runtime
Exceptions. These include programming bugs, such as logic errors or
improper use of an API.
Unchecked exceptions are not checked at compile-time, but they are
checked at runtime.
For example, if you have declared an array of size 5 in your program, and
trying to call the 6th element of the array then
an ArrayIndexOutOfBoundsExceptionexception occurs.

Example
PublicclassUnchecked_Demo
{

publicstaticvoid main(Stringargs[])
{
intnum[]={1,2,3,4};
System.out.println(num[5]);
}
}
If you compile and execute the above program, you will get the following
exception.

Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
atExceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

3) Error:These are not exceptions at all, but problems that arise beyond the
control of the user or the programmer. Errors are typically ignored in your code
because you can rarely do anything about an error. For example, stack
overflow, OutOfMemoryError,etc. They are also ignored at the time of
compilation.

Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The
exception class is a subclass of the Throwable class. Other than the exception
class there is another subclass called Error which is derived from the
Throwable class.

A hierarchy of Java Exception classes are given below:


What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of


the execution. An exception normally disrupts the normal flow of the
execution of the program and terminate the program abnormally, that is why
we use exception handling. Let's take a scenario:

statement 1;
statement 2;
statement 3;//exception occurs
statement 4;
statement 5;
statement 6;
Suppose there are 6 statements in our program and there occurs an exception
at statement 3, the rest of the code will not be executed i.e. statement 4 to 6
will not be executed. If we perform exception handling, the rest of the
statement will be executed. That is why we use exception handling in Java.

Java Exception Keywords

Java provides five keywords that are used to handle the exception. The
following table describes each.

Keyword Description

try The "try" keyword is used to specify a block where we


should place an exception code. It means we can't use try block
alone. The try block must be followed by either catch or finally.

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.
finally The "finally" block is used to execute the necessary code of
the program. It is executed whether an exception is handled or
not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It


specifies that there may occur an exception in the method. It
doesn't throw an exception. It is always used with method
signature.

Syntax:

try
{
// code that may raise exception
}
catch (ExceptionName e1)
{
// Catch block
}
//rest code of the program

Let's see an example of Java Exception Handling in which we are using a try-
catch statement to handle the exception.

JavaExceptionExample.java

public class JavaExceptionExample


{
public static void main(String args[])
{
try{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
}

Following is a list of most common checked and unchecked Java's Built-in


Exceptions.
Java defines several other types of exceptions that relate to its various class
libraries.

Following is the list of Java Unchecked RuntimeException.

Sl.No. Exception & Description


ArithmeticException
1
Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException
2
Array index is out-of-bounds.
ArrayStoreException
3
Assignment to an array element of an incompatible
type.
IllegalArgumentException
4
Illegal argument used to invoke a method.
IllegalStateException
5
Environment or application is in incorrect state.
IllegalThreadStateException
6
Requested operation not compatible with the current
thread state.
IndexOutOfBoundsException
7
Some type of index is out-of-bounds.
NegativeArraySizeException
8
Array created with a negative size.
NullPointerException
9
Invalid use of a null reference.
NumberFormatException
10
Invalid conversion of a string to a numeric format.
SecurityException
11
Attempt to violate security.
StringIndexOutOfBounds
12
Attempt to index outside the bounds of a string.
UnsupportedOperationException
13
An unsupported operation was encountered.

Following is the list of Java Checked Exceptions Defined in java.lang.

Sl.No. Exception & Description


1 ClassNotFoundException
Class not found.
2 CloneNotSupportedException
Attempt to clone an object that does not implement the
Cloneable interface.
3 IllegalAccessException
Access to a class is denied.
4 InstantiationException
Attempt to create an object of an abstract class or
interface.
5 InterruptedException
One thread has been interrupted by another thread.
6 NoSuchFieldException
A requested field does not exist.
7 NoSuchMethodException
A requested method does not exist.

Catching Exceptions
A method catches an exception using a combination of the try and catch
keywords. A try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected code, and
the syntax for using try/catch looks like the following –

Syntax
Try
{
// Protected code
} catch (ExceptionName e1)
{
// Catch block
}

The code which is prone to exceptions is placed in the try block. When an
exception occurs, that exception occurred is handled by catch block associated
with it. Every try block should be immediately followed either by a catch block
or finally block.
A catch statement involves declaring the type of exception you are trying to
catch. If an exception occurs in protected code, the catch block or blocks that
follows the try is checked. If the type of exception that occurred is listed in a
catch block, the exception is passed to the catch block much as an argument is
passed into a method parameter.
Example:
class Excep
{
public static void main(String args[])
{
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}

This will produce the following result −


Output:
Division by zero.
After catch statement.

Multiple Catch Blocks


A try block can be followed by multiple catch blocks. The syntax for multiple
catch blocks looks like the following −
Syntax
try {
// Protected code
}
catch (ExceptionType1 e1)
{
// Catch block
}
catch (ExceptionType2 e2)
{
// Catch block
}
catch (ExceptionType3 e3)
{
// Catch block

}
The previous statements demonstrate three catch blocks, but you can have any
number of them after a single try. If an exception occurs in the protected code,
the exception is thrown to the first catch block in the list. If the data type of the
exception thrown matches ExceptionType1, it gets caught there. If not, the
exception passes down to the second catch statement. This continues until the
exception either is caught or falls through all catches, in which case the
current method stops execution and the exception is thrown down to the
previous method on the call stack.

Example 1:
Here is code segment showing how to use multiple try/catch statements.
// Demonstrate multiple catch statements.
import java.util.*;
class Multi_Exec {
public static void main(String args[]) {
Scanner s=new Scanner(System.in);
try {
System.out.println("Enter Value");
int a = s.nextInt();
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}

Example 2:
// A Java program to demonstrate that we needed multiple catch blocks for
// multiple exceptions

import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
try
{
System.out.println(“Enter a value ");
int n = scn.nextInt();

if (99%n == 0)
System.out.println(n + " is a factor of 99");
}
catch (ArithmeticException ex)
{
System.out.println("Arithmetic " + ex);
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}
}
}
Output 1:
Enter a value
Madhu
Exception encountered java.lang.NumberFormatException:
For input string: "Madhu"
Output 2:
Enter a value
0
Arithmetic Exception encountered java.lang.ArithmeticException: / by zero

throw Keyword:
The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has


some message with it that provides the error description.

We can throw either checked or unchecked exceptions in Java by throw


keyword. It is mainly used to throw a custom exception.

The syntax of the Java throw keyword is given below.


throw throwableObject;

A throwableobject is an instance of class Throwable or subclass of


the Throwable class.
Example:
throw new ArithmeticException("/ by zero");

Example

Throw an exception if age is below 18 (print "Access denied"). If age is 18 or


older, print "Access granted":

public class Main


{
static void checkAge(int age)
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at least 18
years old.");
}
else
{
System.out.println("Access granted - You are old enough!");
}
}

public static void main(String[] args)


{
checkAge(15);
}
}

Output:

Exception in thread "main" java.lang.ArithmeticException: Access denied - You


must be at least 18 years old.

at Main.checkAge(Main.java:4)

at Main.main(Main.java:12)
throws Keyword:
If a method does not handle a checked exception, the method must declare it
using the throws keyword. The throws keyword appears at the end of a
method's signature.
A throws clause lists the types of exceptions that a method might throw. This is
necessary for all exceptions, except those of type Error or RuntimeException, or
any of their subclasses.
All other exceptions that a method can throw must be declared in the throws
clause. If they are not, a compile-time error will result.

This is the general form of a method declaration that includes a throws clause:

type method-name(parameter-list) throws exception-list


{
// body of method
}

Example throws Keyword

Here, we have a method that can throw Arithmetic exception so we mentioned


that with the method declaration and catch that using the catch handler in the
main method.

class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}

public static void main(String args[])


{
try
{
check();
}
catch(ArithmeticException e)
{
System.out.println("caught" + e);
}
}
}

Output:
Inside check function
caughtjava.lang.ArithmeticException: demo
Difference between throw and throws

throw throws

throws keyword is used to declare


throw keyword is used to throw an exception possible during its
an exception explicitly. execution.

throw keyword is followed by an throws keyword is followed by one


instance of Throwable class or one of or more Exception class names
its sub-classes. separated by commas.

throw keyword is declared throws keyword is used with


inside a method body. method signature (method declaration).

We can declare multiple


We cannot throw multiple
exceptions (separated by commas) using
exceptions using throw keyword.
throws keyword.

Finally Block:
The finally block follows a try block or a last catch block.

A finally block of code always executes, irrespective of occurrence of an


Exception.

The finally block in java is used to put important codes such as clean up
code e.g. closing the file or closing the connection.

The finally block executes whether exception rise or not and whether
exception handled or not.

A finally contains all the crucial statements regardless of the exception


occurs or not.
Syntax
try {
// Protected code
}
catch (ExceptionType1 e1)
{
// Catch block
}
catch (ExceptionType2 e2)
{
// Catch block
}
catch (ExceptionType3 e3)
{
// Catch block
}
Finally
{
// The finally block always executes.
}

There are 3 possible cases where finally block can be used:


Case 1: When an exception does not rise
In this case, the program runs fine without throwing any exception and finally
block execute after the try block.
import java.io.*;

class GFG {
public static void main(String[] args)
{
try {
System.out.println("inside try block");

// Not throw any exception


System.out.println(34 / 2);
}

// Not execute in this case


catch (ArithmeticException e) {

System.out.println("Arithmetic Exception");

}
// Always execute
finally {
System.out.println(
"finally : i execute always.");

}
}
}

Output
inside try block
17
finally : i execute always.

Case 2: When the exception rises and handled by the catch block
In this case, the program throws an exception but handled by the catch block,
and finally block executes after the catch block.
import java.io.*;

class GFG {

public static void main(String[] args)


{
try {
System.out.println("inside try block");

// Throw an Arithmetic exception


System.out.println(34 / 0);
}

// catch an Arithmetic exception


catch (ArithmeticException e) {

System.out.println(
"catch : exception handled.");
}

// Always execute
finally {

System.out.println("finally : i execute always.");


}
}
}
Output
inside try block
catch : exception handled.
finally : i execute always.

Case 3: When exception rise and not handled by the catch block
In this case, the program throws an exception but not handled by catch so
finally block execute after the try block and after the execution of finally block
program terminate abnormally, But finally block execute fine.
import java.io.*;

class GFG {
public static void main(String[] args)
{
try {
System.out.println("Inside try block");

// Throw an Arithmetic exception


System.out.println(34 / 0);
}

// Can not accept Arithmetic type exception


// Only accept Null Pointer type Exception
catch (NullPointerException e) {

System.out.println(
"catch : exception not handled.");
}

// Always execute
finally {

System.out.println(
"finally : i will execute always.");
}
// This will not execute
System.out.println("i want to run");
}
}
Output
Inside try block
finally : i will execute always.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at GFG.main(File.java:10)
Note the following −
 A catch clause cannot exist without a try statement.
 It is not compulsory to have finally clauses whenever a try/catch block is
present.
 The try block cannot be present without either catch clause or finally
clause.
 Any code cannot be present in between the try, catch, finally blocks.

User-defined/custom Exceptions:
Java provides us the facility to create our own exceptions which are basically
derived classes of Exception.
Creating our own Exception is known as a custom exception or user-defined
exception.
Basically, Java custom exceptions are used to customize the exception
according to user needs.
In simple words, we can say that a User-Defined Exception or custom
exception is creating your own exception class and throwing that exception
using the ‘throw’ keyword.

We can define our own Exception class as below −

class MyException extends Exception


{

You just need to extend the predefined Exception class to create your own
Exception. These are considered to be checked exceptions.

Example:

class MyException extends Exception


{
MyException (String str)
{
// calling the constructor of parent Exception
super(str);
}

// method to check the age


static void validate (int age) throws MyException{
if(age < 18){

// throw an object of user defined exception


throw new MyException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}

// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (MyException ex)
{
System.out.println("Caught the exception");

// printing the message from InvalidAgeException object


System.out.println("Exception occured: " + ex);
}

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


}
}

Output:

F:\java>java MyException

Caught the exception

Exception occured: MyException: age is not valid to vote

rest of the code...


Collections in Java:

The Java Collections Framework is a collection of interfaces and classes, which


helps in storing and processing the data efficiently. This framework has several
useful classes which have tons of useful functions which makes a programmer
task easy.

Hierarchy of Collection Framework


Iterator interface

Iterator interface provides the facility of iterating the elements in a forward


direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:

Method Description
hasNext() It returns true if the iterator has more elements
otherwise it returns false.
next() It returns the element and moves the cursor
pointer to the next element.
remove() It removes the last elements returned by the
iterator. It is less used.

Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

Method Description

add(object e) It is used to insert an element in this collection.

remove(Object It is used to delete an element from the collection.


element)

size() It returns the total number of elements in the


collection.

clear() It removes the total number of elements from the


collection.

contains(Object It is used to search an element.


element)

public Iterator It returns an iterator.


iterator()

public Object[] It converts collection into array.


toArray()

isEmpty() It checks if collection is empty.

equals(Object element) It matches two collections.


List Interface:

A List is an ordered Collection (sometimes called a sequence). Lists may contain


duplicate elements. Elements can be inserted or accessed by their position in the
list, using a zero-based index. The classes that implements List interface are:

 ArrayList
 LinkedList
 Vector
 Stack

Methods of List:
The List interface includes all the methods of the Collection interface. Its because
Collection is a super interface of List.

Some of the commonly used methods of the Collection interface that's also
available in the List interface are:

 add() - adds an element to a list


 addAll() - adds all elements of one list to another
 get() - helps to randomly access elements from lists
 iterator() - returns iterator object that can be used to sequentially access
elements of lists
 set() - changes elements of lists
 remove() - removes an element from the list
 removeAll() - removes all the elements from the list
 clear() - removes all the elements from the list (more efficient than
removeAll())
 size() - returns the length of lists
 toArray() - converts a list into an array
 contains() - returns true if a list contains specified element

Arraylist:
 Java ArrayList class uses a dynamic array for storing the elements.
 It is like an array, but there is no size limit.
 We can add or remove elements anytime. So, it is much more flexible than
the traditional array.
 It is found in the java.util package. It is like the Vector in C++.

 The ArrayList in Java can have the duplicate elements also.


 It implements the List interface so we can use all the methods of the List
interface here.
 The ArrayList maintains the insertion order internally.

Creating an ArrayList
Before using ArrayList, we need to import the java.util.ArrayList package first.
Here is how we can create arraylists in Java:
ArrayList<Type> arrayList= new ArrayList<>();

Here, Type indicates the type of an arraylist.

For example,

// create Integer type arraylist


ArrayList<Integer> arrayList = new ArrayList<>();

// create String type arraylist


ArrayList<String> arrayList = new ArrayList<>();

In the above program, we have used Integer not int. It is because we cannot use
primitive types while creating an arraylist. Instead, we have to use the
corresponding wrapper classes.

import java.util.*;
class ArrayListExample
{
public static void main(String args[])
{

ArrayList al=new ArrayList(); // creating array list


al.add("Amar"); // adding elements
al.add("Akbar");
System.out.println(“Array list elements are:”);
System.out.println(al);
}
}
}
Output:
Amar
Akbar

Linked List:
Linked List is a sequence of links which contains items. Each link contains a
connection to another link.

Syntax: Linkedlist object = new Linkedlist();

Java Linked List class uses two types of Linked list to store the elements:

 Singly Linked List


 Doubly Linked List
Singly Linked List: In a singly Linked list each node in this list stores the data
of the node and a pointer or reference to the next node in the list. Refer to the
below image to get a better understanding of single Linked list.

Doubly Linked List: In a doubly Linked list, it has two references, one to the
next node and another to previous node. You can refer to the below image to get
a better understanding of doubly linked list.
Some of the methods in the linked list are listed below:

Method Description
It is used to append the specified element to the end
boolean add( Object o)
of the list.
boolean Returns true if this list contains the specified
contains(Object o) element.
void add (int index, Inserts the element at the specified element in the
Object element) list.
It is used to insert the given element at the
void addFirst(Object o)
beginning.
void addLast(Object o) It is used to append the given element to the end.
int size() It is used to return the number of elements in a list
boolean remove(Object Removes the first occurrence of the specified element
o) from this list.
int indexOf(Object Returns the index of the first occurrence of the
element) specified element in this list, or -1.
int lastIndexOf(Object Returns the index of the last occurrence of the
element) specified element in this list, or -1.

Consider the following example.


import java.util.*;
public class linkedlist
{
public static void main(String args[])
{
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
System.out.println(al);
}
}
Output:
Ravi
Vijay
Ravi
Ajay

Vector:
Vector uses a dynamic array to store the data elements. It is similar to ArrayList.
However, It is synchronized and contains many methods that are not the part of
Collection framework.

Creating a Vector
Here is how we can create vectors in Java.

Vector<Type> vector = new Vector<>();

Here, Type indicates the type of a linked list. For example,

// create Integer type linked list


Vector<Integer> vector= new Vector<>();

// create String type linked list


Vector<String> vector= new Vector<>();

Methods of Vector

add(element) - adds an element to vectors


add(index, element) - adds an element to the specified position
addAll(vector) - adds all elements of a vector to another vector
get(index) - returns an element specified by the index
iterator() - returns an iterator object to sequentially access vector elements
remove(index) - removes an element from specified position
removeAll() - removes all the elements
clear() - removes all elements. It is more efficient than removeAll()
toString()-converts the vector into a String
contains()-searches the vector for specified element and returns a boolean result

Consider the following example.

import java.util.Vector;

class Main {
public static void main(String[] args) {
Vector<String> animals= new Vector<>();
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");

System.out.println("Initial Vector: " + animals);

// Using remove()
String element = animals.remove(1);
System.out.println("Removed Element: " + element);
System.out.println("New Vector: " + animals);

// Using clear()
animals.clear();
System.out.println("Vector after clear(): " + animals);
}
}

Output:
Initial Vector: [Dog, Horse, Cat]
Removed Element: Horse
New Vector: [Dog, Cat]
Vector after clear(): []

Stack:
The stack is a linear data structure that is used to store the collection of objects.
It is based on Last-In-First-Out (LIFO). Java collection framework provides many
interfaces and classes to store the collection of objects. One of them is the Stack
class that provides different operations such as push, pop, search, etc.

The stack data structure has the two most important operations that are push
and pop. The push operation inserts an element into the stack and pop
operation removes an element from the top of the stack. Let's see how they work
on stack.

Creating a Stack
If we want to create a stack, first, import the java.util package and create an
object of the Stack class.

Stack stk = new Stack();


Or
Stack<type> stk = new Stack<>();

Methods of the Stack Class

Method Method Description

empty() The method checks the stack is empty or not.

push(E item) The method pushes (insert) an element onto the


top of the stack.

pop() The method removes an element from the top of


the stack and returns the same element as the
value of that function.

peek() The method looks at the top element of the stack


without removing it.

search(Object o) The method searches the specified object and


returns the position of the object.

Example:
import java.util.Stack;
public class StackExample
{
public static void main(String[] args)
{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();
// checking stack is empty or not
boolean result = stk.empty();
System.out.println("Is the stack empty? " + result);
// pushing elements into stack
stk.push(78);
stk.push(113);
stk.push(90);
stk.push(120);
//prints elements of the stack
System.out.println("Elements in Stack: " + stk);
System.out.println("poped Element in Stack: " + stk.pop());
result = stk.empty();
System.out.println("Is the stack empty? " + result);
}
}
Output:
Is the stack empty? true
Elements in Stack: [78, 113, 90, 120]
poped Element in Stack:120
Is the stack empty? False
Introduction to JavaBeans:

JavaBeans are classes that encapsulate many objects into a single object (the
bean). It is a java class that should follow following conventions:

 Must implement Serializable.


 It should have a public no-arg constructor (default constructor).
 All properties in java bean must be private with public getters and setter
methods.

Here are the key characteristics of JavaBeans:

 Properties: JavaBeans have properties, which are private instance


variables that can be accessed through getter and setter methods. These
methods follow a naming convention: getPropertyName for the getter and
setPropertyName for the setter.

 Methods: JavaBeans can have methods beyond the standard getter and
setter methods. These methods enable the component to perform various
actions and operations.

 Events: JavaBeans can generate and handle events. Events are


notifications that something has happened, such as a button click or a
value change. JavaBeans allow event listeners to be registered and
triggered when events occur.

 Serialization: JavaBeans support serialization, which means they can be


converted into a format that can be easily stored and transmitted. This is
important for scenarios like saving the state of a component to a file or
sending it over a network.

 Customization: JavaBeans can be customized using GUI builders or IDEs.


This means that properties and events can be set visually, making them
ideal for GUI components.

Example:

// Java Program of JavaBean class


Import java.io.*;
public class Student implements Serializable
{
private int id;
private String name;
public Student()
{
}
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}

// Java program to access JavaBean class


public class Test {
public static void main(String args[])
{
Student s = new Student(); // object is created
s.setName("BCA"); // setting value to the object
System.out.println(s.getName());
}
}

Output:
BCA

You might also like