Java Lab Manual
Java Lab Manual
Java Lab Manual
Accredited by
NAAC(UGC) with ‘A’ Grade
JAVA Programming
Lab Manual for B.Tech
1
National Institute of Science and Technology
The students will write the today’s experiment in the Observation book as per the following
format:
1) Name of the experiment/Aim
2) Source Program
3) Test Data
a. Valid data sets
b. Limiting value sets
c. Invalid data sets
4) Results for different data sets
5) Viva-Voc Questions and Answers
6) Errors observed (if any) during compilation/execution
7) Signature of the Faculty
Each laboratory will be evaluated from 100 marks. The evaluation distribution is as
follows.
Attendance : 20
Record : 20
Performance(Programs & Viva) : 60
Total : 100
There will a project assigned to each student after the laboratory 5 and the project will be
evaluated (Programming Code, Presentation etc.) at the end of the laboratory work. The
project will carry 20 marks in the final evaluation.
2
National Institute of Science and Technology
Autonomous Syllabus
19CS4PC02L Object-Oriented Programming Using Java Lab (0-0-2) 1 Credit
Course Objective:
1. Learn and implement Programs with the syntax, semantics and idioms of the Java
programming language.
2. Implement practical exercises
3. Develop a standalone application.
List of Experiments:
1. Data types & variables, decision control structures: if, nested if etc Loop control
structures: do, while, for etc.
2. Classes and objects.
3. Data Abstraction & Data hiding, Inheritance.
4. Interfaces and inner classes, wrapper classes.
5. Exception handlings
6. Threads
7. IO Files
8. Collections
9. Database Connectivity.
10. Applets AWT and Swing.
Course Outcome:
1. Understand and implement various Object Oriented Concepts like inheritance,
abstraction and polymorphism.
2. Work with Collection Classes and Files, Multiple Threads, & handle Exceptions.
3. Develop applications to interact with a Database.
4. Design and implement Graphical User Interface(GUI) Applications in Java using AWT and
Swing.
Text Books and Reading Materials :
1. Java: One Step Ahead by Anita Seth (Author), B.L. Juneja (Author) Oxford University
Press.
2. Head First Java 2nd edition Kathy Sierra & Bert Bates
3. JAVA Complete Reference (9th Edition) Herbert Schildt.
4. https://www.udemy.com/java-the-complete-java-developer-course/
5. Java Programming Masterclass for Software Developers Created by Tim Buchalka, Tim
Buchalka's Learn Programming Academy, Goran Lochert
Java Environment
3
National Institute of Science and Technology
Procedure to establish the environment to develop java application by setting two environment
variables i.e. PATH and CLASSPATH.
Step 1: To use all executable commands (javac, java and appletviewer) from any directory on the
command prompt. Setting of PATH environment variable is required. To do this edit C:\autoexec.bat
file. Write following code after last path setting of path variable if it already exists.
C:\jdkx\bin;
Experiment – 1
4
National Institute of Science and Technology
Java Fundamentals
Java is a programming language and a platform. Java is a high level, robust, object-oriented and
secure programming language.
Platform: Any hardware or software environment in which a program runs, is known as a
platform
(1) Hello World Program
Step 1: Use an editor to enter the following code for the Hello World program:
HelloWorldApp Application
Scanner class in Java is found in the java.util package. Java provides various ways to read
input from the keyboard, the java.util.Scanner class is one of them.
(2) Read an input from the console
import java.util.*;
public class SumOfTwoNumbers
{ public static void main(String args[ ])
{ int n1, n2, sum; Scanner key;
System.out.print("Enter First Number :: ");
key = new Scanner(System.in);
n1=key.nextInt();
System.out.print("Enter Second Number :: ");
key = new Scanner(System.in);
n2=key.nextInt();
sum=n1+n2;
System.out.println("Sum of Two Numbers is " + sum);
}
}
5
National Institute of Science and Technology
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}
Java command line arguments:
The java command-line argument is an argument i.e. passed at the time of running the java
program.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample welcomestojava
class A{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac A.java
run by > java A manoj padhi 1 3 abc
6
National Institute of Science and Technology
1. WAP to print your full name where the input will be taken from the command line.
public class CommandLine
{ public static void main(String args[ ])
{ for (int i=0; i<args.length; i++)
System.out.println(“args[“ + i +”]: ” + args[i]);
}
}
COMPILE:
javac CommandLine.java
RUN:
java CommandLine NIST Berhampur Odisha
OUTPUT:
args[0]: NIST
args[1]: Berhampur
args[2]: Odisha
2. Write a java program to enter two numeric values (integer) then compute and display the sum
and product of these two numeric values.
3. Write a java program to find the largest number among three numbers. Where numbers have
to taken from the user.
4. Generate following patterns based upon the number of rows entered by the user:
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * *
6. Write a program to print the Fibonacci series up to a given number.
7. Write a program that finds out sum of digits of a number.
8. Write a program that reverses a number.
9. Write a program to find the gcd of two given numbers
10. Write a program to read a number from the user, and check whether the number is prime or
not.
11. WAP to print the default values of all primitive data types, which are declared inside a
method and a class. (Ex: byte, short, int, long, float, double, boolean and char)
12. Write a program to print following Pascal Triangle, where the number of rows is entered by
the user.
7
National Institute of Science and Technology
8
National Institute of Science and Technology
Experiment – 2
Class, Object & Constructors
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity
only.
(1) Fundamentals
public class JavaProgram
{ void main( )
{ System.out.printf("%s\n%s", "Dear Students", "Welcome to the WORLD of JAVA\
n");
}
static void main(String args)
{ System.out.println(args + " guides you how to prepare for ");
System.out.println("Oracle Certified Professional Java Programmer Exam.");
}
public static void main(String[ ] args)
{ int x=25;
JavaProgram java= new JavaProgram(); //creating an object through default
constructor
java.main(); //Calling a non-static method through object
main("NIST");
System.out.println("Enroll your name for free of COST");
System.out.println("Size of int " +Integer.SIZE);
System.out.println("Integer(Max Value) : "+Integer.MAX_VALUE);
System.out.println("Integer(Min Value) : "+Integer.MIN_VALUE);
System.out.println("Binary value of " + x + " = " + Integer.toBinaryString(x));
System.out.println("Hexadecimal value of " + x + " = " + Integer.toHexString(x));
System.out.println("Octal value of " + x + " = " + Integer.toOctalString(x));
}
}
(2) Class Concepts
class Student
{ private String name, city;
private int age;
public void getData(String x, String y, int t)
{ name=x; city=y; age=t;
}
public void printData()
{ System.out.println(“Student name =“+name);
System.out.println(“Student city =“+city);
System.out.println(“Student age =“+age);
}
}
class CS3
{ public static void main(String args[])
{ Student s1=new Student();
9
National Institute of Science and Technology
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Constructors in Java:
Constructor is special type method having same name as class. In Java, a constructor is a block of
codes similar to the method. It is called when an instance of the class is created. At the time of
calling constructor, memory for the object is allocated in the memory. It is a special type of method
which is used to initialize the object.Every time an object is created using the new() keyword, at least
one constructor is called. It calls a default constructor if there is no constructor available in the class.
In such case, Java compiler provides a default constructor by default.
Example1:Default constructor
10
National Institute of Science and Technology
1.
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
2.
class Student3{
int id;
String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}
1.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
11
National Institute of Science and Technology
s1.display();
s2.display();
}
}
1. WAP that takes 3 command line arguments (operand1 operator and operand2) and displays the
result obtained after performing the operations on the two operands. Operators that can be used
here are +, -, *, / operands are double values.
2. WAP to enter the student’s name, rollno and marks of the any number of subjects through
command line arguments. Print the Mark Sheet of the student as per the BPUT rules.
3. Write a statistical computation program that uses command line parameters to input the data. The
program will find out the maximum, minimum and mean value. For example, if we supply the
values 12, 3, 6, 19 and 5, then the program output will be as follows:
Maximum : 19
Minimum :3
Mean :9
4. Program reads two numbers and outputs their sum and product. Both numbers are given in same
line.
5. WAP which behaves in the following manner: Input 12+10 output 22. Input 12-10 output 2.
6. WAP to print the maximum and minimum values of Character, Integer type and Floating point
type primitive data type.
7. Find out the binary, octal and hexadecimal value of a decimal number using wrapper class. The
number will provide by the user through command line argument.
8. Write a java program to read two integers using command line arguments and find their
maximum.
9. Write a java program to read Student roll number and first name from the user and display them.
10. WAP to create a class Rectangle, with default constructor, one argument construct, and two
argument constructors, and define the methods area and perimeter of the rectangle. Create three
different objects with the help of three different constructors, and print the area and perimeter of
those objects.
11. Define a Park class with attributes length, breadth and area. Define a suitable constructor and a
method to display the object.
12. WAP to create a Triangle class with constructors (no-argument and parameterized) having
instance variables to record its three sides. Write validate() method to check for valid input. Use
findArea() and findPerimerter() of the Triangle class object.
13. Define a Student class (roll number, name, percentage). Define a default and parameterized
constructor. Override the toString method. Keep a count objects created. Create objects using
parameterized constructor and display the object count after each object is created. (Use static
member and method). Also display the contents of each object.
14. Define a class called Room with the follwing attributes 1.length, 2.breadth, 3.height, 4.florr_area,
5.Wall_area, 6.No.of_fans, 7.No.of_windows, 8.no.of_doors. Define a suitable constructor and a
method to display details of a room. Assume that 20% of the total wall area is occupied by doors
and windows.
15. WAP to create a complex class with a no-argument constructor and a parameterized constructor.
Write the proper getter and setter methods and override the toString( ) and equal( ) methods of
Object class.
16. WAP to print the date in dd/mm/yy format.
17. class called television has the following attributes:
a. Make
b. Size of the screen
12
National Institute of Science and Technology
13
National Institute of Science and Technology
Experiment – 3
Overloading, Overriding and Inheritance
(1) Function Overloading: If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
Method overloading increases the readability of the program.
import java.lang.*;
import java.util.*;
class Shape
{ void area()
{ int r=5; System.out.println("Area of circle with no argument: " +(3.14*r*r));
}
void area(int r) { System.out.println("Area of circle: " +(3.14*r*r)); }
Example:
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
(2) Function Overriding:-If subclass (child class) has the same method as declared in the parent class,
it is known as method overriding in Java.
class A
{ void show( ) { System.out.println("welcome to class A"); }
}
14
National Institute of Science and Technology
class B extends A
{ void show( )
{ super.show();
System.out.println("welcome to class B");
super.show();
}
}
15
National Institute of Science and Technology
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
import java.io.DataInputStream;
class Student
{ private int rollno; private String name;
DataInputStream dis=new DataInputStream(System.in);
public void getrollno()
{ try
{ System.out.println("Enter rollno ");
rollno=Integer.parseInt(dis.readLine());
System.out.println("Enter name ");
name=dis.readLine();
}
catch(Exception e){ }
}
void putrollno( ) { System.out.println("Roll No = "+rollno + "Name = "+name); }
}
void putmarks()
{ System.out.println("m1="+m1);
System.out.println("m2="+m2);
System.out.println("m3="+m3);
}
}
16
National Institute of Science and Technology
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
}}
17
National Institute of Science and Technology
the class properties. Each class should have some number of constructors and one of them must be
the clone.
3. Define a class Employee having private members – id, name, department, salary. Define default and
parameterized constructors. Create a subclass called “Manager” with private member bonus. Define
methods to accept and display values for both classes. Create n objects of the Manager class and
display the details of the manager having the maximum total salary (salary + bonus).
4. A bank maintains two kinds of accounts - Savings Account and Current Account. The savings
account provides compound interest, deposit and withdrawal facilities. The current account only
provides deposit and withdrawal facilities. Current account holders should also maintain a minimum
balance of rupees 5000. If balance falls below this level, a service charge of 5% is imposed. Create a
class Account that stores customer name, account number, and type of account. From this class
derive the classes Curr-acct and Sav-acct. Include the necessary methods in order to achieve the
following tasks. Accept deposit from a customer and update the balance. Display the balance.
Compute interest and add to the balance. Permit withdrawal and update the balance (Check for the
minimum balance, impose penalty if necessary).
5. Create a class Animal with a method show(). Inherit the Animal class to Man, Dog, Elephant,
Rabbit. Inherit classes must have string member name and at least two constructor. Implements the
method over riding show().
6. WAP to create a Person class having name, age and gender as instance variables. Write 3
constructors for constructor overloading like
a) First with no-argument
b) Second with argument as parameter for passing name, age and gender
c) Third with object as parameter to create a new copy of Person object.
d) Display the properties of Person class object with suitable methods.
7. WAP to student class extending from Person class of the above program and having regno, rollno,
college_name, and branch as its own instance variables. Use the constructors for this class. Use the
super and this keywords in your program. Display the properties of Student class object with suitable
methods.
8. Write a program that prints all real solutions to the quadratic equation ax2+bx+c=0. Read in a, b, c
and use the quadratic formula. If the discriminant b2-4ac is negative, display a message stating that
there are no real solutions.
Implement a class QuadraticEquation whose constructor receives the coefficients a, b, c of
quadratic equation. Supply methods getSolution1 and getSolution2 that get the solutions, using the
quadratic formula. Supply a method boolean hasSolutions( )that returns false if the discriminate is
negative.
18
National Institute of Science and Technology
Experiment – 4
Abstract classes, Interfaces and Packages
(1) The abstract Classes: A class which is declared as abstract is known as an abstract class. It
can have abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.
Example 1:
abstract class Circle
{ double radius;
abstract double area( );
public void perimeter( ) { // concrete method
System.out.println("Perimeter of the Circle is :: " + (2* Math.PI*radius));
}
}
class Sphere extends Circle
{ public double area( ) { return 4*Math.PI*radius*radius; }
Sphere(double d) { super.radius=d; }
public static void main(String ar[])
{ Sphere s=new Sphere(5); System.out.println("Surface Area :: " + s.area());
}
}
Example 2:
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Example 3:
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
19
National Institute of Science and Technology
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape(
) method
s.draw();
}
}
Example 4:
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Interface:
An interface in Java is a blueprint of a class. It has static constants and abstract methods. 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.
As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.
20
National Institute of Science and Technology
class InterfaceExtendsDemo
{ public static void main(String a[])
{ Rectangle rect=new Rectangle();
double result=rect.compute(10.2,12.3); rect.displayResult(result);
}
}
Multiple inheritance in java by interface:
21
National Institute of Science and Technology
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
Interface inheritance:
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
22
National Institute of Science and Technology
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}
Let's see a simple example where we are using interface and abstract class both.
//Creating interface that has 4 methods
interface A{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}
//Creating abstract class that provides the implementation of one method of A interface
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
//Creating subclass of abstract class, now we need to provide the implementation of rest of th
e methods
class M extends B{
public void a(){System.out.println("I am a");}
23
National Institute of Science and Technology
Package: A java package is a group of similar types of classes, interfaces and sub-packages.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package:
javac -d . Simple.java
how to run java package program:
java mypack.Simple
24
National Institute of Science and Technology
C:\jdk1.6.0_26\bin>java StudentTest
*******************************************************
(5) Compute the factorial of 100
import java.math.*;
public class BigFact
{ public static void main(String[] args)
{ BigInteger total = BigInteger.valueOf(1);
for (int i = 2; i<= 1000; i++)
total = total.multiply(BigInteger.valueOf(i));
System.out.println(total.toString());
}
}
(6) Interfaces and Packages
package animals;
interface Animal
{ public void eat(); public void travel();
} //Compile: javac – d • Animal.java
package animals;
class MammalInt implements Animal
{ public void eat( ) { System.out.println("Mammal eats"); }
public void travel( ) { System.out.println("Mammal travels"); }
public int noOfLegs( ) { return 0; }
public static void main(String args[])
{ MammalInt m = new MammalInt();
m.eat(); m.travel();
}
} //Compile: javac – d • MammalInt.java RUN: java animalsMammalInt
1) Create an abstract class Shape with methods calc_area and calc_volume. Derive three classes
Sphere(radius) , Cone(radius, height) and Cylinder(radius, height), Box(length, breadth, height)
from it. Calculate area and volume of all. (Use Method overriding).
2) Define an abstract class “Staff” with members name and address. Define two subclasses of this
class – “FullTimeStaff” (department, salary) and “PartTimeStaff” (numberof- hours, rate-per-
hour). Define appropriate constructors. Create n objects which could be of either FullTimeStaff
or PartTimeStaff class by asking the user’s choice. Display details of all “FullTimeStaff” objects
and all “PartTimeStaff” objects.
3) Declare an abstract class Vehicle with an Abstract method named numVehicle(). Provide
subclasses Car and Truck which overrides this methods. Create instances of this subclasses and
test the use of its methods.
4) Create a class Sum under a package sumpack, Sub under a package Subpack which is inside
sumpack. Create another class Mul which is inside mulpack. These classes perform the
respective arithmetic operations on integer nos. create a class Test to perform addition,
subtraction and multiplication by creating the object of respective classes.
5) Create a package named Maths. Define class MathsOperations with static methods to find the
maximum and minimum of three numbers. Create another package Stats. Define class
StatsOperations with methods to find the average and median of three numbers. Use these
methods in main to perform operations on three integers accepted using command line
arguments.
6) Write a Java program to create a Package “SY” which has a class SYMarks (members –
ComputerTotal, MathsTotal, and ElectronicsTotal). Create another package TY which has a class
25
National Institute of Science and Technology
TYMarks (members – Theory, Practicals). Create n objects of Student class (having rollNumber,
name, SYMarks and TYMarks). Add the marks of SY and TY computer subjects and calculate
the Grade (‘A’ for >= 70, ‘B’ for >= 60 ‘C’ for >= 50, Pass Class for > =40 else ‘FAIL’) and
display the result of the student in proper format.
7) Define an interface “IntOperations” with methods to check whether an integer is positive,
negative, even, odd, prime and operations like factorial and sum of digits. Define a class
MyNumber having one private int data member. Write a default constructor to initialize it to 0
and another constructor to initialize it to a value (Use this). Implement the above interface.
Create an object in main. Use command line arguments to pass a value to the object and perform
the above operations using a menu.
8) Define an interface “StackOperations” which declares methods for a static stack. Define a class
“MyStack” which contains an array and top as data members and implements the above
interface. Initialize the stack using a constructor. Write a menu driven program to perform
operations on a stack object.
9) Define an interface “QueueOperations” which declares methods for a static queue. Define a class
“MyQueue” which contains an array and front and rear as data members and implements the
above interface. Initialize the queue using a constructor. Write a menu driven program to perform
operations on a queue object.
10) Create a two interfaces of Subsum, Muldiv. Subsum have method of sub() and sum(). Muldiv
extends Subsum with having methods mul() and div(). Also create a class Arithmetic
implementing the Muldiv interfaces having its own method mod().
11) create two interfaces Animal with method running() and bird with method flying(). Animal has
four legs and bird has two legs. Implement the two interfaces to create a class FlyingTiger
having 6 legs and so it use.
12) Create an Animal class and a Mammal class extends from Animal class. Use the abstract
keyword for Animal class which must contain a concrete method and an abstract method.
13) Write a program to do the following job. For a given in degrees, convert it to radian. Find sin
and cos of that angle. Verify sin2 + cos2 = 1 by pow() method.
26
National Institute of Science and Technology
Experiment – 5
Arrays
Java array is an object which contains elements of a similar data type. Additionally, The elements
of an array are stored in a contiguous memory location. It is a data structure where we store similar
elements. We can store only a fixed set of elements in a Java array.
Types of array:
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
2. //Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other
words, it is an array of arrays with different number of columns.
27
National Institute of Science and Technology
class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
}}
28
National Institute of Science and Technology
29
National Institute of Science and Technology
30
National Institute of Science and Technology
Experiment – 6
Exception Handling
Exceptin handling: Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
31
National Institute of Science and Technology
Keyword Description
The "try" keyword is used to specify a block where we should place an exception code. It
try means we can't use try block alone. The try block must be followed by either catch or
finally.
The "catch" block is used to handle the exception. It must be preceded by try block which
catch
means we can't use catch block alone. It can be followed by finally block later.
The "finally" block is used to execute the necessary code of the program. It is executed
finally
whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
The "throws" keyword is used to declare exceptions. It specifies that there may occur an
throws exception in the method. It doesn't throw an exception. It is always used with method
signature.
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...");
}
}
TryCatchExample2.java
32
National Institute of Science and Technology
MultipleCatchBlock1.java
NestedTryBlock.java
33
National Institute of Science and Technology
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
Java finally block is a block used to execute important code such as closing the connection, etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it contains
all the necessary statements that need to be printed regardless of the exception occurs or not.
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
34
National Institute of Science and Technology
package btech.cs3.exc;
import java.util.*;
public class MyException
{ public static void main(String[] args)
{ try {
int c[]={1,2}; c[3]=10;
}
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println("Array out of bound");
}
try
{ int a=3, b; System.out.print("Enter the no:: ");
Scanner s=new Scanner(System.in);
b=s.nextInt(); int d=a/b;
}
catch(ArithmeticException e)
{ System.out.println("divide by zero");
}
finally
{ System.out.println("welcome to Oracle Java Classes");
}
}
}
35
National Institute of Science and Technology
class UserException
{ public static void main(String a[])
{ int age; DataInputStream ds=new DataInputStream(System.in);
try
{ System.out.println("Enter the age (above 15 abd 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); }
}
}
COMPILE:: C:\nist> javac -Xlint UserException.java
RUN:: C:\nist> java UserException
1. Write a java program to implement exception using try catch block
2. Write a java program to implement exception using the keyword throw.
3. Write a java program to implement exception using the keyword throws and finally
4. Write a program with a class that generates an exception when a variable is divided by Zero.
5. Write a program to find the exception marks out of bounds. In this program create a class
called Student. If the mark is greater than 100 it must create an exception called
MarkOutOfBounds Exception and throw it.
6. Write a program to enter the student’s name, Rollno. Marks, in any no. of subjects as
command line argument and find the percentage and grade of the student and thrown a
NumberFormatException if required.
7. Write a program to throw the NegativeArraySize exception, when the size of an array is
Negative.
8. WAP having multiple catch and finally blocks where the catch blocks should handle the
exceptions like, ArrayIndexOutOfBoundsException, NumberFormatException and
ArithmeticException or any other exception.
9. Write a program to take a negative floating point number -7.5. Find out the values of it by
using ceil(), floor() , rint() and round() method.
10. Create a class Student with attributes roll no, name, age and course. Initialize values through
parameterized constructor. If age of student is not in between 15 and 21 then generate user-
defined exception “AgeNotWithinRangeException”. If name contains numbers or special
symbols raise exception “NameNotValidException”. Define the two exception classes
11. Define Exceptions VowelException ,BlankException,ExitException.Write another class Test
which reads a character from command line. If it is a vowel, throw VowelException,if it is
blank throw BlankException and for a character 'X' throw an ExitException and terminate
program. For any other character, display “Valid character”
12. Define class MyDate with member’s day, month, and year. Define default and parameterized
constructors. Accept values from the command line and create a date object. Throw user
defined exceptions – “InvalidDayException” or “InvalidMonthException” if the day and
month are invalid. If the date is valid, display message “Valid date”
13. Write a program which accepts two integers and an arithmetic operator from the command
line and performs the operation. Fire the following user defined exceptions:
36
National Institute of Science and Technology
37
National Institute of Science and Technology
Experiment – 7
Thread
(1) Multithreading
class xyz implements Runnable class nist
{ public void run() { public static void main(String
{ int i; ar[])
for (i=1;i<5;i++) { xyz k;Thread a,b;
{ System.out.print(i); k=new xyz();
try{ Thread.sleep(1000); a=new Thread(k);
}catch(Exception e){} b=new Thread(k);
} a.start(); b.start();
} System.out.print("X");
} }
}
OUTPUT:
The above program outputs X11223344 (or 1X1223344 or 11X223344)
When a.start( ) is replaced by a.run( ) then the output is 1234X1234.
When b.start( ) is replaced by b.run( ) then the output is 11223344X.
OUTPUT:
The above program outputs 53647589 or 53465789 or 53645789 or 53467589 or
35645789
class xyz implements Runnable class pqr implements Runnable class nist
{ public void run() { public void run() { public static void main(String ar[])
{ int i; { xyz t;Thread c; { xyz k;pqr g;Thread a,b;
for (i=1;i<6;i++) System.out.print("X"); k=new xyz();
{ System.out.print(i); try{Thread.sleep(3000);} a=new Thread(k);
try{Thread.sleep(1000);} catch(Exception e){} g=new pqr();
catch(Exception e){} System.out.print("Y"); b=new Thread(g);
} t=new xyz(); a.start();b.start();
} c=new Thread(t); }
} c.start(); }
}
38
National Institute of Science and Technology
OUTPUT:
The above program outputs 1X23Y1425345
(2) Synchronization
class MyPrinter
{ public MyPrinter() { }
public synchronized void printName(String name)
{ for (int i=1; i<81; i++)
{ try
{ Thread.sleep((long)(Math.random() * 100));
}
catch (InterruptedException ie) { }
System.out.print(name);
}
}
}
class PrintThread extends Thread
{ String name; MyPrinter printer;
public PrintThread(String name, MyPrinter printer)
{ this.name = name; this.printer = printer;
}
public void run() { printer.printName(name); }
}
public class ThreadsTest
{ public static void main(String args[])
{ MyPrinter myPrinter = new MyPrinter();
PrintThread a = new PrintThread("*", myPrinter);
PrintThread b = new PrintThread("-", myPrinter);
PrintThread c = new PrintThread("=", myPrinter);
a.start(); b.start(); c.start();
}
}
39
National Institute of Science and Technology
10. Write a program to illustrate thread sleep. Create and run a thread. Then make it sleep.
11. Write a program to explain thread suspension and resumption.
12. Write a program to have Several objects of single thread as multi threading and demo for join.
Create three threads and join at appropriate place.
40
National Institute of Science and Technology
Experiment – 8
String & String Buffer
(1) String class and it’s methods
class stringdemo
{ public static void main(String arg[])
{ String s1=new String("Robert Heller"); String s2=" ROBER HELLER";
System.out.println("The s1 is : " +s1); System.out.println("The s2 is : " +s2);
System.out.println("Length of the string s1 is : " +s1.length());
System.out.println("The first accurence of A is at the position : " +s2.indexOf('A'));
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 greater 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(8,15); System.out.println("Extracted substring is :"+s3);
System.out.println("After Replacing a with o in s1 : " + s1.replace('a','o'));
String s4=" I like Jamshedpur "; System.out.println("The string s4 is :"+s4);
System.out.println("After trim() :"+s4.trim());
}
}
(2) StringBuffer class and it’s methods
class stringbufferdemo
{ public static void main(String arg[])
{ StringBuffer sb=new StringBuffer("NIIT 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(2,'S');System.out.println("After setting char S at position 2 : "
+sb);
System.out.println("After appending : " +sb.append("in Berhampur "));
System.out.println("After inserting : " +sb.insert(13,"Celebrations "));
System.out.println("After inserting : " +sb.insert(5,"Engineering "));
System.out.println("After deleting : " +sb.delete(5, 41));
}
}
1. Input a string and a character from user. Print the no of characters (input character) of an input string.
2. WAP in java which will accept a string and will return a string made of repetitions of that string.
3. Given a string where the string “OOP” appears at least two times, find the first and last “OOP” in the
whole string. Return the text from between the two “OOP”.
4. Suppose you have a string like this:"Once there was a woman name:angelina: and a man name: tony:
and their friend name:jane: and ...". Inside of a long text there are little "name:" sections. Write code
to find and print all the names.
41
National Institute of Science and Technology
5. Write a program in Java which will accept a string and will check whether the string is palindrome or
not?
6. Write a program that reads a string using command line and will find the longest and shortest (in
terms of length) word in the string.
7. Write a program to remove common characters from two strings.
8. Write a program to print all the palindrome words of a given string.
9. Write a program to convert all the starting character of each word of a particular string into upper
case. (e.g. Input: national institute of science and technology, Output: National Institute Of Science
And Technology)
10. Write a program, which reads number n and n strings. The program outputs the string, which has the
longest length.
11. Write a program to input a sentence and arrange each word of the string in alphabetical order.
12. Create a class CharArray with having following methods:
char getChar(int i); void setChar(int i,char c); int getFirstIndex(char c);
void replace(char old,char nw); String toString(); boolean equals(char[]); void swap(char[]);
13. Create a StringBuffer class object with contents “National Institute of Science & Technology” and
apply the following methods of its own class:
delete(5,15); append(78); insert(4,”NA”); reverse();
deleteCharAt(length()-1); append(‘s’); replace(0,2,”RA”);
Write the above codes in a program and check the output.
14. Write a class RevClass and overload a method as follows:
String revString(String s);
void revString(StringBuffer sb);
This revString() is a method that will reverse the respective object which is the argument. First, form
a string out of all the strings supplied through command line arguments and then pass it to this
method by converting into the respective type.
15. Write a class PalindromeClass and overload a method as follows:
int numPalString(String s[]); int numPalString(StringBuffer sb[]);
This numPalString() is a method that will count the number of palindrome strings among the strings
supplied through command line arguments.
16. Input some strings through command line. Half of which will be stored in a String array and rest will
be stored in a StringBuffer array. Write a program that will concatenate each element of this array of
String objects with each element of StringBuffer objects. And the result will be stored in an array of
StringBuffer.
17. Create a String class object with contents “JAVA – The Great” and apply the following methods of
its own class:
concat(“ And Powerful Language.”); replace(‘V’,’B’); substring(11);
“smiles”.substring(1,5); “NIST”.toLowerCase(); “JavA”.toUpperCase();
“ Indians Spride “.trim();
Write the above codes in a program and check the output.
18. Write a program to count the number of repetition of a string in an array of strings.
19. Suppose string has words. e.g. Ram is a good boy
a. find first and second word.
b. Remove all blanks. In above case Ramisagoodboy.
c. Find last letter of first word.
d. Find first letter of last word.
e. Find first letter of every word.
f. Word wise reverse of the string. In above case boy good a is Ram.
20. Write a program that reads in four strings and prints the lexicographically smallest and largest one.
Enter four strings:
Charlie
42
National Institute of Science and Technology
Able
Delta
Baker
The lexicographic minimum is Able.
The lexicographic maximum is Delta.
Experiment – 9
Applet, AWT and Swings
(1) Applet Program
import java.applet.Applet;
import java.awt.*;
/*<applet code=CompleteApplet width=700 height=550> </applet>*/
public class CompleteApplet extends Applet
{ public void paint(Graphics g)
{ setBackground(Color.cyan); g.setColor(new Color(255, 215,156));
g.setFont(new Font("San-serif", Font.BOLD, 24));
g.drawString("NIST welcomes you 4 Summer 2012", 10, 30);
g.setColor(Color.BLUE); g.drawRect(20, 50, 50, 30);
g.setColor(Color.RED); g.fillRect(100, 50, 50, 30);
g.drawImage(getImage(getCodeBase(), "rose.jpg"), 20, 100, this);
play(getCodeBase(), "spacemusic.au");
}
}
Compile: javac CompleteApplet.java
RUN: appletviewer CompleteApplet.java
43
National Institute of Science and Technology
44
National Institute of Science and Technology
}
public void mouseEntered(MouseEvent event) { addItem("mouse entered! "); }
public void mouseExited(MouseEvent event) { addItem("mouse exited! "); }
public void mousePressed(MouseEvent event) { }
public void mouseReleased(MouseEvent event) { }
public void mouseClicked(MouseEvent event) { addItem("mouse clicked! "); }
}
(6) Read two Numbers from Dialog Box and find the Sum
import javax.swing.*;
public class ReadNumbers
{ public static void main(String[ ] args)
{ String str; int n1, n2, sum;
str=JOptionPane.showInputDialog("Enter First number : ");
str=str.trim(); // removes blanks at the beginning and at the end
n1=Integer.parseInt(str);
str=JOptionPane.showInputDialog("Enter Second number : ");
str=str.trim(); // removes blanks at the beginning and at the end
n2=Integer.parseInt(str);
sum=n1+n2;
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE );
}
}
(7) JAVA Swing Example
import java.awt.*;
import javax.swing.*;
class DrawSmiley extends JPanel
{ public void paintComponent( Graphics g )
{ super.paintComponent( g );
// draw the face
g.setColor( Color.YELLOW ); g.fillOval( 10, 10, 200, 200 );
// draw the eyes
g.setColor(Color.BLACK); g.fillOval(55,65,30,30); g.fillOval(135,65,30,30);
// draw the mouth
g.fillOval( 50, 110, 120, 60 );
// "touch up" the mouth into a smile
g.setColor(Color.YELLOW);g.fillRect(50,110,120,30);g.fillOval(50,120,120,40);
}
}
public class DrawSmileyTest
{ public static void main( String args[] )
{ DrawSmiley panel = new DrawSmiley();
JFrame application = new JFrame();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
application.add( panel ); application.setSize( 230, 250 );
application.setVisible( true );
}
}
1) Write an applet program to display “Hello World!” by using appletviewer or internet explorer.
45
National Institute of Science and Technology
2) Write an applet program to take a student’s name and roll_num as parameter using param tag
and display it.
3) Write a private method that builds the top panel as follows
a) Create a panel that contains three buttons, red, orange, and yellow.
b) Use flow layout for the panel and set the background to be white.
c) The buttons should be labeled with the color name and also appear in that color.
d) Set the action command of each button to be the first letter of the color name.
e) Add button listener that implements action listener for each button.
4) Create a bottom panel in the same way as the top panel above in question-3, but use radio buttons
with the colors green, blue, and cyan.
5) Write an applet program to display all geometrical shapes by using the following,
Graphics methods - drawLine, drawRect, fillRect, drawOval, fillOval
drawArc, fillArc, drawPolygon, fillPolygon
6) Write an applet program to display the digital clock.
8) Write a program to input the name, and marks in three subjects of a Student and print the total
and average marks. The name is a String and marks are all float quantities. The Frame will be of
the following format.
After typing the details we shall click the OK button and the message of the following format
will be displayed in the Window at the bottom.
Total marks : 240
Average : 80
Result : Pass
9) Write a java program create a Frame as described below:
In the window there are four radio buttons called Add, Sub,Mul and Div at the top. This group is
called Operation. There are two textField objects to input the first and second number. We must
type the numbers and select one of the operations. When we click the perform button, the result
is displayed. For example if the first numbers is 10 and second number is 72 and operation
selected is Mul the result is displayed as follows
The Result is 720
10) Write a program to implement the following layout managers
CardLayout
FlowLayout
GridLayout
11) WAP that the scroll bars determine the red, green and blue components of the background of the
panel like below. Here when we scroll the vertical scroll bars the colour of the panel will change.
46
National Institute of Science and Technology
47
National Institute of Science and Technology
Experiment – 10
JDBC and files
(1) JDBC
import java.sql.*;
class DatabaseTest
{ public static void main(String args[ ])
{ try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:nistDsnName","","");
Statement st=con.createStatement();
st.execute("create table dept(deptno number,deptname text(20))");
st.execute("insert into dept values(101,'Accounts');");
st.execute("insert into dept values(102,'Purchase');");
st.execute("insert into dept values(103,'Sales');");
st.execute("insert into dept values(104,'Advertisement');");
st.execute("insert into dept values(105,'Computers');");
st.execute("select * from dept"); ResultSet rs=st.getResultSet();
if(rs!=null)
while(rs.next( ))
{ System.out.print("Department No :: " + rs.getString(1) + "\t");
System.out.println("Department Name :: " + rs.getString(2));
}
rs.close(); st.close(); con.close();
} catch(Exception e) { System.out.println("ERROR : " + e.getMessage()); }
}
}
(2) JDBC through MsAccess
import java.awt.*;
import java.sql.*;
import javax.swing.*;
public class BooksDataBase extends JFrame
{ //JDBC driver name and database URL
static final String JDBC_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
static final String DATABASE_URL = "jdbc:odbc:DRIVER={Microsoft Access
Driver (*.mdb)};DBQ=c:\\Books.mdb";
private Connection con; private Statement statement;
//constructor connects to database, queries, processes results and displays results in window
public BooksDataBase()
{ super("Books");
//connect to database Books.mdb and query database
try{ //specify location of database on filesystem
System.setProperty( "C:\\Books.mdb","null" );
//load database driver class
Class.forName(JDBC_DRIVER);
//establish connection to database
con = DriverManager.getConnection(DATABASE_URL);
//create statement for querying database
statement = con.createStatement();
//query database
ResultSet resultSet = statement.executeQuery("SELECT authorid,
48
National Institute of Science and Technology
49
National Institute of Science and Technology
}
} //end class DisplayMembers
50
National Institute of Science and Technology
}
public static void main (String [] args)
{ doReadIntFromConsole();
}
}
(5) Reading contents from File
import java.io.*;
class MyFile
{ public static void main(String arguments[])
{ String temp="",fileName="stud.txt";
try{ FileReader fr= new FileReader(fileName); //open a new file stream
BufferedReader br= new BufferedReader(fr); //wrap it in a buffer
while((temp=br.readLine())!=null)
System.out.println("> "+temp);
fr.close();
}
catch(Exception e) { System.out.println("Error is "+e); }
}
}
(6) Writing contents into File
import java.io.*;
public class IOTest
{ public static void main(String[] args)
{ try { //To create a stream object and associate it with a disk-file
FileWriter out = new FileWriter("test.txt");
// Give the stream object the desired functionality
BufferedWriter bw = new BufferedWriter(out);
PrintWriter pr = new PrintWriter(bw);
// write data to the stream
pr.println("This is NIST");
pr.println("Here we are teaching Java Certification course");
// close the stream
pr.close();
} catch (IOException e) { System.out.println(e); }
}
}
1) WAP to display the student records which are stored in the MS-Access data base through JDBC
2) WAP to connect with database (oracle), create a table, insert the data, update the table, delete the data.
3) Design a GUI interface and do the above operations of question-2.
4) WAP to display the student records which are stored in the MS-Access data base through JDBC.
5) Program to print all the .java files which are containing in your directory
6) WAP to implement the SQL commands using JDBC.
51
National Institute of Science and Technology
52
National Institute of Science and Technology
Experiment – 11
Collections, inner classes, Java Bean and Generics
(1) sort the elements of the list
import java.util.*;
public class Sort
{ private static final String suits[] = { "Hearts", "Diamonds", "Clubs", "Spades" };
public void printElements()
{ List< String > list = Arrays.asList( suits ); // create List
System.out.printf( "Unsorted array elements:\n%s\n", list ); // output list
Collections.sort( list ); // sort ArrayList
System.out.printf( "Sorted array elements:\n%s\n", list); // output list
} // end method printElements
public static void main( String args[] )
{ Sort srt = new Sort();
srt.printElements();
}
}
(2) Vector Class
//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("\nThe elements of a vector are :");
Enumeration e=v.elements();
while(e.hasMoreElements())
System.out.println(e.nextElement() +" ");
System.out.println("\nThe 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)+" ");
}
}
53
National Institute of Science and Technology
class Test
{ public static void main(String arg[])
{ Outer obj= new Outer();
Outer.Inner in = obj.new Inner();
in.message();
}
}
54
National Institute of Science and Technology
class Employee
{ public static void main(String arg[])
{ person p=new Person()
{ void eat(){ System.out.println(“Gree JAVA”); }
};
p.eat();
}
}
Interface
interface Eatable
{ void eat( );
}
class Employee
{ public static void main(String arg[])
{ Eatable e=new Eatable()
{ public void eat(){ System.out.println(“Gree JAVA”); }
};
e.eat();
}
}
55
National Institute of Science and Technology
}
Local lo = new Local();
lo.message();
}
56
National Institute of Science and Technology
57
National Institute of Science and Technology
public T pop ()
{ return stack.remove (--top);
}
(10) JavaBeans
A JavaBean property is a named attribute that can be accessed by the user of the object. The attribute
can be of any Java data type, including classes that you define.
A JavaBean property may be read, write, read only, or write only. JavaBean properties are accessed
through two methods in the JavaBean's implementation class:
Method Description
For example, if property name is firstName, your method
getPropertyName() name would be getFirstName() to read that property. This
method is called accessor.
For example, if property name is firstName, your method
setPropertyName() name would be setFirstName() to write that property. This
method is called mutator.
A read-only attribute will have only a getPropertyName() method, and a write-only attribute
will have only a setPropertyName() method.
Example:
class Employee implements java.io.Serializable{
private int id;
58
National Institute of Science and Technology
public Employee(){}
System.out.println(e.getName());
}}
59
National Institute of Science and Technology
13) Define a Student class (roll number, name and marks). Define a java bean to calculate the grade of
students.
14) class called television has the following attributes:
e. Manufacturer
f. Size of the screen
g. Date of purchase of the TV
h. Is it a color TV
Define a class television. Declare a suitable java bean to maintain the record of the TV.
To demonstrate using our user-defined exception, the following CheckingAccount class contains a
withdraw() method that throws an InsufficientFundsException.
The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of
CheckingAccount.
60
National Institute of Science and Technology
61