OOP With Java Lab Manual
OOP With Java Lab Manual
EXPERIMENT-1
Aim:
Theory:
1. Simple If statement:
The general form of single if statement is :
if ( test expression)
{
statement-Block;
}
statement-Blocks;
Example:
int x = 20;
int y = 18;
if (x > y)
{
System.out.println("x is greater than y");
}
if ( test expression)
{
statement-block1;
}
else
{
statement-block2
}
Example:
int time = 20;
if (time < 18)
{
System.out.println("Good day.");
}
else
{
System.out.println("Good evening.");
}
// Outputs "Good evening."
3. Else-if statement:
general form of else-if statement is:
if ( test condition)
{
statement-block1;
}
else if(test expression2)
{
statement-block2;
}
else
{
statement block3;
}
Example:
int time = 22;
if (time < 10)
{
System.out.println("Good morning.");
}
else if (time < 20)
{
System.out.println("Good day.");
}
else
{
System.out.println("Good evening.");
}
// Outputs "Good evening."
Example:
percentage=65;
if (percentage>=60)
{
if (percentage>=70)
{
System.out.println(“Distinction");
}
else
{
System.out.println(“First Class");
}
}
else
{
System.out.println(“Second Class");
}
switch ( expression)
{
case value-1: block-1;
break;
case value-2: block-2;
break;
......
default: default block;
break;
}
Example:
int day = 4;
switch (day)
{
case 1: System.out.println("Monday");
break;
case 2: System.out.println("Tuesday");
break;
case 3: System.out.println("Wednesday");
break;
case 4: System.out.println("Thursday");
break;
case 5: System.out.println("Friday");
break;
case 6: System.out.println("Saturday");
break;
case 7: System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4)
Loops In Java:
▪ In looping a sequence of statements are executed until a number of time or until some condition
for the loop is being satisfied.
▪ Any looping process includes following four steps:
(1) Setting an initialization for the counter.
(2) Execution of the statement in the loop
(3) Test the specified condition for the loop.
(4) Incrementing the counter.
Java includes three loops. They are:
1. while loop
2. do loop
3. for loop
1) while loop:
The general structure of a while loop is:
Initialization
while (test condition)
{
body of the loop
}
Example:
int i = 0;
while (i < 5)
{
System.out.println(i);
i++;
}
2) do loop:
The general structure of a do loop is :
Initialization
do
{
Body of the loop;
}
while ( test condition);
Example:
int i = 0;
do
{
System.out.println(i);
i++;
} while (i < 5);
3) for loop :
The general structure of for loop is:
for ( Initialization ; Test condition ; Increment)
{
body of the loop;
Example:
for (int i = 0; i < 5; i++)
{
System.out.println(i);
}
Program 1. Write a Java Program to demonstrate Basic programming constructs like branching
and looping.
import java.util.*;
public class DemoBranchingLooping
{
public static void main(String[] args)
{
int i,b,n,j;
String c;
int fact=1;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number:");
n=sc.nextInt();
do
{
System.out.println("\n**Menu...**");
System.out.println("1. Factorial\n2. Print Pattern\n");
System.out.println("Enter the operation to be performed:");
b=sc.nextInt();
switch(b)
{
case 1:
for(i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("\nFactorial of entered number is:"+fact);
break;
case 2:
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.print("\n");
}
break;
default:
System.out.println("\nPlease enter the correct option");
}
Sample Output:
Conclusion: Implemented and demonstrated program on Basic programming constructs like branching
and looping in Java.
EXPERIMENT-2
Aim:
Theory:
Scanner Class
▪ Added by JDK 5, Scanner reads formatted input and converts it into its binary form.
▪ Because of the addition of Scanner, it is now easy to read all types of numeric values, strings,
and other types of data, whether it comes from a disk file, the keyboard, or another source.
▪ Scanner can be used to read input from the console, a file, a string, or any source that
implements the Readable interface or ReadableByteChannel.
▪ For example, you can use Scanner to read a number from the keyboard and assign its value to a
variable.
import java.util.*;
public class UnsignedRightShift
{
public static void main(String[] args)
{
int a;
int b;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a positive value for x:");
a=sc.nextInt();
System.out.println("Enter a negative value for y:");
b=sc.nextInt();
Sample Output:
EXPERIMENT-3
Aim:
Theory:
Class:
▪ A class is a template for an object, and defines the data fields and methods of the object.
▪ The class methods provide access to manipulate the data fields.
▪ The “Data fields” of an object are often called “Instance variables”.
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method
}
}
Creating Objects:
▪ when a class is created , we are creating a new data type.
▪ We can use this type to declare objects of that type.
▪ However, obtaining objects of a class is a two-step process.
▪ First, we must declare a variable of the class type. This variable does not define an object.
Instead, it is simply a variable that can refer to an object.
Rectangle rect1;
▪ Second, we must acquire an actual, physical copy of the object and assign it to that variable by
using the new operator.
rect1=new Rectangle();
▪ The new operator dynamically allocates (that is, allocates at run time) memory for an object
and returns a reference to it.
▪ Following statement combines the two steps just described.
Rectangle rect1 =new Rectangle();
Program 3. Write a Java Program to define a class, define instance methods for setting and
Retrieving values of instance variables and instantiate its object.
import java.lang.*;
class Emp
{
String name;
int id;
String address;
void getdata(String name,int id,String address)
{
this.name=name;
this.id=id;
this.address=address;
}
void putdata()
{
System.out.println("Employee details are :");
System.out.println("Name :" +name);
System.out.println("ID :" +id);
System.out.println("Address :" +address);
}
}
class EmpDemo
{
public static void main(String args[])
{
Emp e=new Emp();
e.getdata("Smith",76859,"London");
e.putdata();
}
}
Sample Output:
Conclusion: Implemented and demonstrated Program to define a class, define instance methods for
setting and Retrieving values of instance variables and instantiate its object in Java.
EXPERIMENT-4
Aim:
Theory:
Method Overloading:
▪ Two or more methods have the same names but different argument lists.
▪ The arguments may differ in type or number, or both.
▪ However, the return types of overloaded methods can be the same or different is called method
overloading.
Example:
class MethodOverloading
{
int add( int a, int b)
{
return(a+b);
}
float add(float a, float b)
{
return(a+b);
}
double add( int a, double b, double c)
{
return(a+b+c);
}
}
Constructors:
▪ It can be tedious to initialize all of the variables in a class each time an instance is created.
▪ Thus automatic initialization is performed through the use of a constructor.
▪ A constructor initializes an object immediately upon creation.
▪ It has the same name as the class in which it resides and is syntactically similar to a method.
▪ the constructor is automatically called immediately after the object is created, before the new
operator completes.
▪ Constructors have no return type, not even void.
▪ This is because the implicit return type of a class’ constructor is the class type itself.
Example:
class Student
{
String name,location;
int postid;
Student()
{
name="Shreya";
location="Mumbai";
postid=400020;
}
Student(String name,String location,int postid)
{
this.name=name;
this.location=location;
this.postid=postid;
}
void display()
{
System.out.println(name +"\t"+location +"\t" +postid);
}
}
Program 4.A. Write a Java Program to define a class, define instance methods and overload
them and use them for dynamic method invocation.
class MethodOverloading
{
void display(int a,int b)
{
int result=a+b;
System.out.println("The sum of 2 integers are:" +result);
}
void display(double a,double b)
{
double result=a+b;
System.out.println("The sum of 2 floating numbers are:" +result);
}
void display(int a,int b,int c)
{
int result=a+b+c;
System.out.println("The sum of 3 integers are:" +result);
}
void display(int a,double b)
{
double result=a+b;
System.out.println("The sum an integer with a floating number is:" +result);
}
}
class MethodOverloadingDemo
{
public static void main(String d[])
{
MethodOverloading obj=new MethodOverloading();
obj.display(5,8);
obj.display(5.11,8.43);
obj.display(5,8,4);
obj.display(5,8.0132);
}
}
Sample Output:
Program 4.B. Write a Java Program to define a class, describe its constructor, overload the
Constructors and instantiate its object.
class Student
{
String name,location;
int postid;
Student()
{
name="Shreya";
location="Mumbai";
postid=400020;
}
Student(String name,String location,int postid)
{
this.name=name;
this.location=location;
this.postid=postid;
}
void display()
{
System.out.println(name +"\t"+location +"\t" +postid);
}
}
class ConstructorsDemo
{
public static void main(String args[])
{
Student s1= new Student();
Student s2=new Student("Aniket","Mumbai", 400080);
s1.display();
s2.display();
}
}
Sample Output:
Conclusion: Implemented and demonstrated Program on method and constructor overloading in Java.
EXPERIMENT-5
Aim:
Program on Packages.
Theory:
Packages:
▪ Package is a mechanism for partitioning the class name-space into more manageable chunks.
▪ A java package is a group of similar types of classes, interfaces and sub-packages.
▪ The package is both a naming and a visibility control mechanism.
▪ It is possible to define classes inside a package that are not accessible by code outside that
package.
▪ We can define class members that are only exposed to other members of the same package.
▪ Package in java can be categorized in two form,
• Built-in package
• User-defined package.
▪ There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Defining a Package
▪ To create a package ,simply include a package command as the first statement in a Java source
file.
▪ Any classes declared within that file will belong to the specified package.
▪ The package statement defines a name space in which classes are stored.
▪ If we skip the package statement, the class names are put into the default package, which has
no name.
▪ The general form of the package statement:
package pkg;
▪ Here, pkg is the name of the package.
▪ For example, the following statement creates a package called MyPackage.
package MyPackage;
▪ The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
Example:
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
1) Using packagename.*
▪ If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
▪ The import keyword is used to make the classes and interface of another package accessible to
the current package.
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Program 5. Write a Java program to implement the concept of importing classes from user
defined package and creating packages.
package package1;
public class PackageStudent
{
int regno;
String name;
public void getdata(int r,String s)
{
regno=r;
name=s;
}
public void putdata()
{
System.out.println("Registration Number = " +regno);
System.out.println("Name = " + name);
}
}
import package1.*;
class PackageStudentDemo
{
public static void main(String arg[])
{
PackageStudent s=new PackageStudent();
s.getdata(111,"Saket Joshi");
s.putdata();
}
}
Sample Output:
Conclusion: Implemented and demonstrated program to implement the concept of importing classes
from user defined package and creating packages in Java.
EXPERIMENT-6
Aim:
Theory:
Array:
▪ An array is a group of like-typed variables that are referred to by a common name.
▪ Arrays of any type can be created and may have one or more dimensions.
▪ A specific element in an array is accessed by its index.
▪ Arrays offer a convenient means of grouping related information.
One-Dimensional Arrays
▪ A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you
first must create an array variable of the desired type.
▪ The general form of a one-dimensional array declaration is
type var-name[ ];
▪ Here, type declares the base type of the array.
▪ The base type determines the data type of each element that comprises the array.
▪ Thus, the base type for the array determines what type of data the array will hold.
▪ For example,
int month_days[];
▪ Although this declaration establishes the fact that month_days is an array variable, no array
actually exists.
▪ In fact, the value of month_days is set to null, which represents an array with no value.
▪ To link month_days with an actual, physical array of integers, you must allocate one using new
and assign it to month_days.
▪ new is a special operator that allocates memory.
▪ The general form of new as it applies to one-dimensional arrays appears as follows:
array-var = new type[size];
▪ Here,
type specifies the type of data being allocated,
size specifies the number of elements in the array, and
array-var is the array variable that is linked to the array
▪ For example,
month_days = new int[12];
▪ This example,
allocates a 12-element array of integers and links them to month_days.
month_days will refer to an array of 12 integers.
all elements in the array will be initialized to zero.
Multidimensional Arrays
▪ In Java, multidimensional arrays are actually arrays of arrays.
▪ To declare a multidimensional array variable, specify each additional index using another set of
square brackets.
▪ For example, the following declares a two dimensional array variable called twoD
int twoD[][] = new int[4][5];
▪ This allocates a 4 by 5 array and assigns it to twoD.
▪ Internally this matrix is implemented as an array of arrays of int.
Strings:
▪ In Java a string is a sequence of characters.
▪ But, unlike many other languages that implement strings as character arrays, Java implements
strings as objects of type String.
String Constructors:
▪ The String class supports several constructors.
▪ To create an empty String, you call the default constructor.
▪ For example,
String s = new String();
will create an instance of String with no characters in it.
▪ To create a String initialized by an array of characters, use the constructor shown here:
String(char chars[ ])
▪ Here is an example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string “abc”.
▪ You can specify a subrange of a character array as an initializer using the following
constructor:
▪ Here, startIndex specifies the index at which the subrange begins, and numChars specifies the
number of characters to use.
▪ Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
▪ This initializes s with the characters cde.
▪ You can construct a String object that contains the same character sequence as another String
object using this constructor:
String(String strObj)
▪ Here, strObj is a String object.
import java.util.*;
class MatrixMultiDemo
{
public static void main(String args[])
{
int m, n, p, q, sum=0, i, j, k;
Scanner sc=new Scanner(System.in);
System.out.println("Enter no. of rows and columns of 1st matrix:");
m=sc.nextInt();
n=sc.nextInt();
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
second[i][j]=sc.nextInt();
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
System.out.print(mult[i][j]+"\t");
}
System.out.println("\n");
}
}
}
Sample Output:
Program 6.B. Write a Java program to practice using String class and its methods.
import java.lang.String;
class StringDemo
{
public static void main(String arg[])
{
String s1=new String("mumbai maharashtra");
String s2="MUMBAI MAHARASHTRA";
System.out.println(" The string s1 is : " +s1);
System.out.println(" The string s1 is : " +s2);
System.out.println(" Length of the string s1 is : " +s1.length());
System.out.println(" The first accurence of r is at the position : " +s1.indexOf('r'));
System.out.println(" The String in Upper Case : " +s1.toUpperCase());
System.out.println(" The String in Lower Case : " +s1.toLowerCase());
System.out.println(" s1 equals to s2 : " +s1.equals(s2));
System.out.println(" s1 equals ignore case to s2 : " +s1.equalsIgnoreCase(s2));
int result=s1.compareTo(s2);
System.out.println("After compareTo()");
if(result==0)
System.out.println( s1 + " is equal to "+s2);
else if(result>0)
System.out.println( s1 + " is greather than to "+s2);
else
System.out.println( s1 + " is smaller than to "+s2);
System.out.println(" Character at an index of 4 is :" +s1.charAt(4));
String s3=s1.substring(4,12);
Sample Output:
EXPERIMENT-7
Aim:
Theory:
String Buffer:
▪ StringBuffer is a peer class of String that provides much of the functionality of strings.
▪ String represents fixed-length, immutable character sequences.
▪ In contrast, StringBuffer represents growable and writeable character sequences.
▪ StringBuffer may have characters and substrings inserted in the middle or appended to the end.
▪ StringBuffer will automatically grow to make room for such additions and often has more
characters preallocated than are actually needed, to allow room for growth.
StringBuffer Constructors
StringBuffer defines these four constructors:
• StringBuffer( )
• StringBuffer(int size)
• StringBuffer(String str)
• StringBuffer(CharSequence chars)
StringBuffer( )
▪ The default constructor (the one with no parameters) reserves room for 16 characters
without reallocation.
StringBuffer(int size)
▪ This version accepts an integer argument that explicitly sets the size of the buffer.
StringBuffer(String str)
▪ This version accepts a String argument that sets the initial contents of the StringBuffer
object and reserves room for 16 more characters without reallocation.
▪ StringBuffer allocates room for 16 additional characters when no specific buffer length
is requested, because reallocation is a costly process in terms of time.
▪ Also, frequent reallocations can fragment memory.
▪ By allocating room for a few extra characters, StringBuffer reduces the number of
reallocations that take place.
StringBuffer(CharSequence chars)
▪ This constructor creates an object that contains the character sequence contained in
chars.
Vectors:
▪ Vector implements a dynamic array.
▪ It is similar to ArrayList, but with two differences:
• Vector is synchronized
• Vector contains many legacy methods that are not part of the Collections Framework.
▪ With the advent of collections, Vector was reengineered to extend AbstractList and to
implement the List interface.
Advantages:
• It is convenient to use vectors to store objects.
• It can be used to store list of objects that may vary in size.
• We can add and delete objects from the list as and when required.
▪ Vector(int size)
This creates a vector whose initial capacity is specified by size.
▪ Vector(Collection c)
This creates a vector that contains the elements of collection c.
Program 7.A. Write a Java program to practice using String Buffer class and its methods.
import java.lang.String;
class StringBufferDemo
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("This is my college");
System.out.println("This string sb is : " +sb);
System.out.println("The length of the string sb is : " +sb.length());
System.out.println("The capacity of the string sb is : " +sb.capacity());
System.out.println("The character at an index of 6 is : " +sb.charAt(6));
sb.setCharAt(3,'x');
System.out.println("After setting char x at position 3 : " +sb);
System.out.println("After appending : " +sb.append(" in Mumbai"));
System.out.println("After inserting : " +sb.insert(19, "SAKEC "));
System.out.println("After deleting : " +sb.delete(19,24));
}
}
Sample Output:
Program 7.B. Write a Java Program to implement Vector class and its methods.
import java.lang.*;
import java.util.Vector;
import java.util.Enumeration;
class VectorDemo
{
public static void main(String arg[])
{
Vector v=new Vector();
v.addElement("one");
v.addElement("two");
v.addElement("three");
v.insertElementAt("zero",0);
v.insertElementAt("oops",3);
v.insertElementAt("four",5);
System.out.println("Vector Size :"+v.size());
System.out.println("Vector apacity :"+v.capacity());
System.out.println(" The elements of a vector are :");
Enumeration e=v.elements();
while(e.hasMoreElements())
System.out.println(e.nextElement() +" ");
System.out.println();
System.out.println("The first element is : " +v.firstElement());
System.out.println("The last element is : " +v.lastElement());
System.out.println("The object oops is found at position : "+v.indexOf("oops"));
v.removeElement("oops");
v.removeElementAt(1);
System.out.println("After removing 2 elements ");
System.out.println("Vector Size :"+v.size());
System.out.println("The elements of vector are :");
for(int i=0;i<v.size();i++)
System.out.println(v.elementAt(i)+" ");
}
}
Sample Output:
Conclusion: Implemented and demonstrated Program on String Buffer and Vectors in Java.
EXPERIMENT-8
Aim:
Program on types of inheritance
Theory:
Inheritance:
▪ One class can acquire the properties of another class.
▪ a class that is inherited is called a superclass.
▪ The class that does the inheriting is called a subclass.
▪ Therefore, a subclass is a specialized version of a superclass.
▪ It inherits all of the instance variables and methods defined by the superclass and adds its own,
unique elements.
▪ To inherit a class, simply incorporate the definition of one class into another by using the
extends keyword.
Types of Inheritance:
▪ Single Inheritance
▪ Multilevel Inheritance
▪ Multiple Inheritance
▪ Hierarchical Inheritance
▪ Hybrid Inheritance
1. Single Inheritance
• When a subclass is derived simply from its parent class then this mechanism is known as
simple inheritance.
• In case of simple inheritance there is only a sub class and its parent class.
• It is also called single inheritance or one level inheritance
2. Multilevel Inheritance
• When a subclass is derived from a derived class then this mechanism is known as the
multilevel inheritance.
• The derived class is called the subclass or child class for it's parent class and this parent class
works as the child class for it's just above ( parent ) class.
• Multilevel inheritance can go up to any number of level.
3. Hierarchical Inheritance
• When two or more classes inherits a single class, it is known as hierarchical inheritance.
Program 8. Write a Java Program to implement inheritance and demonstrate use of method
overriding.
import java.lang.*;
class College
{
College()
{
System.out.println("SAKEC ");
}
}
class InheritanceTypesDemo
{
public static void main(String arg[])
{
System.out.println("Single Inheritance ");
Department dept=new Department();
System.out.println("\nMultilevel Inheritance");
Employee emp=new Employee (123, "Prof. Ramana Shastri");
System.out.println("\nHirarchical Inheritance");
Student std=new Student (10, "Rakesh Jain");
}
}
Sample Output:
EXPERIMENT-9
Aim:
Program on Multiple Inheritance
Theory:
Interfaces:
▪ An interface in Java is a blueprint of a class.
▪ Interfaces are syntactically similar to classes.
▪ It has static constants and abstract methods.
▪ The interface in Java is a mechanism to achieve abstraction.
▪ There can be only abstract methods in the Java interface, not method body.
▪ It is used to achieve abstraction and multiple inheritance in java.
▪ In other words, you can say that interfaces can have abstract methods and variables.
▪ It cannot have a method body.
▪ Once interface is defined, any number of classes can implement an interface.
▪ Also, one class can implement any number of interfaces.
Defining an Interface
▪ An interface is defined much like a class.
▪ This is the general form of an interface:
▪ No access specifier: interface is only available to other members of the package in which
it is declared.
▪ Public access specifier: the interface can be used by any other code.
▪ name is the name of the interface, and can be any valid identifier.
Implementing Interfaces
▪ Once an interface has been defined, one or more classes can implement that interface.
▪ To implement an interface, include the implements clause in a class definition, and then create
the methods defined by the interface.
▪ The general form of a class that includes the implements clause looks like this:
▪ If a class implements more than one interface, the interfaces are separated with a comma.
▪ If a class implements two interfaces that declare the same method, then the same method will
be used by clients of either interface.
▪ The methods that implement an interface must be declared public.
▪ Also, the type signature of the implementing method must match exactly the type signature
specified in the interface definition
Program 9. Write a Java Program to implement multiple inheritance and demonstrate use of
interfaces.
interface Citizen
{
String name="Raman";
abstract void showCitizen();
}
interface Employee
{
int eno=75;
int salary=50000;
abstract void showEmployee();
}
System.out.println("Publications="+publications);
}
}
class MultiInheriInterfaceDemo
{
public static void main(String args[])
{
Professor p=new Professor();
p.showCitizen();
p.showEmployee();
p.showProfessor();
}
}
Sample Output:
EXPERIMENT-10
Aim:
Program on Exception handling
Theory:
Exception-Handling Fundamentals
▪ A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code.
▪ When an exceptional condition arises, an object representing that exception is created and
thrown in the method that caused the error.
▪ That method may choose to handle the exception itself, or pass it on.
▪ Either way, at some point, the exception is caught and processed.
▪ Exceptions can be generated by the Java run-time system, or they can be manually generated
by your code.
▪ Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java
language or the constraints of the Java execution environment.
▪ The unexpected situations that may occur during program execution are:
• Running out of memory
• Resource allocation errors
• Inability to find files
• Problems in network connectivity
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
try Block:
▪ The java code that you think may produce an exception is placed within a try block for a
suitable catch block to handle the error.
▪ If no exception occurs the execution proceeds with the finally block else it will look for the
matching catch block to handle the error.
▪ Again if the matching catch handler is not found execution proceeds with the finally block and
the default exception handler throws an exception.
catch Block:
▪ Exceptions thrown during execution of the try block can be caught and handled in a catch
block.
▪ On exit from a catch block, normal execution continues and the finally block is executed
(Though the catch block throws an exception).
finally Block:
▪ A finally block is always executed, regardless of the cause of exit from the try block, or
whether any catch block was executed.
▪ Generally finally block is used for freeing resources, cleaning up, closing connections etc.
Program 10. Write a Java program to implement the concept of Exception Handling using
predefined exception.
import java.io.*;
import java.util.*;
class ExceptionHandlingDemo
{
public static void main(String ar[])throws IOException
{
int a,b,res;
Scanner sc=new Scanner(System.in);
System.out.println("Enter 2 numbers:");
a=sc.nextInt();
b=sc.nextInt();
try
{
res=a/b;
System.out.println("The Quotient="+res);
}
catch(ArithmeticException e)
{
System.out.println("\nException has occored,You have entered the Divisor as
Zero\n"+e);
}
finally
{
System.out.println("\nIn finally block..");
}
}
}
Sample Output 1:
Sample Output 2:
EXPERIMENT-11
Aim:
Program on user defined exception
Theory:
Program 11. Write a Java program to implement the concept of Exception Handling by creating
user defined exceptions.
import java.lang.Exception;
import java.lang.*;
import java.lang.Exception;
import java.io.DataInputStream;
class UserDefinedExceptionDemo
{
public static void main(String a[])
{
int age;
DataInputStream ds=new DataInputStream(System.in);
try
{
System.out.println("Enter the age (above 15 and below 25) :");
age=Integer.parseInt(ds.readLine());
if(age<15 || age> 25)
{
throw new MyException("Number not in range");
}
System.out.println(" the number is :" +age);
}
catch(MyException e)
{
System.out.println("Caught MyException");
System.out.println(e.getMessage());
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Sample Output 1:
Sample Output 2:
EXPERIMENT-12
Aim:
Program on Multithreading.
Theory:
JAVA Threads
▪ Java provides built-in support for multithreaded programming.
▪ A multithreaded program contains two or more parts that can run concurrently.
▪ Each part of such a program is called a thread, and each thread defines a separate path of
execution.
▪ Thus, multithreading is a specialized form of multitasking.
▪ Multithreading enables you to write very efficient programs that make maximum use of the
CPU, because idle time can be kept to a minimum.
▪ Multitasking threads require less overhead than multitasking processes.
▪ It is the duty of the thread scheduler to provide the thread time to run, i.e., moving the
thread the running state.
▪ A program implementing multithreading acquires a fixed slice of time to each individual
thread.
▪ Each and every thread runs for a short span of time and when that allocated time slice is
over, the thread voluntarily gives up the CPU to the other thread, so that the other
threads can also run for their slice of time.
▪ Whenever such a scenario occurs, all those threads that are willing to run, waiting for
their turn to run, lie in the runnable state.
▪ In the runnable state, there is a queue where the threads lie.
▪ Running:
▪ When the thread gets the CPU, it moves from the runnable to the running state.
▪ Generally, the most common change in the state of a thread is from runnable to running
and again back to runnable.
3. Blocked or Waiting:
▪ Whenever a thread is inactive for a span of time (not permanently) then, either the thread is in
the blocked state or is in the waiting state.
▪ For example, a thread (let's say its name is A) may want to print some data from the printer.
However, at the same time, the other thread (let's say its name is B) is using the printer to print
some data. Therefore, thread A has to wait for thread B to use the printer. Thus, thread A is in
the blocked state.
▪ A thread in the blocked state is unable to perform any execution and thus never consume any
cycle of the Central Processing Unit (CPU).
▪ Hence, we can say that thread A remains idle until the thread scheduler reactivates thread A,
which is in the waiting or blocked state.
▪ When the main thread invokes the join() method then, it is said that the main thread is in the
waiting state.
▪ The main thread then waits for the child threads to complete their tasks. When the child threads
complete their job, a notification is sent to the main thread, which again moves the thread from
waiting to the active state.
▪ If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread
scheduler to determine which thread to choose and which one to reject, and the chosen thread is
then given the opportunity to run.
4. Timed Waiting:
▪ Sometimes, waiting for leads to starvation.
▪ For example, a thread (its name is A) has entered the critical section of a code and is not
willing to leave that critical section. In such a scenario, another thread (its name is B)
has to wait forever, which leads to starvation.
▪ To avoid such scenario, a timed waiting state is given to thread B.
▪ Thus, thread lies in the waiting state for a specific span of time, and not forever.
▪ A real example of timed waiting is when we invoke the sleep() method on a specific
thread. The sleep() method puts the thread in the timed wait state. After the time runs
out, the thread wakes up and start its execution from when it has left earlier.
5. Terminated:
▪ A thread reaches the termination state because of the following reasons:
➢ When a thread has finished its job, then it exists or terminates normally.
➢ Abnormal termination: It occurs when some unusual events such as an
unhandled exception or segmentation fault.
▪ A terminated thread means the thread is no more in the system. In other words, the thread
is dead, and there is no way one can respawn (active after kill) the dead thread.
Program. 12. Write a Java program to implement the concept of threading by extending Thread
Class.
import java.lang.Thread;
class A extends Thread
{
public void run()
{
System.out.println("thread A is sterted:");
for(int i=1;i<=5;i++)
{
System.out.println("\t from thread A:i="+i);
}
System.out.println("exit from thread A:");
}
}
class B extends Thread
{
public void run()
{
System.out.println("thread B is sterted:");
for(int j=1;j<=5;j++)
{
System.out.println("\t from thread B:j="+j);
}
System.out.println("exit from thread B:");
}
}
class C extends Thread
{
public void run()
{
System.out.println("thread C is sterted:");
for(int k=1;k<=5;k++)
{
System.out.println("\t from thread C:k="+k);
}
System.out.println("exit from thread C:");
}
}
class ThreadDemo
{
public static void main(String arg[])
{
new A().start();
new B().start();
new C().start();
}
Sample Output 1:
Sample Output 2:
EXPERIMENT-13
Aim:
Program on Graphics class
Theory:
Program. 13.A. Write a Java program using Applet to display a message in the Applet to
demonstrate Graphics class.
import java.applet.Applet;
import java.awt.Graphics;
{
public void paint(Graphics g)
{
String msg="HELLO!, Welcome to my applet ";
g.drawString(msg,80,150);
}
}
<HTML>
<HEAD>
<TITLE>Welcome to JAVA Applet Demo</TITLE>
</HEAD>
<BODY>
<APPLET CODE="Appletdemo.class" width=300 height=300>
</APPLET>
</BODY>
</HTML>
Sample Output:
Program. 13.B. Write a Java program using Applet to draw a Smiley in the Applet to
demonstrate Graphics class.
import java.awt.*;
import java.applet.*;
Sample Output:
EXPERIMENT-14
Aim:
Program to create GUI application
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. 14. Write a Java program to create GUI application with event handling using AWT
controls.
import java.awt.event.*;
import java.awt.*;
//import java.awt.event.ActionEvent;
//import java.awt.event.ActionListener;
//import java.awt.Button;
//import java.awt.Frame;
//import java.awt.Label;
//import java.awt.TextField;
//import java.awt.event.WindowAdapter;
//import java.awt.event.WindowEvent;
t1 = new TextField();
t1.setBounds(200, 50, 150, 30);
f.add(t1);
t2 = new TextField();
t2.setBounds(200, 80, 150, 30);
f.add(t2);
b1 = new Button("Login");
b1.setBounds(90, 200, 100, 30);
f.add(b1);
b1.addActionListener(this);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
f.setLayout(null);
f.setSize(600, 500);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
int c = 0;
if (e.getSource().equals(b1))
{
if (t1.getText().equals("Admin") && (t2.getText().equals("123")))
{
lb3.setText(String.valueOf("Success login!"));
}
else
{
lb3.setText(String.valueOf("Invalid login!"));
}
}
}
public static void main(String args[])
{
AWTLogin t = new AWTLogin();
}
}
Sample Output:
EXPERIMENT-15
Aim:
Mini Project using concepts of Java.