OOPM Lab Manual
OOPM Lab Manual
EXPERIMENT NO: 1
Learning Objectives:
2.1 Intellectual Skills:
Understand the how use the class and object in java programming.
Understand the various keys used in java programming.
2.2Motor Skills:
Ability to learn how develops the Java program in details.
Apparatus:
3.1HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD
512MB DDR
REQUIREMENTS:
The path is required to be set for using tools such as javac, java etc.
If you are saving the java source file inside the jdk/bin directory, path is not
required to be set because all the tools will be available in the current directory.
But If you are having your java file outside the jdk/bin folder, it is necessary to set
path of JDK.
OOPM JAVA /CSL 304 / Sem- III Page 1
Computer Engineering /SSJCET, Asangaon
1. temporary
2. permanent
1) How to set Temporary Path of JDK in Windows
To set the temporary path of JDK, you need to follow following steps:
For setting the permanent path of JDK, you need to follow these steps:
Features of Java
There is given many features of java. They are also known as java buzzwords. The
Java Features given below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10.High Performance
11.Multithreaded
12.Distributed
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that
OOPM JAVA /CSL 304 / Sem- III Page 2
Computer Engineering /SSJCET, Asangaon
Loads code
Verifies code
Executes code
Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime
environment.It is the implementation of JVM.It physically exists.It contains set of
libraries + other files that JVM uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun
Micro Systems.
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.
class Simple{
System.out.println("Hello Java");
}
Java Program:
PROGRAM:-
//import Scanner as we require it.
import java.util.Scanner;
System.out.println("Enter Years");
y = input.nextInt();
Step
Details of the step
no.
1.
Compile the Java program using javac compiler.
Result:
Enter Amount:
1000
Enter Years
2
Enter Rate of interest
3
Simple interest = 60.0
Total = 1060.0
Conclusion:
Here we understand the basic java program, how we use class in java and how make
the object here.
Questions:
1. Write java program for find the Armstrong number from 2 numbers
2. Write java program to show first 10 prime numbers.
3. Understand the class and Object.
www.tutorialspoint.com
www.stackoverflow.com --
If error occurs in program then this site helps you to solve error in your program
EXPERIMENT NO: 2
THEORY :
Branching statements are used to change the flow of execution from one section of a
program to another. Branching statements are typically utilized within control
statements. Java includes three types of branching statements: continue, break, and
return. When a given condition is met, we can depart from a control statement
using branching statements.
In Java, the continue and break statements are two key branching statements that are
used in conjunction with the control statements. The break statement ends or breaks
the loop and moves control outside of it. The continue command skips the current
execution and returns control to the loop's beginning. The return statement returns a
value from a method and does so openly.
In a for, while, or do-while loop: It ends the loop's execution instantly, enabling the
program to proceed with the code after the loop.
In a switch statement, it quits the switch block, preventing further case blocks from
being executed.
Syntax
while (true) {
// Code here
if (condition) {
break; // Exit the loop
}
}
The continue statement is used to skip the current loop iteration and go to the next.
When this happens, it skips the remaining code in the current iteration and moves on
to the next.
Syntax
control-flow-statement;
continue;
The return statement is used to quit a method and, if desired, return a value to the
caller.
It defines the value that the method should return (if the method has a return type).
It also causes the function to quit instantly, bypassing any code that comes after the
method's return statement.
Syntax
return value;
public int add(int a, int b) {
return a + b; // Return the result and exit the method
}
Example1:
BranchingStatements.java
Output:
1
2
3
4
Loops in Java
Loops are a block of code that executes itself until the specified condition becomes
false. In this section, we will look in detail at the types of loops used in Java
programming.
While Loop is also an iteration statement that can iterate over various types of
values.
After accepting the condition While loop evaluates it to a "boolean value".
Execute a particular statement or a block of the statement until it generates
"false".
While loop is used when the user is not aware of the exact iteration number.
There are various types of while loops; those are "Empty While Loop", and
"Infinite While Loops".
Test Condition: It is used for testing the exit condition for a loop. It must
return a boolean value. While loop is an entry-controlled loop as the condition
is checked before the execution of the loop statements.
Statement execution: Once the condition is evaluated to be true, the
statements in the loop body are executed. Normally the statements contain an
update value for the variable being processed for the next iteration.
Loop termination: When the condition becomes false, the loop terminates
marking the end of the while loop.
//initialization
while (condition)
{
//Execute a set of statements
//increment
}
Do while loop works the same as while loop but it only generates the
expression only after the execution of the code block has been done. The
concept of Abstraction in Java can be applied to understand the Do-While
loop better
This statement first executes the statement under "do" after that it checks the
condition of "while".
This statement executes at least once even though the statement generates a
"false" value.
Do while loop is an "exit control loop".
There is only one type of “Do while loop” which is called "Infinite Do While
Loop".
Statement execution: The loop starts with the execution of the statement(s).
There is no checking of any condition for the first time.
Test Condition: After the statements execution step, the condition is checked
for true or false value. If it is evaluated to be true, the next iteration of the
loop starts.
Loop termination: When the condition becomes false, the loop terminates
marking the end of the do...while loop.
do
{
//statements to be iterated
}
while(conditions)
class Main {
public static void main(String[] args) {
int sum = 0;
System.out.println("Enter a number");
number = input.nextInt();
}
System.out.println("Sum = " + sum);
input.close();
}
}
Output
Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39
EXPERIMENT NO: 3
Learning Objectives:
2.1 Intellectual Skills:
Understand the different methods and functions in java program.
Understand the order by java program.
2.2Motor Skills:
Ability to learn how develops the Java program in details.
Apparatus:
HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD
512MB DDR
SOFTWARE REQUIREMENTS:
Theory:
Prior Concept:
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike, marker,
pen, table, car etc. It can be physical or logical (tengible and intengible). The
example of integible object is banking system.
data member
method
constructor
block
class and interface
Syntax to declare a class:
1. class <class_name>{
2. data member;
3. method;
4. }
static keyword
The static keyword is used in java mainly for memory management. We may apply
static keyword with variables, methods, blocks and nested class. The static keyword
belongs to the class than instance of the class.
Java Program:
/* Palindrome Program In JAVA
*/
import java.util.Scanner;
class Palindrome{
public static void main(String args[]){
System.out.print("Enter Number: ");
Scanner read = new Scanner(System.in);
int num = read.nextInt();
int n = num;
//reversing number
int rev=0,rmd;
while(num > 0)
{
rmd = num % 10;
rev = rev * 10 + rmd;
num = num / 10;
}
if(rev == n)
System.out.println(n+" is a Palindrome Number!");
else
System.out.println(n+" is not a Palindrome Number!");
}}
1. 2.
Compile the Java program using javac compiler.
Result:
Conclusion:
Here understand the how java scanner class used with the help of package, and how
set the data to the objects in java program.
Questions:
www.tutorialspoint.com
EXPERIMENT NO: 4
Learning Objectives:
2.1 Intellectual Skills:
Understand the different methods and functions in java program.
2.2Motor Skills:
Ability to learn how develops the Java program in details.
Apparatus:
HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD
512MB DDR
SOFTWARE REQUIREMENTS:
Theory:
Prior Concept:
Java Array
Java array is an object the contains elements of similar data type. It is a data
structure where we store similar elements. We can store only fixed set of elements
in a java array.
Array in java is index based, first element of the array is stored at 0 index.
Code Optimization: It makes the code optimized, we can retrieve or sort the
data easily.
Random access: We can get any data located at any index position.
Size Limit: We can store only fixed size of elements in the array. It doesn't
grow its size at runtime. To solve this problem, collection framework is used
in java.
1. arrayRefVar=new datatype[size];
import java.io.*;
class GFG {
marks[i][j] = i + j;
System.out.println();
Output
Java String
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.
StringExample.java
Output:
java
strings
example
Conclusion:
Here understand the concept about the working of array and string in java.
Questions:
Student Activity:
(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
Define and list down all the requirements as per the case study by using any
java program.
Related Links:
www.javatpoint.com
www.tutorialspoint.com
EXPERIMENT NO: 5
Learning Objectives:
2.1 Intellectual Skills:
Understand the different methods and functions in java program.
2.2Motor Skills:
Ability to learn how develops the Java program in details.
Apparatus:
HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD
512MB DDR
SOFTWARE REQUIREMENTS:
Theory:
Prior Concept:
If a class have multiple methods by same name but different parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods
increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs. So,
we perform method overloading to figure out the program quickly.
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding. In other words, If subclass provides the specific
implementation of the method that has been provided by one of its parent class, it is
known as Method Overriding.
Advantage of Java Method Overriding
1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10,10,10);
8. obj.sum(20,20);
9. }
10. }
OOPM JAVA /CSL 304 / Sem- III Page 28
Computer Engineering /SSJCET, Asangaon
Result:
Consider the following Java program, in which we have used different constructors
in the class.
Example
public class Student {
//instance variables of the class
int id;
String name;
Student(){
System.out.println("this a default constructor");
}
Output:
Student Id : 0
Student Name : null
Student Id : 10
Student Name : David
In the above example, the Student class constructor is overloaded with two different
constructors, I.e., default and parameterized.
Conclusion:
Here understand the concept method overloading and method overloading.
Questions:
1.Write java program method overloading.
2. Write java program method overriding.
Student Activity:
(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
Define and list down all the requirements as per the case study by using any
java program.
11.0 Related Links:
www.javatpoint.com
www.tutorialspoint.com
EXPERIMENT NO: 6
Learning Objectives:
Intellectual Skills:
Understand the different methods and functions in java program.
Motor Skills:
Ability to learn how develops the Java program in details.
Apparatus:
HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD
512MB DDR
SOFTWARE REQUIREMENTS:
Theory:
Prior Concept:
VECTOR:-
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections
framework.
Vector proves to be very useful if you don't know the size of the array in advance or
you just need one that can change sizes over the lifetime of a program.
The Vector class supports four constructors. The first form creates a default vector,
which has an initial size of 10:
Vector( )
The second form creates a vector whose initial capacity is specified by size:
OOPM JAVA /CSL 304 / Sem- III Page 33
Computer Engineering /SSJCET, Asangaon
Vector(int size)
The third form creates a vector whose initial capacity is specified by size and whose
increment is specified by incr. The increment specifies the number of elements to
allocate each time that a vector is resized upward:
Vector(int size, int incr)
The fourth form creates a vector that contains the elements of collection c:
Vector(Collection c)
Java Program:
import java.util.*;
class TestVector1{
System.out.println(e.nextElement());
}
}
Result:
Output: umesh,
Irfan, kumar
StringBuffer Class
Here are some important features and methods of the StringBuffer class:
StringBuffer objects are mutable, meaning that you can change the contents of
the buffer without creating a new object.
The initial capacity of a StringBuffer can be specified when it is created, or it
can be set later with the ensureCapacity() method.
The append() method is used to add characters, strings, or other objects to the
end of the buffer.
The insert() method is used to insert characters, strings, or other objects at a
specified position in the buffer.
The delete() method is used to remove characters from the buffer.
The reverse() method is used to reverse the order of the characters in the buffer.
Here is an example of using StringBuffer to concatenate strings:
Output
Hello world
Conclusion:
Here understand the concept vector with the practically did program in vector.
Questions:
1. Write java program to add data into vector dataset.
2. Write java program to remove data into vector dataset.
Student Activity:
(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
Define and list down all the requirements as per the case study by using any
java program.
Related Links:
www.javatpoint.com
www.tutorialspoint.com
EXPERIMENT NO: 7
Learning Objectives:
2.1 Intellectual Skills:
Understand the different methods and functions in java program.
2.2Motor Skills:
Ability to learn how develops the Java program in details.
Apparatus:
REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD
512MB DDR
REQUIREMENTS:
Theory:
Prior Concept:
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties
and behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of parent class, and you can add new methods and fields also.
Single Inheritance
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
8.0 Conclusion:
Here understand the concept about the inheritance, polymorphism, encapsulation,
and abstraction in java.
9.0 Questions:
OOPM JAVA /CSL 304 / Sem- III Page 41
Computer Engineering /SSJCET, Asangaon
www.tutorialspoint.com
EXPERIMENT NO: 8
Learning Objectives:
2.1 Intellectual Skills:
Understand the different methods and functions in java program.
2.2Motor Skills:
Ability to learn how develops the Java program in details.
Apparatus:
HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD
512MB DDR
SOFTWARE REQUIREMENTS:
Interface in Java
The java compiler adds public and abstract keywords before the interface method
and public, static and final keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods
are public and abstract.
As shown in the figure given below, a class extends another class, an interface
extends another interface but a class implements an interface.
Java Program:
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print()
{System.out.println("Hello");}
6.
7. public static void main(String args[]
){ A6 obj = new A6();
8. obj.print(); } }
Result:
Output: Hello
Conclusion:
Here understand the concept of Interface and how we use interface in java program.
Questions:
1. Write java program to using interface methods create class and derived
that methods.
Student Activity:
(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
Define and list down all the requirements as per the case study by using any
java program.
11.0 Related Links:
www.javatpoint.com
www.tutorialspoint.com
EXPERIMENT NO: 9
Aim : Program on Multithreading
Learning Objectives:
Apparatus:
HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD
512MB DDR
SOFTWARE REQUIREMENTS:
Theory:
Prior Concept:
Multithreading in Java
1) It doesn't block the user because threads are independent and you can perform
multiple operations at same time.
Threads are independent, if there occurs exception in one thread, it doesn't affect
other threads. It shares a common memory area.
As shown in the above figure, thread is executed inside the process. There
is context-switching between the threads. There can be multiple
processes inside the OS and one process can have multiple threads. Life
cycle of a Thread (Thread States)
A thread can be in one of the five states. According to sun, there is only 4 states in
thread life cycle in java new, runnable, non-runnable and terminated. There is no
running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are
as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2) 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.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
Java Program:
Multithreading Program
RunnableDemo R1 = new
RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new
RunnableDemo( "Thread-2");
R2.start();
} }
Output:Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
OOPM JAVA /CSL 304 / Sem- III Page 53
Computer Engineering /SSJCET, Asangaon
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Conclusion:
Here understand the concept of thread and multithreading in java programming .
Questions:
1. Write java program to create thread using Runnable interface and
second extends thread class.
Student Activity:
(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
Define and list down all the requirements as per the case study by using any
java program.
11.0 Related Links:
www.javatpoint.com
www.tutorialspoint.com
EXPERIMENT NO: 10
Learning Objectives:
2.1 Intellectual Skills:
Understand the different methods and functions in java program.
2.2Motor Skills:
Ability to learn how develops the Java program in details.
Apparatus:
REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD
512MB DDR
REQUIREMENTS:
4.0 Theory:
Prior Concept:
Java Package
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.Here, we will have the detailed learning of creating and using
user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. } }
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can
use any directory name like /home (in case of Linux), d:/abc (in case of windows)
etc. If you want to keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package
ARRAYLIST:-
The ArrayList class extends AbstractList and implements the List interface.
ArrayList supports dynamic arrays that can grow as needed.
Standard Java arrays are of a fixed length. After arrays are created, they cannot
grow or shrink, which means that you must know in advance how many elements an
array will hold.
Array lists are created with an initial size. When this size is exceeded, the collection
is automatically enlarged. When objects are removed, the array may be shrunk.
The ArrayList class supports three constructors. The first constructor builds an
empty array list.
ArrayList( )
The following constructor builds an array list that is initialized with the elements of
the collection c.
ArrayList(Collection c)
The following constructor builds an array list that has the specified initial capacity.
The capacity is the size of the underlying array that is used to store the elements.
LINKEDLIST:-
The LinkedList class supports two constructors. The first constructor builds an
empty linked list:
LinkedList( )
The following constructor builds a linked list that is initialized with the elements of
the collection c.
LinkedList(Collection c)
import java.util.*;
al);
}}
LinkedList program:
import java.util.*;
Result:
Conclusion:
Here understand the concept of packages, ArrayList, LinkedList creation.
Questions:
1. Write java program to create package and using that package create a
program to add data into Arraylist and LinkedList program.
Student Activity:
(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
Define and list down all the requirements as per the case study by using any
java program.
11.0 Related Links:
www.javatpoint.com
www.tutorialspoint.com
EXPERIMENT NO: 11
Learning Objectives:
2.1 Intellectual Skills:
OOPM JAVA /CSL 304 / Sem- III Page 61
Computer Engineering /SSJCET, Asangaon
Apparatus:
HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD
512MB DDR
SOFTWARE REQUIREMENTS:
Theory:
Prior Concept:
The exception handling in java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
In this page, we will learn about java exception, its type and the difference between
checked and unchecked exceptions.
What is exception
Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
What is exception handling
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFound, IO, SQL, Remote etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application that is
why we use exception handling. Let's take a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
OOPM JAVA /CSL 304 / Sem- III Page 62
Computer Engineering /SSJCET, Asangaon
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception. The sun microsystem says 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 that extend 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 that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-time rather they are checked
at runtime.
3) Error
There are given some scenarios where unchecked exceptions can occur. They are as
follows:
1) Scenario where ArithmeticException occurs
1. int a=50/0;//ArithmeticException
2) Scenario where NullPointerException occurs
If we have null value in any variable, performing any operation by the variable
occurs an NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
3) Scenario where NumberFormatException occurs
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
1. try{
2. ...
3. }catch(Exception_class_Name reference){}
Syntax of try with finally block
1. try{
2. ...
3. }finally{}
catch block
Catch block is used to handle the Exception. It must be used after the try block.
Problem without exception handling
7. }
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
Solution by exception handling
e..."); } }
Result:
Conclusion:
Here understand the concept of exception and how exception handle in java
program using try, catch, throw, throws and finally keyword.
Questions:
1. Write java program to handle the exception.
2. Write java program where used multiple catch block.
Student Activity:
(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
Define and list down all the requirements as per the case study by using any
java program.
11.0 Related Links:
www.javatpoint.com
www.tutorialspoint.com
EXPERIMENT NO: 12
Java defines several types of exceptions that relate to its various class
libraries. Java also allows users to define their own exceptions.
User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, the user can also create exceptions which are called ‘user-
defined Exceptions’.
The following steps are followed for the creation of a user-defined Exception.
The user should create an exception class as a subclass of the Exception class.
Since all the exceptions are subclasses of the Exception class, the user should
also make his class a subclass of it. This is done as:
MyException(){}
MyException(String str)
{
super(str);
The following program illustrates how to create your own exception class
MyException.
Details of account numbers, customer names, and balance amounts are taken in
the form of three arrays.
In main() method, the details are displayed using a for-loop. At this time, a
check is done if in any account the balance amount is less than the minimum
balance amount to be apt in the account.
If it is so, then MyException is raised and a message is displayed “Balance
amount is
Example
// default constructor
MyException() { }
// parameterized constructor
// write main()
try {
"\t" + "BALANCE");
"\t" + bal[i]);
MyException me =
throw me;
} //end of try
catch (MyException e) {
e.printStackTrace();
} }
Runtime Error
MyException: Balance is less than 1000
at MyException.main(fileProperty.java:36)
Output:
EXPERIMENT NO: 13
Learning Objectives:
2.1 Intellectual Skills:
Understand the different methods and functions in java program.
2.2Motor Skills:
Ability to learn how develops the Java program in details.
Apparatus:
REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD
512MB DDR
SOFTWARE REQUIREMENTS:
Theory:
Prior Concept:
Applet :
An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java
application, including the following:
A main() method is not invoked on an applet, and an applet class will not
define main().
When a user views an HTML page that contains an applet, the code for the
applet is downloaded to the user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the
Web browser or a separate runtime environment.
The JVM on the user's machine creates an instance of the applet class and
invokes various methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The
security of an applet is often referred to as sandbox security, comparing the
applet to a child playing in a sandbox with various rules that must be
followed.
Other classes that the applet needs can be downloaded in a single Java
Archive (JAR) file.
Four methods in the Applet class give you the framework on which you build any
serious applet:
init: This method is intended for whatever initialization is needed for your
applet. It is called after the param tags inside the applet tag have been
processed.
start: This method is automatically called after the browser calls the init
method. It is also called whenever the user returns to the page containing the
applet after having gone off to other pages.
stop: This method is automatically called when the user moves off the page
on which the applet sits. It can, therefore, be called repeatedly in the same
applet.
destroy: This method is only called when the browser shuts down normally.
Because applets are meant to live on an HTML page, you should not
normally leave resources behind after a user leaves the page that contains the
applet.
paint: Invoked immediately after the start() method, and also any time the
applet needs to repaint itself in the browser. The paint() method is actually
inherited from the java.awt.
Every applet is an extension of the java.applet.Applet class. The base Applet class
provides methods that a derived Applet class may call to obtain information and
services from the browser context.
Get the network location of the HTML file that contains the applet
Fetch an image
Additionally, the Applet class provides an interface by which the viewer or browser
obtains information about the applet and controls the applet's execution. The viewer
may:
request information about the author, version and copyright of the applet
The "Hello, World" applet is complete as it stands. The only method overridden is
the paint method.
5.0 Java Program:
A "Hello, World" Applet:
Invoking an Applet:
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class"
width="320" height="120">
If your browser was Java-enabled, a
"Hello, World"
message would appear here.
</applet><hr></html>
<applet
codebase="http://amrood.com/applets"
code="HelloWorldApplet.class"
width="320" height="120">
Result:
Conclusion:
Here understand the concept of what is applet and applet life cycle, and how
implement applet program using html file.
Questions:
Write program to show “Hello World” using applet program.
Write program where circle, triangle, rectangle, arc show using Applet
program.
(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
Define and list down all the requirements as per the case study by using any
java program.
11.0 Related Links:
www.javatpoint.com
www.tutorialspoint.com
www.stackoverflow.com -- If error occurs in program then this site helps you to
solve error in your program
EXPERIMENT NO: 14
Graphics is an abstract class provided by Java AWT which is used to draw or paint
on the components. It consists of various fields which hold information like
components to be painted, font, color, XOR mode, etc., and methods that allow
drawing various shapes on the GUI components. Graphics is an abstract class and
thus cannot be initialized directly. Objects of its child classes can be obtained in
the following two ways.
Inside paint() or update() method
It is passed as an argument to paint and update methods and therefore can be
accessed inside these methods. paint() and update() methods are present in the
Component class and thus can be overridden for the component to be painted.
void paint(Graphics g)
void update(Graphics g)
1. public abstract void drawString(String str, int x, int y): is used to draw the
specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle
with the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to
fill rectangle with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used
to draw oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to
fill oval with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to
draw line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used to fill a circular or elliptical arc.
10.public abstract void setColor(Color c): is used to set the graphics current
color to the specified color.
11.public abstract void setFont(Font font): is used to set the graphics current
font to the specified font.
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
OOPM JAVA /CSL 304 / Sem- III Page 80
Computer Engineering /SSJCET, Asangaon
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
1. <html>
2. <body>
3. <applet code="GraphicsDemo.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
EXPERIMENT : 15