You are on page 1of 45

SUMAN EDUCATIONAL TRUST’S

DILKAP RESEARCH INSTITUTE OF ENGINEERING AND


MANAGEMENT STUDIES
Village Mamdapur, Post Neral, Taluka Karjat, Dist Raigad – 410101

Department of Computer Engineering

CSL304 – OOPM (Java) Lab

REFERENCE LAB MANUAL


S.E. (CMPN) /SEM III

ACADEMIC YEAR: 2017-2018


Sr. Topic CO
No. Mapping
1. Program on Various ways to accept data through keyboard and
unsigned right shift operator
Input through Command Line Argument
Demonstrate the concept of arithmetic operators.
List the subjects offered to you in sem III
Input through scanner Class
Print the Fibonacci series upto the nth term taking the value of n from the
user.
WAP to reverse the four digit no.
Unsigned right shift operator
Demonstrate the working of right shift operator.

2. Program On Branching ,Looping, Labelled break and continue


1. Branching
WAP to print the roots of quadractic equation.
WAP to check if the entered no. is a prime no. or not.
WAJP to demonstrate the working of types of operators(Bitwise, Logical and
relational) using switch case.
Looping
WAP to print the patterns.
WAP to print all the three digit armstrong nos.
Labelled break & continue
WAP to demonstrate the working of labelled break and continue.

3. Program on Arrays
1. 1D Arrays
To search an given element in the Array.
To merge two arrays.
2D arrays
To check if the entered matrix is symmetric or not.
To perform Matrix Multiplication
To find out trace and Norm of a particular Matrix.

4. Program on Strings & String buffer


Reverse the string and decide whether it is palindrome or not
Capitalize the first letter of each word
Count the frequency of particular letter and replace that particular letter by #
Count the no. of uppercase, lowercase, blank spaces, digits, special characters from
string
5. Program on Vector.
WAJP to add n Strings in a vector array. Input new String and check
whether it is present in the vector . If it is present delete it otherwise add
it to the vector
WAJP to test whether the given element is present in the vector or not.
WAJP to find the frquency of an element in given vector array
6. Program to create class with members and methods, accept and display
details for single object.
Ddefine a class to represent a bank account. Include the following
members: name of the depositor, account number, type of account
balance amount in the account
Methods:
1.to assign initial values
2.to deposit an amount
3.to withdraw an amount after checking balance.
4.to display the name & balance

7. Demonstrate the concept of constructor and constructor overloading


8. Program on method overloading
Consider a class Figure and overload the function called area() to diplay
the area of figures like square,triangle, Rectangle and circle.
9. Program on passing object as argument and returning object
10. Program on creating user defined package
11. Program on Single and Multilevel inheritance(Use super Keyword)
12. Program on Abstract classes
13. Program on interfaces
WAP to Create an interface Area & implement the same in different classes
Rectangle ,circle ,triangle
14. Program on Dynamic method dispatch using base class and interface
reference
15. Exception Handling
Program to demonstrate try, catch,throw,throws and finally
WAJP to demonstrate the concept of multiple catch statements
WAJP to calculate the Result. It should consist of name , seatno. date,
center no. and marks of three semester. Create a user defined Exception
class MarksOutOfBoundsException, If enetred marks of nay subject is
greater than 100 or less than 0 then program should create a user
defined Exception of type MarksOutOfBoundsException and must have
a provision to handle it.
17. Program on Multithreading
WAJP to print the table of 5,7,13 using Multithreading(Use thread class)
WAJP to print first 20 prime nos. and 15 fibonacci terms and also print
the total time taken by each threadfor the execution
18. Program on concept of synchronization
19. Program on Applet
1. To demonstrate Graphics, Font and Color class
House
Traffic Signal
Joker face
Passing Parameters to applets

20. Program to create GUI Applications


1. Create Registration form using AWT.
2. Take a Login and Password from the user and display it on third
Text field which appears only on clickng OK button and clear both
the text Fields on clicking RESET button perrform same using AWT.

21. Mini Project based on concept of the syllabus.


Experiment:1
AIM :
Program on Various ways to accept data through keyboard and unsigned right shift
operator
Input through Command Line Argument
To demonstrate the concept of arithmetic operators.
List the subjects offered to you in sem III
Input through scanner Class
Print the Fibonacci series upto the nth term taking the value of n from the user.
WAP to reverse the four digit no.
Unsigned right shift operator
Demonstrate the working of right shift operator.

OBJECTIVE : To make students understand how to take input from the user and explain the difference
in working of right shift operator and unsigned right shift operator.
DESCRIPTION : Students should write about the following along with examples to support the
theory
Command-Line Arguments
Scanner class
Bitwise operators in java and C
CONCLUSION: Students are expected to List the error they are facing along with their solution
REFERENCES :
Experiment:2
AIM : Program On Branching ,Looping, Labelled break and continue
Branching
WAP to print the roots of quadractic equation.
WAP to check if the entered no. is a prime no. or not.
WAJP to demonstrate the working of types of operators(Bitwise, Logical and relational)
using switch case.
Looping
WAP to print the patterns.
WAP to print all the three digit armstrong nos.
Labelled break & continue
WAP to demonstrate the working of labelled break and continue.

OBJECTIVE : To make Students understand the working of different decision Making and
Looping Constructs in Java. Also introduce them to the concept of Labelled break and continue.

Description :

Give syntax and explaination for if-else, switch,for while and do_while loop along with example.
Give description for Labelled break and continue with example.

CONCLUSION: Students are expected to List the error they are facing along with their solution
REFERENCES :
Experiment:3
AIM : Program on Arrays
1D Arrays
To search an given element in the Array.
To merge two arrays.
2D arrays
To check if the entered matrix is symmetric or not.
To perform Matrix Multiplication
To find out trace and Norm of a particular Matrix.

OBJECTIVE : To make students understand the basics of Arrays in Java and their major difference with
Arrays in C

Description :

Write the following about both 1D and 2D arrays :


What are arrays in General.
Syntax of array declaration, creation and initialization
Static and dynamic initialization methods
Default initialisation
Write about arraycopy method(refer book of authorThampi) and Length Atribute
Difference between arrays in c and java

CONCLUSION: Mention about ArrayIndexOutOfBoundsException.


REFERENCES :

Experiment:4

AIM : Program on Strings & String buffer


Reverse the string and decide whether it is palindrome or not
Capitalize the first letter of each word
Count the frequency of particular letter and replace that particular letter by #
Count the no. of uppercase, lowercase, blank spaces, digits, special characters from string

OBJECTIVE : To make students understand the significance of String Handling in Java.

DESCRIPTION :
What are strings in Java?
Give the List Of String Constructors.
Give the List of String Functions category Wise with Simple description?
Strings in Java are immutable. Explain
Limitations of String Class.
StringBuffer in Java.
List of Constructors and Functions
CONCLUSION: Errors and exception faced during Execution
REFERENCES :

Experiment:5

Program on Vector.
WAJP to add n Strings in a vector array. Input new String and check whether it is present
in the vector . If it is present delete it otherwise add it to the vector
WAJP to test whether the given element is present in the vector or not.
WAJP to find the frquency of an element in given vector array
OBJECTIVE :To give Strudents a brief introduction of Vector(A Dynamic array) and wrapper
class in java.

DESCRIPTION : Write about


Vector class in java
Wrapper classes in java.
List the important constructors and functions of Vector and wrapper class in java
Limitations of Arrays.
Need of Vector class
Limitation of Vector class.
CONCLUSION: Errors and exception faced during Execution
REFERENCES :
Experiment:6

Aim:Program to create class with members and methods, accept and display details for
single object.define a class to represent a bank account. Include the following
members: name of the depositor, account number, type of account
balance amount in the account
Methods:
1.to assign initial values
2.to deposit an amount
3.to withdraw an amount after checking balance.
4.to display the name & balance

OBJECTIVE : To make students understand the basics of class,methods and how to retrieve data in Java

Description :

What is class and object in java.


How to create object
How to define the structure of java program
How to define method and how to access method of a class

CONCLUSION: Students are expected to List the error they are facing along with their solution

REFERENCES :
www.learnjavaonline.org/
www.javaworld.com
www.w3schools.com
www.codejava.net/books/4-best-free-java-e-books-for-beginners

Books:

For Beginner:

● Head First Java, 2nd Edition


● Thinking in Java (4th Edition)
● Think Java
● Introduction to Java by Sedgewick
● Java in a Nutshell
● Core Java Volume I--Fundamentals (9th Edition) (Core Series): Cay S. Horstmann
● Java How To Program (late objects) by Paul Deitel, Harvey Deitel
Intermediate:

● Effective Java (2nd Edition): Joshua Bloch


● Java Performance: Charlie Hunt, Binu John
● Head First Servlets and JSP
● SCJP by Kathy and Sierra
● Java - The Complete Reference by Herbert Schildt.
● Java Concurrency in Practice
● Java Performance
● The Java Programming Language, 4th Edition

Advanced:

● Java Puzzlers : Traps, Pitfalls, And Corner Cases


Experiment:7
Aim:Demonstrate the concept of constructor and constructor overloading.

OBJECTIVE : To introduce the concept of Constructors to the students and Polymorphism


principle of oops
Description :
what are constructors?
Types of Constructor
their resemblence to functions
What is constructor overloading.

CONCLUSION: Students are expected to analyse output of the program and check the program for
different inputs.

REFERENCES :

Experiment 8

Program on method overloading


Consider a class Figure and overload the function called area() to display the area of
figures like square,triangle, Rectangle and circle.

OBJECTIVE : To make students understand the basics of method overloading in java.

Description
What do you mean by Method overloading.
How overloading or functions are identified to be called at runtime.

CONCLUSION: Students are expected to List the error they are facing along with their solution

REFERENCES :
https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Java complete rwference 7th edition by Herbert Schildt
Programming with JAVA by Balgurusamy
Experiment 9

Program on passing object as argument and returning object

Description:

When we pass a primitive type to a method, it is passed by value. But when we pass an object to a

method, the situation changes dramatically, because objects are passed by what is effectively

call-by-reference. Java does this interesting thing that’s sort of a hybrid between pass-by-value and

pass-by-reference. Basically, a parameter cannot be changed by the function, but the function can ask the

parameter to change itself via calling some method within it.

● While creating a variable of a class type, we only create a reference to an object. Thus, when we pass

this reference to a method, the parameter that receives it will refer to the same object as that referred

to by the argument.

● This effectively means that objects act as if they are passed to methods by use of call-by-reference.
● Changes to the object inside the method do reflect in the object used as an argument.

CONCLUSION: Students are expected to List the error they are facing along with their solution

REFERENCES :
www.learnjavaonline.org/
www.javaworld.com
www.w3schools.com
www.codejava.net/books/4-best-free-java-e-books-for-beginners
Experiment 10

OBJECTIVE : Create user defined package and import them In your program.

DESCRIPTION:
Packages are nothing more than the way we organize files into different directories according to their
functionality, usability as well as category they should belong to. Another way of achieving
reusability in java Grouping is done according to functionality.Packages act as “containers” for
classes.
Defining a Package.
List out different built in packages in java with their description
Finding Packages and CLASSPATH
As just explained, packages are mirrored by directories. This raises an important question: How does the
Java run-time system know where to look for packages that you create? The answer has three parts. First,
by default, the Java run-time system uses the current working directory as its starting point. Thus, if your
package is in a subdirectory of the current directory, it will be found. Second, you can specify a directory
path or paths by setting the CLASSPATH environmental variable. Third, you can use the -classpath
option with java and javac to specify the path to your classes. For example, consider the following
package specification:
package MyPack
In order for a program to find MyPack, one of three things must be true. Either the program can be
executed from a directory immediately above MyPack, or the CLASSPATH must be set to include the
path to MyPack, or the -classpath option must specify the path to MyPack when the program is run via
java. When the second two options are used, the class path must not include MyPack, itself. It must
simply specify the path to MyPack. For example, in a Windows environment, if the path to MyPack is
C:\MyPrograms\Java\MyPack
Then the class path to MyPack is
C:\MyPrograms\Java
The easiest way to try the examples shown in this book is to simply create the package directories below
your current development directory, put the .class files into the appropriate directories, and then execute
the programs from the development directory.
CONCLUSION: Students need to know how packages are defined.

REFERENCES:
Java complete rwference 7th edition by Herbert Schildt
Programming with JAVA by Balgurusamy
AIM : WAP to implement Inheritance

OBJECTIVE : To make students understand OOP concept - Inheritance in Java.

DESCRIPTION :
In the Java language, classes can be derived from other classes, thereby inheriting fields and
methods from those classes. A class that is derived from another class is called a subclass (also a derived
class, extended class, or child class). The class from which the subclass is derived is called as superclass
(also a base class or a parent class).
Excepting Object, which has no superclass, every class has one and only one direct superclass
(single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of
Object. Classes can be derived from classes that are derived from classes that are derived from classes,
and so on, and ultimately derived from the topmost class, Object. Such a class is said to be descended
from all the classes in the inheritance chain stretching back to Object.
A subclass inherits all the members (fields, methods, and nested classes) from its superclass.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the
superclass can be invoked from the subclass.

Figure 5.1 : Types of Inheritance

The Java Platform Class Hierarchy


The Object class, defined in the java.lang package, defines and implements behavior common to
all classes—including the ones that you write. In the Java platform, many classes derive directly from
Object, other classes derive from some of those classes, and so on, forming a hierarchy of classes.
Figure 5.2 : All Classes in the Java Platform are Descendants of Object

At the top of the hierarchy, Object is the most general of all classes. Classes near the bottom of
the hierarchy provide more specialized behavior.

An Example of Inheritance
Here is the sample code for a possible implementation of a Bicycle class that was presented in the Classes
and Objects lesson:
public class Bicycle {
// the Bicycle class has three fields
public int cadence;
public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has four methods
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}

A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:
public class MountainBike extends Bicycle {
// the MountainBike subclass adds one field
public int seatHeight;
// the MountainBike subclass has one constructor
public MountainBike(int startHeight,
int startCadence,
int startSpeed,
int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
// the MountainBike subclass adds one method
public void setHeight(int newValue) {
seatHeight = newValue;
}
}

MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a
method to set it. Except for the constructor, it is as if you had written a new MountainBike class entirely
from scratch, with four fields and five methods. However, you didn't have to do all the work. This would
be especially valuable if the methods in the Bicycle class were complex and had taken substantial time to
debug.

What You Can Do in a Subclass


A subclass inherits all of the public and protected members of its parent, no matter what package
the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private
members of the parent. You can use the inherited members as is, replace them, hide them, or supplement
them with new members:
● The inherited fields can be used directly, just like any other fields.
● You can declare a field in the subclass with the same name as the one in the superclass, thus
hiding it (not recommended).
● You can declare new fields in the subclass that are not in the superclass.
● The inherited methods can be used directly as they are.
● You can write a new instance method in the subclass that has the same signature as the one in the
superclass, thus overriding it.
● You can write a new static method in the subclass that has the same signature as the one in the
superclass, thus hiding it.
● You can declare new methods in the subclass that are not in the superclass.
● You can write a subclass constructor that invokes the constructor of the superclass, either
implicitly or by using the keyword super.

Private Members in a Superclass


A subclass does not inherit the private members of its parent class. However, if the superclass has
public or protected methods for accessing its private fields, these can also be used by the subclass. A
nested class has access to all the private members of its enclosing class—both fields and methods.
Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private
members of the superclass.

Casting Objects
We have seen that an object is of the data type of the class from which it was instantiated. For
example, if we write
public MountainBike myBike = new MountainBike();

then myBike is of type MountainBike. MountainBike is descended from Bicycle and Object.
Therefore, a MountainBike is a Bicycle and is also an Object, and it can be used wherever Bicycle or
Object objects are called for. The reverse is not necessarily true: a Bicycle may be a MountainBike,
but it isn't necessarily. Similarly, an Object may be a Bicycle or a MountainBike, but it isn't
necessarily.

Casting shows the use of an object of one type in place of another type, among the objects
permitted by inheritance and implementations. For example, if we write
Object obj = new MountainBike();
then obj is both an Object and a MountainBike (until such time as obj is assigned another object that is
not a MountainBike). This is called implicit casting. If, on the other hand, we write
MountainBike myBike = obj;

we would get a compile-time error because obj is not known to the compiler to be a MountainBike.
However, we can tell the compiler that we promise to assign a MountainBike to obj byexplicit casting:
MountainBike myBike = (MountainBike)obj;

This cast inserts a runtime check that obj is assigned a MountainBike so that the compiler can safely
assume that obj is a MountainBike. If obj is not a MountainBike at runtime, an exception will be thrown.

REFERENCES : https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
CONCLUSION: Thus we studied to use inheritance
Experiment: 8
AIM : Working of an Array
1. WAP to implement Binary Search.
2. WAP to implement Bubble Sort.

3. WAP to implement matrix multiplication

OBJECTIVE : To impart within the student the knowledge of working with arrays and
its pros and cons while working with arrays and loops.

DESCRIPTION: An array is a collection of variables of the same type, referred to by a common name.
In Java, arrays can have one or more dimensions, although the one-dimensional array is the most
common. Arrays are used for a variety of purposes because they offer a convenient means of grouping
together related variables. For example, you might use an array to hold a record of the daily high
temperature for a month, a list of stock price averages, or a list of your collection of programming books.
The principal advantage of an array is that it organizes data in such a way that it can be easily
manipulated. Also, arrays organize data in such a way that it can be easily sorted. Arrays in java have one
special attribute: they are implemented as objects. By implementing arrays as objects, several important
advantages are gained, not the least of which is that unused arrays can be garbage collected.

One-DimensionalArrays:

A one-dimensional array is a list of related variables. Such lists are common in programming. To
declare a one-dimensional array, you will use this general form:

type array-name[ ] = new type[size];

Here, type declares the base type of the array. The base type determines the data type of each element
contained in the array. The number of elements that the array will hold is determined by size. Since arrays
are implemented as objects, the creation of an array is a two-step process. First, you declare an array
reference variable. Second, you allocate memory for the array, assigning a reference to that memory to the
array variable. Thus, arrays in Java are dynamically allocated using the new operator.The following
creates an int array of 10 elements and links it to an array reference variable named sample.
int sample[] = new int[10];

This declaration works just like an object declaration. The sample variable holds a reference to the
memory allocated by new. This memory is large enough to hold 10 elements of type int. As with objects,
it is possible to break the preceding declaration in two. For example: int sample[];

sample = new int[10];

In this case, when sample is first created, it is null, because it refers to no physical object. It is only after
the second statement executes that sample is linked with an array. An individual element within an array
is accessed by use of an index. An index describes the position of an element within an array. In Java, all
arrays have zero as the index of their first element.

MultidimensionalArrays:

Although the one-dimensional array is the most commonly used array in programming, multidimensional
arrays (arrays of two or more dimensions) are certainly not rare. In Java, a multidimensional array is an
array of arrays.
Two-Dimensional Arrays

The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array
is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array table of size
10, 20 you would write

int table[][] = new int[10][20];

In the case of multi-dimensional arrays, you must use an index for each dimension to access an element.
The first index is the row and the second index is the column.
CONCLUSION: Thus we studied Overloading.
REFERENCES:
http://www.tutorialspoint.com/java/java_arrays.htm
Java complete rwference 7th edition by Herbert Schildt
Programming with JAVA by Balgurusamy
SAMPLE CODE:

// Program to Search an element from given set of elements.


import java.io.*;
class Search
{
public static void main(String[] args)throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader stdin=new BufferedReader(isr);
int i,n,key;
System.out.println("enter the no of elements");
n=Integer.parseInt(stdin.readLine()); int
x[]=new int[n]; System.out.println("enter
the elements"); for(i=0;i<n;i++)
x[i]=Integer.parseInt(stdin.readLine());
System.out.println("enter the element to be searched");
key=Integer.parseInt(stdin.readLine());
i=search(x,n,key);
if(i==-1)
System.out.println(key+"not found");
else
System.out.println(key+" found at position "+i+1);
}
static int search(int x[],int n,int key)
{
int i=0;
while(i<n)
if(key==x[i])
return i;
else i++;
return -1;
}
}
Output:
F:\Progr>javac search.java
F:\Progr>java Search
enter the no of elements
5
enter the elements
5
4
3
2
1
enter the element to be searched
3

3 found at position 3

Experiment: 9
AIM : Working of String:
1. Reverse the string and decide whether it is palindrome or not
2. Capitalize the first letter of each word
3. Count the frequency of particular letter and replace that particular letter by #

4. Count the no. of uppercase, lowercase, blank spaces, digits, special characters from string

OBJECTIVE : To enable the student to get a basic knowledge of the String class and its
functions that is used in String manipulation.

DESCRIPTION: 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.
The String class is immutable, so that once it is created a String object cannot be changed. The
String class has a number of methods, some of which will be discussed below, that appear to
modify strings. Since strings are immutable, what these methods really do is create and return a
new string that contains the result of the operation.

Creating Strings
The most direct way to create a string is to write:
String greeting = "Hello world!";
In this case, "Hello world!" is a string literal—a series of characters in your code that is
enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler
creates a String object with its value—in this case, Hello world!.
As with any other object, you can create String objects by using the new keyword and a
constructor. The String class has thirteen constructors that allow you to provide the initial value
of the string using different sources, such as an array of characters:
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println(helloString);
The last line of this code snippet displays hello.
String Length
Methods used to obtain information about an object are known as accessor methods. One
accessor method that you can use with strings is the length() method, which returns the number
of characters contained in the string object. After the following two lines of code have been
executed, len equals 17:
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
A palindrome is a word or sentence that is symmetric—it is spelled the same forward and
backward, ignoring case and punctuation. Here is a short and inefficient program to reverse a
palindrome string. It invokes the String method charAt(i), which returns the ith character in the
string, counting from 0.
Concatenating Strings
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end.
You can also use the concat() method with string literals, as in:
"My name is ".concat("Rumplestiltskin");
Strings are more commonly concatenated with the + operator, as in
"Hello," + " world" + "!"
which results in
"Hello, world!"
The + operator is widely used in print statements. For example:
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
which prints
Dot saw I was Tod
Such a concatenation can be a mixture of any objects. For each object that is not a String, its
toString() method is called to convert it to a String.
CONCLUSION: Thus we studied to use of strings and different methods of string manipulation.
REFERENCES:
Java complete rwference 7th edition by Herbert Schildt
Programming with JAVA by Balgurusamy
SAMPLE CODE
import java.io.*;
class TitleCase{
public static void main(String args[]) throws IOException{
String str,str1,str2;
int i,n;
BufferedReader br= new BufferedReader (new InputStreamReader (System.in));
System.out.println("Enter a String:");
str=br.readLine();
str=str.toLowerCase();
str1=str.substring(1);
str=str.substring(0,1);
str=str.toUpperCase();
str=str.concat(str1);
n=str.length();
for(i=0;i<=n-1;i++)
{
if(str.charAt(i)==' ')
{
str1=str.substring(0,i+1);
str2=str.substring(i+2);
str=str.substring(i+1,i+2);
str=str.toUpperCase();
str=str1.concat(str);
str=str.concat(str2);
}
}
System.out.println(str);
}
}
D:\Programs\Programs\chapter 3\prog 3.22>javac TitleCase.java

D:\Programs\Programs\chapter 3\prog 3.22>java TitleCase


Enter a String:
java is programming langauge
Java Is Programming Langauge

Experiment: 10
AIM : WAP to implement functions of Vectors.
OBJECTIVE : To make the students familiarize with the concepts and the methods of
the Vector class.
DESCRIPTION: Vector implements a dynamic array. It is similar to ArrayList, but with two
differences:
- Vector is synchronized.
- Vector contains many legacy methods that are not part of the collections framework.
Vector proves to be very useful if you don't know the size of the array in advance or you just need one
that can change sizes over the lifetime of a program.
The Vector class supports four constructors. The first form creates a default vector, which has an initial
size of 10:
Vector()
The second form creates a vector whose initial capacity is specified by size:
Vector(int size)
The third form creates a vector whose initial capacity is specified by size and whose increment is
specified by incr. The increment specifies the number of elements to allocate each time that a vector is
resized upward:
Vector(int size, int incr)
The fourth form creates a vector that contains the elements of collection c:
Vector(Collection c)
CONCLUSION: Thus we studied to use vectors.
REFERENCES:
Java complete rwference 7th edition by Herbert Schildt
Programming with JAVA by Balgurusamy
SAMPLE CODE:
import java.util.*;
import java.io.*;
class Sorts
{
public static void main(String args[])
{
Vector v=new Vector();
int i,j,k;
String s=new String();
for(i=0;i<5;i++)
v.addElement( args[i]);
System.out.println("Elements in vector before sorting are:");
for(i=0;i<5;i++)
System.out.print(" "+v.elementAt(i));
System.out.println();
String str[]=new String[10];
for(i=0;i<5;i++)
str[i]=(String)(v.elementAt(i));
for(i=0;i<5-1;i++)
for(j=0;j<5-1-i;j++)
if((str[j+1].compareTo(str[j]))<0)
{
s=str[j];
str[j]=str[j+1];
str[j+1]=s;
}
v.removeAllElements();
for(i=0;i<5;i++)
v.addElement( str[i]);
System.out.println("Elements in vector after sorting:");
for(i=0;i<5;i++)
System.out.print(" "+v.elementAt(i));
}
}

Output:
C:\Users\Animals\Desktop>javac sorts.java
C:\Users\Animals\Desktop>java Sorts sonal heena anil anup zeba
Elements in vector before sorting are:
sonal heena anil anup zeba
Elements in vector after sorting are:
anil anup heena sonal zeba
Experiment: 11
AIM :To study interface: Create an interface Area & implement the same in
different classes Rectangle ,circle ,triangle.
OBJECTIVE : To understand concept of interface and how to implement multiple inheritance.
DESCRIPTION:
* An interface is a collection of method names, without definitions, that can be added to classes to
provide additional behavior not included with those methods the class defined itself or inherited from its
superclasses.
* Although, a single Java class can have only one superclass (due to single inheritance) that class can also
implement any number of interfaces.
*If two very disparate classes implement the same interface, they can both respond to the same method
calls (as defined by that interface), although what each class actually does in response to those method
calls may be very different.

UsingInterface:

Public interface SoundInterface {


public void speak();}

*The interface keyword is used instead of class .


*All methods declared in an interface are public by default, so there is no need to specify accessibility. A
class can implement an interface by using the implements keyword.
*A class can extend only one other class, but a class can implement as many interfaces as necessary.
eg. abstract public class MammalClass implements SundInterface
{ //accessor methods for properties //namepublic String getName(){
return name;}

CONCLUSION: Thus we studied to use interface.

REFERENCES:
Java complete rwference 7th edition by Herbert Schildt
Programming with JAVA by Balgurusamy

SAMPLE CODE
import java.util.*;
interface methods
{
double PI=3.14159;
public void area();
public void display();
}
class rectangle implements methods
{
protected double length, breadth,area;
rectangle (double l, double b)
{
length=l;
breadth=b;
}
public void area()
{
area=length*breadth;
}
public void display()
{
System.out.println("Area="+area);
}
}
class circle implements methods
{ protected double rad,area;
circle(double r)
{
rad=r;
}
public void area()
{
area= PI*rad*rad;
}
public void display()
{
System.out.println("Area="+area);
}
}
class main
{ public static void main(String args[])
{
methods ref;
for(int i=1;i<=2;i++)
{
switch(i)
{ case 1: ref=new rectangle(4,5);
System.out.println("Rectangle:");
ref.area();
ref.display();
break;
case 2: ref=new circle(4);
System.out.println("circle:");
ref.area();
ref.display();
break;
default: ref=null; }
}}}

EXPERIMENT 12

AIM : To study Multithreading.-


▪ Print the output of table of 5,7,13 using threads
▪ Print the odd number and even number by thread

OBJECTIVE: Understand multitasking and implement multithreading.

DESCRIPTION:
*The thread is the smallest unit of dispatchable code. This means that a single program can perform two
or more tasks at once.
*The principal advantage of multithreading is that it enables you to write very efficient programs because
it lets you utilize the idle time that is present in most programs. A thread can be in one of several states. It
can be running. It can be ready to run as soon as it gets CPU time.
* A running thread can be suspended, which is a temporary halt to its execution. It can later be resumed.
A thread can be blocked when waiting for a resource.
*A thread can be terminated, in which case its execution ends and cannot be resumed. Along with
thread-based multitasking comes the need for a special type of feature called synchronization, which
allows the execution of threads to be coordinated in certain well-defined ways.
*Java’s multithreading system is built upon the Thread class and its companion interface, Runnable.
Thread encapsulates a thread of execution. To create a new thread, your program will either extend
Thread or implement the Runnable interface.
* The Thread class defines several methods that help manage threads. Here are some of the more
commonly used ones (we will be looking at these more closely as they are used):
*All processes have at least one thread of execution, which is usually called the main thread, because it is
the one that is executed when your program begins.
* Creating a Thread
In the most general sense, you create a thread by instantiating an object of type Thread. Java defines two
ways in which this can be accomplished:
• You can implement the Runnable interface.
• You can extend the Thread class, itself.

CONCLUSION : Thus we studied to handle multithreading.

REFERENCES:

Java complete rwference 7th edition by Herbert Schildt


Programming with JAVA by Balgurusamy

SAMPLE CODE:
import java.io.*;
class OddNumbers extends Thread
{
public void run()
{
int i;
for(i=1;i<=10;i+=2)
{
System.out.println(i);
}
}
}
class EvenNumbers extends Thread
{
public void run()
{
int i;
for(i=2;i<=10;i+=2)
{
System.out.println(i);
}
}
}
class MainT
{
public static void main(String args[])
{
OddNumbers n=new OddNumbers();
Thread t1=new Thread(n);
EvenNumbers n1=new EvenNumbers();
Thread t2=new Thread(n1);
t1.start();
t2.start();
}
}
D:\Programs>javac MainT.java

D:\Programs>java MainT
1
2
3
4
5
6
7
8
9
10

EXPERIMENT NO 13

AIM : Program to implement Collection examples on ArrayList, LinkedList.

OBJECTIVE : Understand collection framework and implement it.

DESCRIPTION:

*The Java Collections Framework standardizes the way in which groups of objects are handled by your
programs.
*Collections were not part of the original Java release, but were added by J2SE 1.2. Prior to the
Collections Framework, Java provided ad hoc classes such as Dictionary, Vector, Stack, and Properties
to store and manipulate groups of objects.
*The Collections Framework was designed to meet several goals.
-First, the framework had to be high-performance. The implementations for the fundamental collections
(dynamic arrays, linked lists, trees, and hash tables) are highly efficient. You seldom, if ever, need to code
one of these “data engines” manually.
-Second, the framework had to allow different types of collections to work in a similar manner and with a
high degree of interoperability.
-Third, extending and/or adapting a collection had to be easy. Toward this end, the entire Collections
Framework is built upon a set of standard interfaces. Several standard implementations (such as
LinkedList, HashSet, and TreeSet) of these interfaces are provided that you may use as-is. You may
also implement your own collection, if you choose. Various special-purpose implementations are created
for your convenience, and some partial implementations are provided that make creating your own
collection class easier. Finally, mechanisms were added that allow the integration of standard arrays into
the Collections Framework.
*The Collection Classes
Now that you are familiar with the collection interfaces, you are ready to examine the standard
classes that implement them. The standard collection classes are summarized in the following table:
*ArrayList supports dynamic arrays that can grow as needed Standared array supported by java cannot grow
or shrink, after created you must know in advance how many elements an array will hold, but, sometimes,
you may not know until run time precisely how large an array you need. To handle this situation,
Collections Framework defines ArrayList In essence, an ArrayList is a variable-length array of object
REFERENCES That is, an ArrayList can dynamically increase or decrease in size.
Lists are created with an initial size, when this size is exceeded, the collection is automatically
enlarged.When objects are removed, the array can be shrunk. ArrayList has the constructors shown
here:
ArrayList( )
ArrayList(Collection<? extends E> c)
ArrayList(int capacity)
The first constructor builds an empty array list. The second constructor builds an array list that is
initialized with the elements of the collection c. The third constructor builds an array list that has the
specified initial capacity. The capacity is the size of the underlying array that is used to store the
elements The capacity grows automatically as elements are added to an array list.
*The LinkedList class extends AbstractSequentialList and implements the List, Deque, and Queue
interfaces. It provides a linked-list data structure. LinkedList is a generic class that has this declaration:
class LinkedList<E>
Here, E specifies the type of objects that the list will hold LinkedList has the two constructors shown
here:
LinkedList( )
LinkedList(Collection<? extends E> c)
The first constructor builds an empty linked list. The second constructor builds a linked list that is
initialized with the elements of the collection c.

REFERENCES:

Java complete rwference 7th edition by Herbert Schildt


Programming with JAVA by Balgurusamy

SAMPLE CODE:
// Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " +
al.size());
// Add elements to the array list.
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +
al.size());
// Display the array list.
System.out.println("Contents of al: " + al);
// Remove elements from the array list.
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +
al.size());
System.out.println("Contents of al: " + al);
}
}
The output from this program is shown here:
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]

// Demonstrate LinkedList.
import java.util.*;
class LinkedListDemo {
public static void main(String args[]) {
// Create a linked list.
LinkedList<String> ll = new LinkedList<String>();
// Add elements to the linked list.
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
// Remove elements from the linked list.
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: "
+ ll);
// Remove first and last elements.
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: "
+ ll);
// Get and set a value.
String val = ll.get(2); ll.set(2, val + "
Changed"); System.out.println("ll after
change: " + ll);
}
}
The output from this program is shown here:
Original contents of ll: [A, A2, F, B, D, E, C, Z]
Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]
EXPERIMENT NO 14

AIM : WAP to implement packages

OBJECTIVE : Understand what is package. Create user defined package and import them
In your program.

DESCRIPTION:

*To create a package is quite easy: simply include a package command as the first statement in a Java
source file. Any classes eclared within that file will belong to the specified package.
* The package statement defines a name space in which classes are stored. If you omit the package
statement, the class names are put into the default package, which has no name. (This is why you haven’t
had to worry about packages before now.)
*While the default package is fine for short, sample programs, it is inadequate for real applications. Most
of the time, you will define a package for your code.
*This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a package
called MyPackage.
package MyPackage;
*Java uses file system directories to store packages. For example, the .class files for any classes you
declare to be part of MyPackage must be stored in a directory called MyPackage. Remember that case is
significant, and the directory name must match the package name exactly. More than one file can include
the same package statement.
*The package statement simply specifies to which package the classes defined in a file belong. It does
not exclude other classes in other files from being part of that same package. Most real-world packages
are spread across many files.
*You can create a hierarchy of packages. To do so, simply separate each package name from the one
above it by use of a period. The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
Apackage hierarchy must be reflected in the file system of your Java development
system. For example, a package declared as package java.awt.image; needs to be stored in
java\awt\image in a Windows environment. Be sure to choose your package names carefully. You cannot
rename a package without renaming the directory in which the classes are stored.
*In a Windows environment, if the path to MyPack is
C:\MyPrograms\Java\MyPack
Then the class path to MyPack is
C:\MyPrograms\Java

CONCLUSION: Thus we studied how to create and use package.

REFERENCES:

Java complete rwference 7th edition by Herbert Schildt


Programming with JAVA by Balgurusamy

SAMPLE CODE:
Creating package
package package1;
public class ClassA
{
public void displayA()
{
System.out.println("class A");
}
}

Using package
import package1.ClassA;
class PackageTest1
{
public static void main(String args[])
{
ClassA a=new ClassA();
a.displayA();
}} Output
C:\Users\Admin>d:

D:\>cd Programs

D:\Programs>cd package1
D:\Programs\package1>javac ClassA.java

D:\Programs\package1>cd..

D:\Programs>javac PackageTest1.java

D:\Programs>java PackageTest1
class A

EXPERIMENT NO 15

AIM : To study graphics using applet


▪ Joker face.
▪ House
▪ Traffic signal

OBJECTIVE : Understand what is applet, how it works, and implement and draw different
Graphics shape.

DESCRIPTION:

*One of Java’s design goals is to create applets, which are little programs that run inside a Web
browser. Because they must be safe, applets are limited in what they can accomplish. However, applets
are a powerful tool that support client-side programming, a major issue for the Web.

*Applets are built using an application framework. You inherit from class Applet and override the
appropriate methods. There are a few methods that control the creation and execution of an applet on a
Web page:
*Java applets inherit significant functionality from the Applet or JApplet class, including the
capabilities to communicate with the browser and present a graphical user interface (GUI) to the user.
*An applet that will be using GUI components from Swing (Java's GUI toolkit) should extend the
javax.swing.JApplet base class, which provides the best integration with Swing's GUI facilities.

sample code: import


java.awt.*; import
java.applet.*;
public class SimpleApplet extends Applet {
public void paint(Graphics g)
{
g.drawString("Java makes applets easy.", 20, 20);
}
}

SimpleApplet:

<applet code="SimpleApplet" width=200 height=60>


</applet>
The width and height statements specify the dimensions of the display area used by the applet. To
execute SimpleApplet with an applet viewer, you will execute this HTML file. For example, if the
preceding HTML file is called StartApp.html, then the following command line will run

SimpleApplet:
C:\>appletviewer
StartApp.html

CONCLUSION : Thus we studied graphics using applet.

REFERENCES:

Java complete rwference 7th edition by Herbert Schildt


Programming with JAVA by Balgurusamy

SAMPLEPROGRAM

import java.applet.*;
import java.awt.*; /*

<applet CODE="DrawingStuff.class" WIDTH=250


HEIGHT=350> </applet>
*/

public class DrawingStuff extends Applet


{
public void paint( Graphics g )

{
setBackground(Color.white);
Color c1=new Color(255,0,0);
Color c2=new Color(100,100,255);
g.setColor(c1);
g.drawString( "Playing with colors !", 10, 10 );
g.setColor( c2);
g.drawLine(10,20,200,20);
g.setColor(Color.darkGray);
g.fillRect( 10, 50, 50,50);
g.setColor( Color.blue );
g.drawRect( 80, 50, 60,40);
g.setColor( Color.pink );
g.fillOval( 80, 100, 50, 25 );
g.setColor( Color.cyan );
g.drawOval( 50, 225, 100, 50 );
g.setColor( Color.yellow );

g.drawArc( 10, 110, 80, 80, 90, 180 );


g.setColor( Color.orange);
g.fillArc( 140, 40, 120, 120, 90, 45 );
g.setColor( Color.magenta );
g.fillArc( 150, 150, 100, 100, 90, 90 );
g.setColor( Color.black );

g.fillArc( 160, 160, 80, 80, 90, 90 );


g.setColor( Color.green );
}

EXPERIMENT NO 16
AIM : Program to demonstrate user defined exception

OBJECTIVE : Understand user defined exceptions and implement it.

DESCRIPTION:

User defined exceptions in java are also known as Custom exceptions. Most of the times when
we are developing an application in java, we often feel a need to create and throw our own
exceptions.
There are two types of exceptions: checked exceptions and unchecked exceptions. In this tutorial
we will learn both of them with the help of examples. The main difference between checked and
unchecked exception is that the checked exceptions are checked at compile-time while
unchecked exceptions are checked at runtime.
What are checked exceptions?

Checked exceptions are checked at compile-time. It means if a method is throwing a checked


exception then it should handle the exception using try-catch block or it should declare the
exception using throws keyword, otherwise the program will give a compilation error. It is
named as checked exception because these exceptions are checked at Compile time.

Lets understand this with this example: In this example we are reading the file myfile.txt and
displaying its content on the screen. In this program there are three places where an checked
exception is thrown as mentioned in the comments below. FileInputStream which is used for
specifying the file path and name, throws FileNotFoundException. The read() method which
reads the file content throws IOException and the close() method which closes the file input
stream also throws IOException.

class MyException extends Exception{


String str1;
MyException(String str2) {
str1=str2;
}
public String toString(){
return ("Output String = "+str1) ;
}
}

class CustomException{
public static void main(String args[]){
try{
throw new MyException("Custom");
// I'm throwing user defined custom exception above
}
catch(MyException exp){
System.out.println("Hi this is my catch block") ;
System.out.println(exp) ;
}
}
}

Output-

Thus we have implemented User defined Exception


EXPERIMENT NO 17
AIM : Program to demonstrate user defined exception

OBJECTIVE : Understand user defined exceptions and implement it.

DESCRIPTION:

Multithreading in java is a process of executing multiple threads simultaneously.


Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
Java Multithreading is mostly used in games, animation etc

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.

2) You can perform many operations together so it saves time.

3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.

Life Cycle of a Thread

A thread goes through various stages in its life cycle. For example, a thread is born, started,
runs, and then dies. The following diagram shows the complete life cycle of a thread.

Following are the stages of the life cycle −

● New − A new thread begins its life cycle in the new state. It remains in this state until

the program starts the thread. It is also referred to as a born thread.

● Runnable − After a newly born thread is started, the thread becomes runnable. A thread

in this state is considered to be executing its task.


● Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for

another thread to perform a task. A thread transitions back to the runnable state only

when another thread signals the waiting thread to continue executing.

● Timed Waiting − A runnable thread can enter the timed waiting state for a specified

interval of time. A thread in this state transitions back to the runnable state when that

time interval expires or when the event it is waiting for occurs.

● Terminated (Dead) − A runnable thread enters the terminated state when it completes

its task or otherwise terminates.

Thread Priorities

Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.

Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).

Threads with higher priority are more important to a program and should be allocated processor
time before lower-priority threads. However, thread priorities cannot guarantee the order in
which threads execute and are very much platform dependent.

Create a Thread by Implementing a Runnable Interface

If your class is intended to be executed as a thread then you can achieve this by implementing a
Runnable interface. You will need to follow three basic steps −

Step 1
As a first step, you need to implement a run() method provided by a Runnable interface. This
method provides an entry point for the thread and you will put your complete business logic
inside this method. Following is a simple syntax of the run() method −

public void run( )

Step 2

As a second step, you will instantiate a Thread object using the following constructor −

Thread(Runnable threadObj, String threadName);

Where, threadObj is an instance of a class that implements the Runnableinterface and


threadName is the name given to the new thread.

Step 3

Once a Thread object is created, you can start it by calling start() method, which executes a call
to run( ) method. Following is a simple syntax of start() method −

void start();

Example

Here is an example that creates a new thread and starts running it −

class RunnableDemo implements Runnable {


private Thread t;
private String threadName;

RunnableDemo( String name) { threadName =


name; System.out.println("Creating " +
threadName );
}

public void run() {


System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
}catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start () {


System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {

public static void main(String args[]) {


RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");


R2.start();
}
}Output
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

You might also like