Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Lab Manual

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 61

National Institute of Science and Technology

Accredited by
NAAC(UGC) with ‘A’ Grade

JAVA Programming
Lab Manual for B.Tech

National Institute of Science & Technology


Palur Hills, Berhampur, Odisha.

1
National Institute of Science and Technology

Standard Lab Procedure

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

Evaluation of Laboratory & Grading Policy

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;

If no setting of path variable is exists then write following code.


PATH=%PATH%; C:\jdkx\bin;

Where x represents the version number. Eg. 1.6.0 or 1.6.2


Step 2: Set CLASSPATH environment variable to access java library classes. To set it
write the following code in C:\autoexec.bat file.
CLASSPATH=%CLASSPATH%; C:\jdkx\lib;

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

public class HelloWorld


{ public static void main (String args[ ])
{ System.out.println ("Hello World!");
}
}
//Save this code in a file as HelloWorld.java

Step 2: Compile the application with the command line:


javac HelloWorld.java
This creates the class file (with the byte code output): HelloWorld.class

Step 3: Use the java command to run the program:


java HelloWorld
Hello World!
The output is printed after the command line.

Hint for setting the path in Command Prompt:


C:\nist> set path="C:\Program Files (x86)\Java\jdk1.7.0_02\bin"; %path%;

Read an input from the keyboard:

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

(3) Print the System Date


import java.util.*;
public class Today
{ public static void main (String[] args)
{ System.out.print("Welcome to the World of Java");
System.out.println(new Date());
}
}

(4 ) Scanner class example:

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.

Simple example of command-line argument in java

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

Example of command-line argument that prints all the values

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

Student s2=new Student();


s2.getData(“Kapil”,”Delhi”,23);
s2.printData();
s1.getData(“Amit”,”Dehradun”,22);
s1.printData();
}
}

Java Program to illustrate how to define a class and fields :


Main() method is inside the class:
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Main() method is in another class:

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

//Java Program to create and call a 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);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}

Java Program to demonstrate the use of the parameterized constructor.

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

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object

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

c. Date of purchase of the TV


d. Is it a color TV
Define a class television. Define a method for displaying the attribute values of a TV.

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

void area(int a,int b) { System.out.println("Area of rectangle: " +(a*b)); }

void area(float a,float b) { System.out.println("Area of rectangle: " +(a*b)); }


}

public class FuncOverloading


{ public static void main(String[ ] args)
{ Shape m=new Shape(); int a,b; System.out.println("Enter the two numbers: ");
Scanner s= new Scanner(System.in); a = s.nextInt(); b = s.nextInt();
m.area(); m.area(a); m.area(a,b); m.area(5.5f,6.5f);
}
}

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

public class FuncOverriding


{ public static void main(String[] args)
{ B b=new B();
b.show();
}
}
Example:
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
(3) Overriding toString( ) Method
public class Faculty
{ String name; int empid;
Faculty( ) { name="James Smith"; empid=2912; }
public String toString()
{ return ("Faculty name is " + name + ", and empid is " + empid);
}
public static void main( String args[] )
{ Faculty f=new Faculty();
System.out.println(f);
}
}
Inheritance: Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
Types of inheritance:

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.

(4) Multilevel Inheritance


Write a Java Program to implement multilevel inheritance by applying various access controls to its
data members and methods.

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

class Marks extends Student


{ protected int m1,m2,m3;
void getmarks()
{ try
{ System.out.println("Enter marks :");
m1=Integer.parseInt(dis.readLine());
m2=Integer.parseInt(dis.readLine());
m3=Integer.parseInt(dis.readLine());
}
catch(Exception e) { }
}

void putmarks()
{ System.out.println("m1="+m1);
System.out.println("m2="+m2);
System.out.println("m3="+m3);
}
}

class Result extends Marks


{ private float total;
void compute_display()
{ total=m1+m2+m3;

16
National Institute of Science and Technology

System.out.println("Total marks :" +total);


}
}
class MultilevelDemo
{ public static void main(String arg[])
{ Result r=new Result();
r.getrollno();
r.getmarks();
r.putrollno();
r.putmarks();
r.compute_display();
}
}

Single inheritance example:


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();
}}
hierarchical inheritance example:

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
}}

1. Write a java program to implement single inheritance.


2. Define a class dimension, inherit class line from dimension, rectangle from line, and box from
rectangle. Write down get and set functions in each class. Write a print function in each class to print

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.

Relationship between classes and interfaces:

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

(2) Implementation of Interface


interface Area
{ final static float pi=3.14F; float compute(float x,float y);
}
class Rectangle implements Area
{ public float compute(float x,float y) { return(pi*x*y); }
}
class Circle implements Area
{ public float compute(float x,float x) { return(pi*x*x); }
}
class InterfaceDemo
{ public static void main(String a[])
{ Rectangle rect=new Rectangle(); Circle cir=new Circle(); Area A;
A=rect; System.out.println("Area of rectangle="+A.compute(10,20));
A=cir; System.out.println("Area of circle="+A.compute(30,0));
}
}

(3) Extending Interface


interface Area
{ final static float pi=3.14F; double compute(double x,double y);
}
interface Display extends Area { void display_result(double result); }

class Rectangle implements Display


{ public double compute(double x,double y) { return(pi*x*y); }
public void displayResult(double result)
{ System.out.println("The Area is :" +result);
}
}

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:

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is


known as multiple inheritance.

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

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}

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

public static void main(String args[]){


TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}

22
National Institute of Science and Technology

Default method in interface:

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

Static method in interface:


interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}

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

public void b(){System.out.println("I am b");}


public void d(){System.out.println("I am d");}
}

//Creating a test class that calls the methods of A interface


class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}

Package: A java package is a group of similar types of classes, interfaces and sub-packages.

Simple example of java package:


The package keyword is used to create a package in java.

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

(4) Creating a user defined Package P1


package p1;
public class Student
{ int regno; String name;
public void getdata(int r,String s) { regno=r; name=s; }
public void putdata()
{ System.out.println("Regno = " +regno); System.out.println("Name = " + name);
}
}
Importing a classes from a user defined Package
import p1.Student;
class StudentTest
{ public static void main(String arg[])
{ Student s=new Student();
s.getdata(201110786,"Anusha"); s.putdata();
}
} *********************************OUTPUT**************
C:\jdk1.6.0_26\bin>javac ─ d ∙ Student.java
C:\jdk1.6.0_26\bin>javac StudentTest.java

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:

There are two types of array.

 Single Dimensional Array


 Multidimensional Array

1. //Java Program to illustrate how to declare, instantiate, initialize

//and traverse the Java 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();
}
}}

Jagged array in java:

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

//Java Program to illustrate the jagged array

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

//printing the data of a jagged array


for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}

//Java Program to demonstrate the addition of two matrices in Java

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

//creating another matrix to store the sum of two matrices


int c[][]=new int[2][3];

//adding and printing addition of 2 matrices


for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}

}}

28
National Institute of Science and Technology

(1) Array of Objects


class Employee
{ private String name; private double salary;
public Employee(String n, double s) { name = n; salary = s; }
public void print() { System.out.println(name + " " + salary); }
}
public class EmployeeTest{
public static void main(String[] args)
{ Employee[] staff = new Employee[3];
staff[0] = new Employee("James Bond", 3500);
staff[1] = new Employee("Carl Cracker", 7500);
staff[2] = new Employee("Tony Tester", 3800);
for (int i = 0; i < 3; i++) staff[i].print();
}
}
(2) Average of Numbers through command line args
class Average{
public static void main(String args[])
{ int n=args.length; float sum=0;
float [] x=new float[n];
for(int i=0; i<n; i++) { x[i]=Float.parseFloat(args[i]); }
for(int i=0; i<n; i++) sum=sum+x[i];
float avg=sum/n;
System.out.println("Average of given numbers is "+avg);
}
}

(3) Enhanced for statement


// WAP to print sum of the elements of an array using enhanced for statement
public class EnhancedForTest {
public static void main( String args[] )
{ int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
int sum = 0;
// add each element's value to total
for ( int number : array )
sum += number;
System.out.printf( "Sum of the elements of an array :: %d\n", sum);
} // end main
} // end of class EnhancedForTest
(4) 2-D Array
public class MultiDimensionalArray{
public static void main( String args[] )
{ int arr[][] = { {2, 9, 1, 2}, {1, 1}, {4,5,6}, {0,4,3,7,2,9}, {7,8,6}, {1,2,3,4,5} };
System.out.println( "Values in array by row are" );
outputArray(arr); // displays array by row
} // end of main
// output rows and columns of a two-dimensional array
public static void outputArray(int array[][])
{ // loop through array's rows

29
National Institute of Science and Technology

for(int row = 0; row < array.length; row++ )


{ // loop through columns of current row
for(int column = 0; column < array[row].length; column++ )
System.out.printf( "%d ", array[row][column] );
System.out.println(); // start new line of output
} // end of outer for
} // end of method outputArray
} // end of class MultiDimensionalArray
(5) Addition of two matrices
class Addition
{ public static void main(String args[])
{ int [][] x={{1,2,3},{4,5,6},{7,8,9}};
int [][] y={{11,12,13},{14,15,16},{17,18,19}};
int [][] z=new int[3][3];
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
{ z[i][j]=x[i][j]+y[i][j];
}
for(int i=0; i<3; i++)
{ for(int j=0; j<3; j++)
{ System.out.print(z[i][j]+” ”);
}
System.out.print(“\n”);
}
}
}
1. Write a java program to sort an array of 10 elements using bubble sort.
2. Write a java program to implement binary search for 10 elements.
3. Define a class CricketPlayer (name, no_of_innings, no_times_notout, total_runs, bat_avg).
Create an array of n player objects. Calculate the batting average for each player using a method
avg(). Define a method “sortPlayer” which sorts the array on the basis of average. Display the
player details in sorted order.
4. Write a java program to create n objects of the Student class. Assign roll numbers in the
ascending order using static method. Accept name and percentage from the user for each object.
Define a method “sort Student” which sorts the array on the basis of percentage
5. WAP to swap two numbers by using callbyvalue and callbyreference using an array.
6. Write a program to find out the maximum and minimum element in an array of floating point
numbers supplied by the user.
7. Write a program to count the number of repetition of a string in an array of strings.
8. Write a program to multiply two square matrices whose dimension and values is specified by the
user.
9. Write a program to add two matrices of floating point numbers whose dimension and values is
specified by the user.
10. Count occurrence of a given number in an array.
11. Input two arrays and merge them in a new array in ascending order.
12. WAP to print sum of the elements of an array using enhanced for statement
13. Write program, which reads an expression and finds its value. Input (((6+3)*8)(4*3)) output 60.
14. Read a complex number and print it in simplified form. Input 7i+12i+9+4i-8i+13 output 22+15i.

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.

Hierarchy of Java Exception classes

Types of Java Exceptions

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

Java Exception Keywords


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

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

public class TryCatchExample2 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

32
National Institute of Science and Technology

MultipleCatchBlock1.java

public class MultipleCatchBlock1 {


public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

NestedTryBlock.java

public class NestedTryBlock{


public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}

//inner try block 2


try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}

33
National Institute of Science and Technology

//catch block of inner try block 2


catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}

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:

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.

The finally block follows the try-catch block.

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

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


}
}

34
National Institute of Science and Technology

(1) Predefined Exceptions


//Write a program to implement the concept of Exception Handling using predefined
exception.
class ExcHandling
{ public static void main(String argv[])
{ int a=10,b=5,c=5,x,y;
try { x=a/(b-c); }
catch(ArithmeticException e) { System.out.println("DIVISION BY
ZERO"); }
y=a/(b+c); System.out.println("y="+y);
}
} OUTPUT:
DIVISION BY ZERO
y=1

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

(2) Userdefined Exceptions


//WAP to implement the concept of Exception Handling by creating user defined exceptions.
import java.io.DataInputStream;
class MyException extends Exception
{ MyException(String message) { super(message); }
}

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

a) If the no of arguments are less than 3 then fire “IllegalNumberOfArguments”


b) If the operator is not an Arithmetic operator, throw “InvalidOperatorException”.
c) If result is –ve, then throw “NegativeResultException

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.

class xyz implements Runnable class nist


{ int k; { public static void main(String
xyz(int g) {k=g;} ar[])
public void run() { xyz x,y;Thread a,b;
{ int i; x=new xyz(5);
for (i=k;i<k*2;i++) a=new Thread(x);
{ System.out.print(i); y=new xyz(3);
try { Thread.sleep(1000); } b=new Thread(y);
catch(Exception e) { } a.start();b.start();
} }
} }
}

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

1. Write a java program to implement thread using runnable interface


2. Write a java program to implement thread using the thread class
3. Write a java program to create and start two threads, each of which prints two lines to
System.out
4. Write a java program to creates ten threads, each of which do some work(search for the
maximum value of a large matrix .Each thread searches one portion of the matrix.) It waits for
them all to finish, then gathers the results.
5. Write a java program to show the use of synchronized method ().
6. Write a java program to show the use of wait (), notify (), notify all() methods.
7. Write a program to explain the multithreading with the use of multiplication Tables. Three
threads must be defined. Each one must create one multiplication table; they are 5 table, 7
table and 13 table.
8. Write a program to name the thread. In the main program change the name of the thread.
9. Write a program to illustrate thread priority. Create three threads and assign three different
priorities.

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

(2) Applets by passing parameters


import java.applet.*;
import java.awt.Graphics;
/* <applet code="AppletParamDemo.class" width=300 height=100>
<param name=person value="Khalid Mughal">
<param name=subject value="Java Programming Instructor"> </applet> */
public class AppletParamDemo extends Applet
{ String p,c;
public void init( ) { p=getParameter("person"); c=getParameter("subject"); }
public void paint(Graphics g) { g.drawString(p,80,20); g.drawString(c,100,40); }
}
(3) Menu System
import java.awt.*;
import java.awt.event.*;
class MenuSystem
{ private MenuBar mb;
private Menu One, Two, Three;
private MenuItem mi1, mi2, mi3, mi4, mi5, mi6;
private CheckboxMenuItem cmi;
private Frame frm;
public void launchFrame()
{ frm = new Frame("Menu System"); frm.setSize(400,400);
mb = new MenuBar();
One = new Menu("File");
Two = new Menu("Edit");

43
National Institute of Science and Technology

Three = new Menu("Format");


One.add(mi1 = new MenuItem("New"));
One.add(mi2 = new MenuItem("Open"));
One.add(mi3 = new MenuItem("Close"));
Two.add(mi4 = new MenuItem("cut"));
Two.add(mi5 = new MenuItem("copy"));
Two.add(mi6 = new MenuItem("paste"));
Three.add(cmi = new CheckboxMenuItem("Word Wrap"));
mb.add(One); mb.add(Two); mb.add(Three);
frm.setMenuBar(mb); frm.setVisible(true);
}
public static void main(String args[])
{ MenuSystem ms = new MenuSystem();
ms.launchFrame();
}
}
(4) Swing Program
import javax.swing.JOptionPane;
public class Dialog
{ public static void main( String args[] )
{ JOptionPane.showMessageDialog( null, "We Teaches\nfor\nJAVA" );
}
}

(5) Event Handling


import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;
/* <applet code=ExampleEventHandling width=400 height=500> </applet> */
public class ExampleEventHandling extends Applet implements MouseListener
{ StringBuffer strBuffer;
public void init()
{ addMouseListener(this);
strBuffer = new StringBuffer();
addItem("initializing the apple ");
}
public void start( ) { addItem("starting the applet "); }
public void stop( ) { addItem("stopping the applet "); }
public void destroy( ) { addItem("unloading the applet"); }
void addItem(String word)
{ System.out.println(word);
strBuffer.append(word); repaint();
}
public void paint(Graphics g)
{ //Draw a Rectangle around the applet's display area.
g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);

//display the string inside the rectangle.


g.drawString(strBuffer.toString(), 10, 20);

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.

7) Write an applet program to display the following by using different layouts.

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

12) WAP to implement the Simple calculator.

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

firstName, lastName FROM Authors");


//process query results
StringBuffer results = new StringBuffer();
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
for( int i = 1; i <= numberOfColumns;i++)
results.append( metaData.getColumnName(i) + "\t");
results.append("\n");
while (resultSet.next())
{ for (int i = 1; i <= numberOfColumns; i++)
results.append( resultSet.getObject(i) + "\t");
results.append("\n");
}
//set up GUI and display window
JTextArea textArea = new JTextArea( results.toString() );
Container container = getContentPane();
container.add( new JScrollPane( textArea ));
setSize( 350, 300 ); //set window size
setVisible ( true );
}//end try
//detect problems interacting with database
catch ( SQLException sqlException )
{ JOptionPane.showMessageDialog( null,
sqlException.getMessage(), "Database Error",
JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
}
//detect problems loading database driver
catch ( ClassNotFoundException classNotFound )
{ JOptionPane.showMessageDialog( null, classNotFound.getMessage(),
"Driver Not Found", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
}

//ensure statement and connection are closed properly


finally
{ try { statement.close(); con.close(); }
//handle exceptions closing statement and connection
catch(SQLException sqlException)
{ JOptionPane.showMessageDialog( null,
sqlException.getMessage(),
"Database Error", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
}
}
}//end NSBEdatabase constructor

public static void main( String[] args)


{ BooksDataBase window = new BooksDataBase();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

49
National Institute of Science and Technology

}
} //end class DisplayMembers

(3) JDBC Connection through Oracle


Java JDBC Connection Example, JDBC Driver Example
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCDriverInformation
{ static String userid=”scott”, password = “tiger”;
static String url = “jdbc:odbc:bob”;
static Connection con = null;
public static void main(String[] args) throws Exception
{ Connection con = getOracleJDBCConnection();
if(con!= null)
{ System.out.println(”Got Connection.”);
DatabaseMetaData meta = con.getMetaData();
System.out.println(”Driver Name : “+meta.getDriverName());
System.out.println(”Driver Version : “+meta.getDriverVersion());
}
else System.out.println(”Could not Get Connection”);
}
public static Connection getOracleJDBCConnection()
{ try { Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”);
}
catch(java.lang.ClassNotFoundException e)
{ System.err.print(”ClassNotFoundException: “);
System.err.println(e.getMessage());
}
try { con = DriverManager.getConnection(url, userid, password);
}
catch(SQLException ex)
{ System.err.println(”SQLException: ” + ex.getMessage());
}
return con;
}
}

(4)Read an Input from Console


import java.io.*;
Public class ReadIntFromConsole
{ private static void doReadIntFromConsole() throws IOException
{ String inline = null;
int checkInteger = 0;
Buffered Reader br = new BufferedReader (new InputStreamReader(System.in));
System.out.print("Enter a valid Integer and hit <ENTER>: ");
inline = br.readLine();
checkInteger = Integer.parseInt(inline);
System.out.println("You entered a valid Integer: " + checkInteger);

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

7) WAP to write the contents into the file


8) WAP to read the contents of the file
9) WAP to copy the one file into another file.
10) WAP to concatenate the one file into the end of another file.

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)+" ");
}
}

Compile: C:\nist> javac ─Xlint VectorDemo.java


Run: C:\nist> java VectorDemo

53
National Institute of Science and Technology

Types of Nested Classes

Non-static (inner classes) static nested classes

Member class Anonymous Local class


class
(3) Member Class
A class that is declared inside a class but outside a method is knoiwn as member inner class.
Invocation of Member Inner class
 From within the class
class Outer
{ private int data=50;
class Inner
{ void message() { System.out.println(“Data is “ + data); }
}
void display( )
{ Inner in= new Inner();
in.message();
}
public static void main(String arg[])
{ Outer obj= new Outer();
obj.display();
}
}

 From outside the class


class Outer
{ private int data=100;
class Inner
{ void message() { System.out.println(“Data is “ + data); }
}
}

class Test
{ public static void main(String arg[])
{ Outer obj= new Outer();
Outer.Inner in = obj.new Inner();
in.message();
}
}

(4) Annonymous Inner Class


A class that have no name is known as annomymous inner class.
Annomymous can be created by:
 Clas (may be abstract class also)
abstract class Person

54
National Institute of Science and Technology

{ abstract void eat( );


}

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

(5) Local Inner Class


A class that is created inside a method is known as local inner class. If you want to invoke the
methods of local inner class, you must instantiate this class inside the method.
class Simple
{ private int data=50;
void display( )
{ class Local
{ void mesasage() { System.out.println(data); }
}
Local lo = new Local();
lo.message();
}
public static void main(String arg[])
{ Simple obj=new Simple();
obj.display( );
}
}

Accessing Non-final Local variables


class Simple
{ private int data=50;
void display( )
{ int value=100; //Local Varaible must be final
class Local
{ void mesasage() { System.out.println(value); } //Comple ERROR

55
National Institute of Science and Technology

}
Local lo = new Local();
lo.message();
}

public static void main(String arg[])


{ Simple obj=new Simple(); obj.display( );
}
}
RUN: Compile Error

Accessing final Local variables


class Simple
{ private int data=50;
void display( )
{ final int value=100; //Local Varaible must be final
class Local
{ void mesasage() { System.out.println(data + “ “ + value); } //OK
}
Local lo = new Local(); lo.message();
}
public static void main(String arg[])
{ Simple obj=new Simple();
obj.display( );
}
}
RUN: 50 100

(6) Static nested class


A static class that is created inside a class is known as static nested class. It cannot access the
non-static members.
 It can access static data members of outer class including private.
 Static nested class cannot access non-static data members or methods.

Static nested class that have instance method


class Outer
{ private int data=50;
static class Inner
{ void message() { System.out.println(“Data is “ + data); }
}
public static void main(String arg[])
{ Outer.Inner obj= new Outer.Inner();
obj.message();
}
}

Static nested class that have static method


class Outer
{ static int data=50;
static class Inner

56
National Institute of Science and Technology

{ void message() { System.out.println(“Data is “ + data); }


}

public static void main(String arg[])


{ Outer.Inner.message(); //No need to create an instance of static nested class
}
}
(7) Nested Interface
interface Showable
{ void show();
interface Message
{ void msg();
}
}
class Test implements Showable.Message
{ public void msg() { System.out.println("Hello nested interface"); }
public static void main(String args[ ])
{ Showable.Message message=new Test(); //upcasting here
message.msg();
}
}

(8) Generic Method


public class MaximumTest
{ // determines the largest of three Comparable objects
public static <T extends Comparable<T>> T maximum(T x, T y, T z)
{ T max = x; // assume x is initially the largest
if ( y.compareTo( max ) > 0 )
{ max = y; // y is the largest so far
}
if ( z.compareTo( max ) > 0 )
{ max = z; // z is the largest now
}
return max; // returns the largest object
}
public static void main( String args[] ){
System.out.printf( "Max of %d, %d and %d is %d\n\n", 3, 4, 5, maximum(3,4,5));
System.out.printf( "Maxm of %.1f,%.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7,
maximum( 6.6, 8.8, 7.7 ) );
System.out.printf( "Max of %s, %s and %s is %s\n","pear", "apple", "orange",
maximum( "pear", "apple", "orange" ) );
}
}

57
National Institute of Science and Technology

(9) Generic Class


import java.util.*;
public class GenericStack <T>
{ private ArrayList<T> stack = new ArrayList<T> ();
private int top = 0;
public int size () { return top; }
public void push (T item)
{ stack.add (top++, item);
}

public T pop ()
{ return stack.remove (--top);
}

public static void main (String[] args)


{ GenericStack<Integer> s1 = new GenericStack<Integer> ();
GenericStack<String> s2 = new GenericStack<String> ();
s2.push("Anusha");
String name=s2.pop();
s1.push (2912);
int dob = s1.pop ();
System.out.format ("\n%s%n", name);
System.out.format ("\n%4d%n", dob);
}
}

(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

private String name;

public Employee(){}

public void setId(int id){this.id=id;}

public int getId(){return id;}

public void setName(String name){this.name=name;}

public String getName(){return name;}

public class Test{


public static void main(String args[]){

Employee e=new Employee();//object is created

e.setName("Arjun");//setting value to the object

System.out.println(e.getName());

}}

1) Create Stack and do the push pop operation on that


2) Create a Queue and do the enqueue and dequeue operation on that
3) Create a TreeMap and do the operation on that
4) Create a LinkedList and add, delete the elements from the List.
5) Create a HashTable and do the operations.
6) Create a Vector list and store different types of objects in that.
7) Define stack using two queues. An element is put in stack by putting in first queue. An element is
taken from stack by taking last element of first queue. Another queue acts as auxiliary queue.
8) WAP to print the the array of intergers, floats, chars and strings using generic method.
9) WAP to implement the generic queue and linked lists.
10) Define a class Employee having private members – id, name, department, salary. Create a subclass
called “Manager” with private member bonus. Define a java bean for all the classes. Create n objects
of the Manager class and display the details of the manager having the maximum total salary (salary
+ bonus).
11) Define a class Bank which records the information of a client. Define another class Account which
manages the account information and is a subclass of Bank. Define a java bean to manage the client
information as well as Account information.
12) Define a class called Room with the following 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 java bean for
accepting and displaying the details of a room. Assume that 20% of the total wall area is occupied
by doors and windows.

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.

Sample Code for Mini Project:


// File Name InsufficientFundsException.java
import java.io.*;
public class InsufficientFundsException extends Exception
{ private double amount;
public InsufficientFundsException(double amount)
{ this.amount = amount;
}
public double getAmount()
{ return amount;
}
}

To demonstrate using our user-defined exception, the following CheckingAccount class contains a
withdraw() method that throws an InsufficientFundsException.

// File Name CheckingAccount.java


import java.io.*;
public class CheckingAccount
{ private double balance;
private int number;
public CheckingAccount(int number) { this.number = number; }
public void deposit(double amount) { balance += amount; }
public void withdraw(double amount) throws InsufficientFundsException
{ if(amount <= balance)
balance -= amount;
else
{ double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance( ) { return balance; }
public int getNumber( ) { return number; }
}

The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of
CheckingAccount.

60
National Institute of Science and Technology

// File Name BankDemo.java


public class BankDemo
{ public static void main(String [] args)
{ CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try
{ System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}
catch(InsufficientFundsException e)
{ System.out.println("Sorry, but you are short $" + e.getAmount());
e.printStackTrace();
}
}
}

61

You might also like