Vous êtes sur la page 1sur 36

ADIT/IT/LM/2150704/00

Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

INDEX
S R. EXPT. PAGE NO. OF
TITLE
NO. NO. NO. PAGES
1 - Table of contents 01 01
1 - Revision Record Sheet 02 01
2 - Control copy holder 03 01
3 - General Instructions 04 01
4 - List of experiments - -
To set PATH environment variable and to build simple 05 01
01
program
To study various operators, control statements and 06 02
02
arrays (one-dimensional and multidimensional arrays)
To study String and StringBuffer Class and Operations 08 08
03
on String.
To study about classes, objects, methods and 16 02
04
constructors
To study the concept of polymorphism using method 18 02
05
overloading and constructor overloading
To study the concept of inheritance and method 20 03
06
overriding
07 To study the concept of packages and interfaces 23 06

08 To study about exception handling mechanism 29 04


09 To study about multi threading concept 33 01
10 To study about java.io package 34 01
11 To study UML diagrams. 35 01
5 - List of equipments / instruments 36 01

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
1
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

REVISION RECORD SHEET

S R. N O . EXPERIMENT NAME OF EXPERIMENT DATE OF NO. OF


NO. REVISION PAGES
1 2 To study about data types, and arrays (one-
dimensional and multidimensional arrays)
2 4 To study about classes, objects, methods
and constructors

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
2
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

CONTROL COPY HOLDER

S R. N O EXPT. NO CONTROL COPY REVISION ISSUE DATE


NO.
1 Management representative
2 Head of the Department
3 Course Coordinator

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
3
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

GENERAL INSTRUCTIONS

1. Start computer only after obtaining permission of the concerned instructor/teacher.


2. Do not bring the bags inside laboratory.
3. Observe safety precautions during the lab hours.
4. Obtain the required instruments/ manuals & other required material from the lab
teacher & return it at the end of the practical.
5. At the end of the lab, shut-down the computers , switch off power supply and put
chairs properly.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
4
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

PRACTICAL - 1

OBJECTIVE: To set PATH environment variable and to build simple program

1. Write a program to display a simple message.

class Example {
public static void main(String args[]) {
System.out.println("This is A SIMPLE JAVA PROGRAM");
}
}

STEPS:
1. Write above code in notepad or any java editor & save it as Example.java
2. Go to command prompt
3. Go to your directory where Example.java file is stored
4. Compile the program using following command.
For Ex: C :\> javac Example.java
This command will create Example.class file at your directory.
Before applying javac command you must have to set the path where javac is
located using following command.
For ex: C :\> set path=c:\jdk1.4\bin;
5. Now execute the program using following command.
For Ex: C :\> java Example
This command will display output at prompt.
This is A SIMPLE JAVA PROGRAM

NOTE: If you want to run program outside the directory where you have stored
class file then you have to set the classpath using following command.
For Ex: C :\> set classpath=path of classfile

Exercises:

1. Write the steps to work with javac and java commands using command prompt.
2. Write a program to display two messages in separate lines.
3. Write a program to display a string with an embedded quote. For example:
Shastri said: Sachin has played a game of his Life.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
5
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

PRACTICAL - 2

OBJECTIVE: To study various operators, control statements and arrays (one-


dimensional and multidimensional arrays)

1. The following program initializes 1-D array of 4 elements & print the elements along
with size of an array.

class ArrayInitializer {
public static void main(String args[]) {
// Declare, allocate, initialize
int myarray[] = { 33, 71, -16, 45 };
// Display length
Sytem.out.println("myarray.length = " + myarray.length);
// Display elements
System.out.println(myarray[0]);
System.out.println(myarray[1]);
System.out.println(myarray[2]);
System.out.println(myarray[3]);
}
}

2. The following program initializes 2-D array & print the elements along with size of an
array.

class TwoDimensionArray {
public static void main(String args[]) {
// Declare and allocate space
int myarray[][] = new int[3][2];
// Initialize elements
myarray[0][0] = 33;
myarray[0][1] = 71;
myarray[1][0] = -16;
myarray[1][1] = 45;
myarray[2][0] = 99;
myarray[2][1] = 27;
// Display length
System.out.println("myarray.length = " + myarray.length);
// Display elements
System.out.println(myarray[0][0]);
Prepared by: Approved by: Issued by:
Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
6
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

System.out.println(myarray[0][1]);
System.out.println(myarray[1][0]);
System.out.println(myarray[1][1]);
System.out.println(myarray[2][0]);
System.out.println(myarray[2][1]);
}
}

Exercises:

1. Write a program to sort all elements of one dimensional integer array using command
line arguments.
2. Write a program to find maximum and minimum element of one dimensional integer
array.
3. Write a program to display following using multidimensional array.
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
4. Write a program for computing xy by doing repetitive multiplication. x and y are of
type integer and are to be given as command line arguments.
5. Write a program to display the elements of one dimensional array using for each loop.
6. Write a program to find the number and sum of all integers greater than 100 and less
than 200 that are divisible by 7.
7. Write a program to convert rupees to dollar. 60 rupees=1 dollar.
8. Write a program that calculate percentage marks of the student if marks of 6
subjects are given.
9. Write a program to enter two numbers and perform mathematical operations on
them.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
7
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

PRACTICAL - 3

OBJECTIVE: To study String and StringBuffer Class and Operations on String.

Strings, which are widely used in Java programming, are a sequence of characters. In the
Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings:
There are two ways to create a String in Java

1. String literal
2. Using new keyword

String literal

In java, Strings can be created like this: Assigning a String literal to a String instance:

String str1 = "Welcome";


String str2 = "Welcome";

Using New Keyword

String str1 = new String("Welcome");


String str2 = new String("Welcome");

String Methods:

Sr. No. Methods with Description

1 char charAt(int index)

Returns the character at the specified index.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
8
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

2 int compareTo(Object o)

Compares this String to another Object.

3 int compareTo(String anotherString)

Compares two strings lexicographically.

4 int compareToIgnoreCase(String str)

Compares two strings lexicographically, ignoring case differences.

5 String concat(String str)

Concatenates the specified string to the end of this string.

6 boolean contentEquals(StringBuffer sb)

Returns true if and only if this String represents the same sequence of characters
as the specified StringBuffer.

7 static String copyValueOf(char[] data)

Returns a String that represents the character sequence in the array specified.

8 static String copyValueOf(char[] data, int offset, int count)

Returns a String that represents the character sequence in the array specified.

9 boolean endsWith(String suffix)

Tests if this string ends with the specified suffix.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
9
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

10 boolean equals(Object anObject)

Compares this string to the specified object.

11 boolean equalsIgnoreCase(String anotherString)

Compares this String to another String, ignoring case considerations.

12 byte getBytes()

Encodes this String into a sequence of bytes using the platform's default charset,
storing the result into a new byte array.

13 byte[] getBytes(String charsetName

Encodes this String into a sequence of bytes using the named charset, storing
the result into a new byte array.

14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

Copies characters from this string into the destination character array.

15 int hashCode()

Returns a hash code for this string.

16 int indexOf(int ch)

Returns the index within this string of the first occurrence of the specified
character.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
10
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

17 int indexOf(int ch, int fromIndex)

Returns the index within this string of the first occurrence of the specified
character, starting the search at the specified index.

18 int indexOf(String str)

Returns the index within this string of the first occurrence of the specified
substring.

19 int indexOf(String str, int fromIndex)

Returns the index within this string of the first occurrence of the specified
substring, starting at the specified index

20 String intern()

Returns a canonical representation for the string object.

21 int lastIndexOf(int ch)

Returns the index within this string of the last occurrence of the specified
character.

22 int lastIndexOf(int ch, int fromIndex)

Returns the index within this string of the last occurrence of the specified
character, searching backward starting at the specified index.

23 int lastIndexOf(String str)

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
11
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

Returns the index within this string of the rightmost occurrence of the specified
substring.

24 int lastIndexOf(String str, int fromIndex)

Returns the index within this string of the last occurrence of the specified
substring, searching backward starting at the specified index.

25 int length()

Returns the length of this string.

26 boolean matches(String regex)

Tells whether or not this string matches the given regular expression.

27 boolean regionMatches(boolean ignoreCase, int toffset, String other, int


ooffset, int len)

Tests if two string regions are equal.

28 boolean regionMatches(int toffset, String other, int ooffset, int len)

Tests if two string regions are equal

29 String replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this
string with newChar.

30 String replaceAll(String regex, String replacement

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
12
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

Replaces each substring of this string that matches the given regular expression
with the given replacement.

31 String replaceFirst(String regex, String replacement)

Replaces the first substring of this string that matches the given regular
expression with the given replacement.

32 String[] split(String regex)

Splits this string around matches of the given regular expression.

33 String[] split(String regex, int limit)

Splits this string around matches of the given regular expression.

34 boolean startsWith(String prefix)

Tests if this string starts with the specified prefix.

35 boolean startsWith(String prefix, int toffset)

Tests if this string starts with the specified prefix beginning a specified index.

36 CharSequence subSequence(int beginIndex, int endIndex)

Returns a new character sequence that is a subsequence of this sequence.

37 String substring(int beginIndex)

Returns a new string that is a substring of this string.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
13
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

38 String substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string.

39 char[] toCharArray()

Converts this string to a new character array.

40 String toLowerCase()

Converts all of the characters in this String to lower case using the rules of the
default locale.

41 String toLowerCase(Locale locale)

Converts all of the characters in this String to lower case using the rules of the
given Locale.

42 String toString()

This object (which is already a string!) is itself returned.

43 String toUpperCase()

Converts all of the characters in this String to upper case using the rules of the
default locale.

44 String toUpperCase(Locale locale)

Converts all of the characters in this String to upper case using the rules of the
given Locale.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
14
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

45 String trim()

Returns a copy of the string, with leading and trailing whitespace omitted.

46 static String valueOf(primitive data type x)

Returns the string representation of the passed data type argument.

Exercises:

1. Write a program to find length of string and print second half of the string.
2. Write a program to accept a line and check how many consonants and vowels are
there in line.
3. Write a program to count the number of words that start with capital letters.
4. Write a program to find that given number or string is palindrome or not.
5. Write a program to sort the array of Strings using command line argument.
6. Given a string, return a new string where the first and last chars have been exchanged.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
15
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

PRACTICAL - 4

OBJECTIVE: To study about classes, objects, methods and constructors

1. The following program demonstrates use of a method.

class num{
int x,y;
int add(int x, int y)
{
return (x+y);
}
}
class p {
public static void main(String args[]) {
num n=new num();
n.x=2;
n.y=3;
int z=n.add(n.x,n.y);
System.out.println("x = " + n.x);
System.out.println("y = " + n.y);
System.out.println("z = " + z);
}
}

2. The following example declares a simple class name point3D, instance of this class
encapsulates 3-co ordinates of a point in space. This class has 3 double instance variable
name x, y & z.

class Point3D {
double x;
double y;
double z;
}
class Point3DExample {
public static void main(String args[]) {
Point3D p = new Point3D();
p.x = 1.1;
p.y = 3.4;
p.z = -2.8;

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
16
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

System.out.println("p.x = " + p.x);


System.out.println("p.y = " + p.y);
System.out.println("p.z = " + p.z);
}
}

Exercises:
1. Create a stack class with instance variables tos, and item of type integer and integer
array respectively. Also define two methods push and pop that insert elements in the
stack and remove the elements from the stack respectively. Write a program to insert
10 items in stack and remove it.
2. Write a program that creates 50 Student objects and saves these in an array. Assign
an ID number to each student starting from 1 as it is created. After all student objects
have been created, display their IDs in sequence.
3. Define the Rectangle class that contains Two double fields x and y that specify the
center of the rectangle, the data field width and height ; A no-arg constructor that
creates the default rectangle with (0,0) for (x,y) and 1 for both width and height; A
parameterized constructor creates a rectangle with the specified x, y, height and
width; A method getArea() that returns the area of the rectangle; A method
getPerimeter() that returns the perimeter of the rectangle. Write a program that
creates two rectangle objects. One with default values and other with user specified
values. Test all the methods of the class for both the objects.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
17
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

PRACTICAL - 5

OBJECTIVE: To study the concept of polymorphism using method overloading and


constructor overloading

1. The following application demonstrates an example of method overloading.

//Method overloading
class overload
{
void test()
{
System.out.println(No Parameters);
}
void test(int a)
{
System.out.println(a: + a);
}

}
class overloaddemo
{
public static void main(String a[])
{
overload ob = new overload();
ob.test();
ob.test(20);
}
}

2. The following application demonstrates an example of constructor overloading.

//Constructor overloading

class Box
{
double width, height, depth;

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
18
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

Box()
{
width=height=depth= -1;
}
Box(double l)
{
width=height=depth= l;
}
double vol()
{
return width * height * depth;
}
}
class BoxDemo
{
public static void main(String a[])
{
Box b1 = new Box();
Box b2 = new Box(7);
double ans;
ans=b1.vol();
System.out.println(Volume of b1 is: + ans);
ans=b2.vol();
System.out.println(Volume of b2 is: + ans);

}
}

Exercises:
1. Create a circle class with 2 constructors. The first form takes a double value that
represents the radius of a circle; this constructor assumes that circle is centered at the
origin. The second form takes 3 double values, the first 2 arguments define the
coordinates of the center & third argument defines the radius. Also declare one
member function which calculates an area of a circle. Write a program to demonstrate
the same.
2. Create a class named absolute. Define the method named findAbs() to find absolute
value for integer, float and double. Pass the appropriate type of argument to the
method to overload it. Write a program to invoke this overloaded method.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
19
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

PRACTICAL 6

OBJECTIVE: To study the concept of inheritance and method overriding

1. The following application demonstrates a class inheritance hierarchy.

class W {
float f;
}
class X extends W {
StringBuffer sb;
}
class Y extends X {
String s;
}
class Z extends Y {
Integer i;
}
class Wxyz {
public static void main(String args[]) {
Z z = new Z();
z.f = 4.567f;
z.sb = new StringBuffer("abcde");
z.s = "Teach Yourself Java";
z.i = new Integer(41);
System.out.println("z.f = " + z.f);
System.out.println("z.sb = " + z.sb);
System.out.println("z.s = " + z.s);
System.out.println("z.i = " + z.i);
}
}

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
20
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

2. This example illustrates method overriding.

class A1 {
void hello() {
System.out.println("Hello from A1");
}
}

class B1 extends A1 {
void hello() {
System.out.println("Hello from B1");
}
}
class C1 extends B1 {
void hello() {
System.out.println("Hello from C1");
}
}
class MethodOverriding1 {
public static void main(String args[]) {
C1 obj = new C1();
obj.hello();
}
}

Exercises:

1. Three classes namely A, B, and C respectively forms a multilevel inheritance hierarchy.


Each class declares a method named display() with the same type signature which
displays name of the class. Write a program to demonstrate the same by creating the
object of each class.
2. Rewrite the above program by only creating the object of last class in inheritance
hierarchy to get the same output.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
21
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

3. Three classes namely A, B, and C declare an instance variable named a, b, and c of type
int respectively. These variables are initialized in its respective constructor. Each
constructor also displays a message to indicate that it has started execution. The
main() method begins by instantiating class C. The instance variables for the object
are then displayed. Write a program to demonstrate the same.
4. Rewrite the above program by using super keyword to explicitly invoke its immediate
super classs constructor. Also use this keyword.
5. Write a program that creates an Integer object. Then obtain the associated Class
object. Invoke the getSuperclass() method to get the Class object for the super class
of Integer. Invoke the getName() method to obtain the name of the class and super
class and display them.
6. The abstract class Fruit has four sub classes named Apple, Banana, Orange and
Strawberry. Write an application that demonstrates how to establish this class
hierarchy. Declare one instance variable of type String that indicates the color of a
fruit. Create instances of these objects and display output in the form super class
name: sub class name: color with and without overriding toString() method of Object
class.
7. The abstract class Airplane has three subclasses named B747, B757, and B767 and an
abstract method getPassengers() that is implemented by each subclass that returns
different number of passengers. Declare one instance variable of type String that
indicates unique serial number of an airplane. Write an application that declares this
class hierarchy. Instantiate 5 types of airplanes and display them in order of type, serial
number, and capacity.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
22
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

PRACTICAL 7

OBJECTIVE: To study the concept of packages and interfaces

1. This program illustrates how to declare interface & implement these in various classes.

interface Shape2D {
double getArea();
}
interface Shape3D {
double getVolume();
}
class Point3D {
double x, y, z;
Point3D(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
}
abstract class Shape {
abstract void display();
}
class Circle extends Shape
implements Shape2D {
Point3D center, p; // p is any point on the circumference
Circle(Point3D center, Point3D p) {
this.center = center;
this.p = p;
}
public void display() {
System.out.println("Circle");
}

public double getArea() {


double dx = center.x - p.x;
Prepared by: Approved by: Issued by:
Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
23
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

double dy = center.y - p.y;


double d = dx * dx + dy * dy;
double radius = Math.sqrt(d);
return Math.PI * radius * radius;
}
}
class Sphere extends Shape
implements Shape3D {
Point3D center;
double radius;
Sphere(Point3D center, double radius) {
this.center = center;
this.radius = radius;
}
public void display() {
System.out.println("Sphere");
}
public double getVolume() {
return 4 * Math.PI * radius * radius * radius / 3;
}
}
class Shapes {
public static void main(String args[]) {
Circle c = new Circle(new Point3D(0, 0, 0), new Point3D(1, 0, 0));
c.display();
System.out.println(c.getArea());
Sphere s = new Sphere(new Point3D(0, 0, 0), 1);
s.display();
System.out.println(s.getVolume());
}
}

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
24
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

Exercises:

1. Write a program that creates one interface LO declares lightOff & lightOn methods.
Class SO is extended by CONE & CUBE. Class LC extends CONE & implements LO. Class
LCB extends CUBE & implements LO. Instantiate the LC & LCB classes. Use interface
reference to refer to those objects. Invoke the method of the LO interface via the
interface reference.
2. Write a program that illustrates interface inheritance. Interface K1 declares method
mK() and a variable intK that is initialized to 1. Interface K2 extends K1 & declares mK().
Interface K3 extends K2 & declares mK(). The return type of mK() is void in all
interfaces. Class U implements K3. Its version of mK() displays the value of intK.
Instantiate U & invoke its method.
3. The Transport interface declares a deliver() method. The abstract class Animal is the
super class of the Tiger, Camel, Deer, and Donkey classes. The Transport interface is
implemented by the Camel and Donkey classes. Write a demo program that initializes
an array of four Animal objects. If the object implements the Transport interface, the
deliver() method is invoked.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
25
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

2. The following program illustrates how the classes defined in two separate source files
can be grouped in to one package named P.

// The source code for p\PackageDemo.java is shown in the following listing. An object of class
A is created and method a1 is called.

package p;
class PackageDemo {
public static void main(String args[]) {
A a = new A();
a.a1();
}
}

// The source code for p\A.java is shown in the following listing.

package p;
class A {
void a1() {
System.out.println("a1"); }}

How to run & compile?


1. To builD this package you must change to the parent directory of p & issues the following
command.
javac p\*.java
The .class files created by this command are placed in the subdirectory
2. To execute this application remain in the parent directory of p & issue following command.
java p.PackageDemo

2. The following example illustrates the accessibility of public, protected & private variables
among different packages.

//The source code for e\E.java is shown in the following listing.

package e;
public class E {
Prepared by: Approved by: Issued by:
Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
26
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

public int e1 = 11;


protected int e2 = 22;
private int e3 = 33;
}

//The source code for f\F.java is shown in the following listing.

package f;
import e.*;
public class F extends E {
public void display() {
// OK to access public member
System.out.println(e1);
// OK to accesss protected member
// in our superclass
System.out.println(e2);
// Not OK to acces private member
// System.out.println(e3);
}
}

//The source code for h\ProtectedDemo.java is shown in the following listing. This is the
application that uses the class f.F

package h;
import f.F;
class ProtectedDemo {
public static void main(String args[]) {
// Test subclass in a different package
F f = new F();
f.display();
}
}

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
27
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

Exercises:
1. Write a program that demonstrates use of packages & import statements. (simple
addition program)
2. The abstract class Tent has concrete subclasses named TentA, TentB, TentC & TentD.
The WaterProof interface defines no constants & declares no methods. It is
implemented by TentB & TentD. Define all of the classes & implement the interfaces
as specified. Create one instance of each class then display all WaterProof tents. Place
this code in a package named tents.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
28
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

PRACTICAL 8

OBJECTIVE: To study about exception handling mechanism

1. The following program shows the default exception handling mechanism used by JAVA.

class DivideByZero {
public static void main(String args[]) {
a();
}
static void a() {
b();
}
static void b() {
c();
}
static void c() {
d();
}
static void d() {
int i = 1;
int j = 0;
System.out.println(i/j);
}
}

2. The JAVA language allows you to handle exception that occurs during execution of a
program. This is shown in following example.

class Divider {
public static void main(String args[]) {
try {
System.out.println("Before Division");
int i = 1;
int j = 0;
System.out.println(i/j);
System.out.println("After Division");
}
catch(ArithmeticException e) {
System.out.println("ArithmeticException");
Prepared by: Approved by: Issued by:
Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
29
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

}
finally {
System.out.println("Finally block");
}
}
}

3. The following program illustrates how a catch block may throw an exception.

class ThrowDemo {
public static void main(String args[]) {
try {
System.out.println("Before a");
a();
System.out.println("After a");
}
catch(ArithmeticException e) {
System.out.println("main: " + e);
}
finally {
System.out.println("main: finally");
}
}
public static void a() {
try {
System.out.println("Before b");
b();
System.out.println("After b");
}
catch(ArithmeticException e) {
System.out.println("a: " + e);
}
finally {
System.out.println("a: finally");
}
}
public static void b() {
try {
int i = 1;
int j = 0;
System.out.println("Before division");
Prepared by: Approved by: Issued by:
Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
30
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

System.out.println(i/j);
System.out.println("After division");
}
catch(ArithmeticException e) {
System.out.println("b: " + e);
throw e;
}
finally {
System.out.println("b: finally");
}
}
}

4. The example illustrates how the throws clause is used. (throws will allow the caller of the
function to handle the exception thrown by the called function).

class ThrowsDemo {
public static void main(String args[]) {
a();
}
public static void a() {
try {
b();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void b() throws ClassNotFoundException {
c();
}
public static void c() throws ClassNotFoundException {
Class cls = Class.forName("java.lang.Integer");
System.out.println(cls.getName());
System.out.println(cls.isInterface());
}
}

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
31
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

Exercises:

1. Write a program that reads two arguments from the prompt & perform the division
operation on them. Write the appropriate exception handling code.
2. Write a program that accepts the fully qualified name of a class as its argument.
Compute & display how many super classes exist for that class. (HINT. Use the
forName() and getSuperClass() methods of class.) If a ClassNotFoundException
occurs, catch it & provide an error for the user.
3. A method named average() has one argument that is an array of strings. It converts
these to double values and returns their average. The method generates a
NullPointerException if an array element is null or a NumberFormatException if an
element is incorrectly formatted. Write a program that illustrates how to declare and
use this method. Include a throws clause in the method declaration to indicate that
these problems can occur.
4. A method named add() accepts an array of strings as its argument. It converts these
to double values and returns their sum. The method generates a
NumberFormatException if an element is incorrectly formatted. It can also create and
throw a custom exception, RangeException, if an element is less than 0 or greater
than 1. Write a program that illustrates how to declare and use this method.
5. Write a program that generates a Custom Exception if any of its command line
arguments are negative.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
32
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

PRACTICAL 9

OBJECTIVE: To study about multi threading concept

Thread can be created using Extending Thread class (Super Class) and by implementing
Runnable interface.

We cant make our own runnable interface because of in Thread class constructor we having
Runnable reference.

To create thread application, Runnable interface is preferable than extending Thread class
because of any class can extend only one class.

Exercises:

1. Write a program to create thread which displays Hello World message by extending
Thread class.
2. Write a program to create thread which displays Hello World message by
implementing Runnable interface.
3. Write a program to perform addition of 1 to 100 numbers using 4 threads.
4. Write a program to increment the value of a variable by one and display it after one
second using thread.

Synchronization Concept
We can synchronize any method and can synchronize current object to get consistency in
record.

Exercises:

1 Write a program to create one producer thread and one consumer thread. Producer
produces 10 items for consumer. (Use single memory buffer to store items produced by
producer).
2 Write a program to create one producer and two consumers. Producer produces 10 items
for consumers. (Use queue to store items produced by producer).
3 Write a program to create one producer and two consumers. Producer produces item for
specific consumer. (Use different methods of HashTable class which resides in utility
package).

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
33
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

PRACTICAL 10

OBJECTIVE: To study about java.io package.

Exercises:

1. Create a class which ask the user to enter a sentence, and it should display count of each
vowel type in the sentence. The program should continue till user enters a word
quit. Display the total count of each vowel for all sentences.
2. Create a class called Student. Write a student manager program to manipulate the
student information from files by using FileInputStream and FileOutputStream
3. Refine the student manager program to manipulate the student information from files
by using the BufferedReader and BufferedWriter
4. Refine the student manager program to manipulate the student information from files
by using the DataInputStream and DataOutputStream. Assume suitable data
5. Write a program to read information from one text file and write to another text file. Use
separate thread to read information from file and write information to file. Name of the
files is taken from the user.
6. Write a program to count number of files and sub-directories in a specified directory. Take
name of directory from user.
7. Write a program to display list of only .class files from given directory by user. (Use
FilenameFilter interface to filter list of files)

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
34
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

PRACTICAL 11

OBJECTIVE: To study UML diagrams.

Exercises:

1. Prepare a class diagram for given group of classes using multiplicity, generalization,
association concepts. And add at least 5-7 attributes and 3-5 operations for
particular class Page, Shape, Point, Line, Arc, Ellipse, Rectangle, Circle
2. Prepare a class diagram for given group of classes using multiplicity, generalization,
association concepts. And add at least 5-7 attributes and 3-5 operations for
particular class. City, Airport, Airline, Pilot, Flight, Plane, Seat, Passenger
3. Categorize the following relationships into generalization, aggregation or association.
[A] A country has a capital city
[B] A dining philosopher uses a fork
[C] A file is an ordinary file or a directory file
[D] Files contains records
[E] A polygon is composed of an ordered set of points
[F] A drawing object is text, a geometrical object, or a group
[G] A person uses a computer language on a object
[H] Modems and keyboards are input/output devices
[I] Classes may have several attributes
[J] A person plays for a team in a certain year
[K] A route connects two cities
[L] A student takes a course from a professor
4. Prepare a state diagram for an interactive diagram editor for selecting and dragging
objects
5. Prepare a use case diagram and sequence diagram for a computer email system
6. Prepare an activity diagram for computing a restaurant bill, there should be charge
for each delivered item. The total amount should be subject to tax and service
charge of 18% for group of six and more. For smaller groups there should be a blank
entry. Any coupons or gift certificates submitted by the customer should be
subtracted
7. Prepare a sequence diagram for issuing a book in the library management system.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
35
ADIT/IT/LM/2150704/00
Issue Date:20.08.15
2150704 Object Oriented Revision Date:
Programming with JAVA

List of Equipments / Instruments

1. 25 computers with general configuration and also connected with LAN.


2. JDK1.4 software, Tomcat 6.0 (Web Server).
3. White board with marker pen and duster.

Prepared by: Approved by: Issued by:


Ms Hetal Shah Head IT Dr Anant Kulkarni
Date: 20.08.15 Date: 20.08.15 Date: 20.08.15
36

Vous aimerez peut-être aussi