Sie sind auf Seite 1von 60

examkey.wordpress.

com
LAB

Ex. No :1

25245 - JAVA PROGRAMMING

Print the digits of a number

Aim :
To write a java program to print the individual digits of a 3 digit number.
Algorithm:
1. Get any 3 digit integer as input
2. Find the last digit by n%10 and store it in r;
3. Print value of r
4. Reduce n by n/10;
5. Repeat this until n not equal to 0
Program:
/* Program to print the individual digits of a 3-digit number */
import java.io.*;
class SumDigit
{
public static void main(String args[])throws IOException
{
BufferedReader din=new BufferedReader(new
InputStreamReader(System.in));
int n;
System.out.print("Enter the number:");
n=Integer.parseInt(din.readLine());
System.out.println("The digits in the number are);
while(n!=0)
{
int r=n%10; /* Find the last digit */
n=n/10; /* Reduce the number */
System.out.println(r);
}
}
}
1

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Output:
D:\java>javac Digits.java
D:\java>java Digits 729
The number is 729
The digits in the number are
**************************
9
2
7
D:\java>
Viva Questions:
What are command line arguments?
The values that are passed to the main method from the command line while executing
the program are called as command line arguments.
What are the various types of operators available in java?
Arithmetic operator, Relational operator, Logical operator, Bitwise operator,Increment
and decrement operator, Assignment operator, Conditional operator and Special operator.
What is a ternary operator?
The operator that takes three arguments is called as ternary operator. The conditional
operator is the only ternary operator available in java.
What is the use of Integer.parseInt() method?
This method is used to convert the String object into integer value.
What is called as a Boolean expression?
An expression that returns either true or false value is called a Boolean expression.

examkey.wordpress.com
LAB

Ex. No :2

25245 - JAVA PROGRAMMING

Biggest Number

Aim:
To write a java program to read two integers and print the larger number followed by the
words is larger. If the numbers are equal print the message These numbers are equal.
Agorithm:
1. Import the package java.io*
2. Read the value in the variable a and b
3. check whether a>b if it is true print a is larger
4. else check b>a if it is true print b is larger
5. else print a is equal to b
Program:
import java.io.*;
class Large
{
public static void main(String args[])throws IOException
{
BufferedReader din=new BufferedReader(new
InputStreamReader(System.in));
int a,b;
System.out.print("Enter the value of a:");
a=Integer.parseInt(din.readLine());
System.out.print("Enter the value of b:");
b=Integer.parseInt(din.readLine());
System.out.println("a="+a+"\t\tb="+b);
if(a==b)
System.out.println("These numbers are equal");
else if(a>b)
System.out.println(a+ " is larger");
3

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

else
System.out.println(b+" is larger");
}
}
Output 1:
D:\java>javac Large.java
D:\java>java Large
Enter the value of a:45
Enter the value of b:34
a=45 b=34
45 is larger
Viva Questions:
What is a control structure?
Control structures are statements that are used to change the flow of the program based
on some condition.
What are the two types of control structures?
Decision making statements and Looping statements
What are decision making statements?
The statements that are used to execute only a block of code and leaving others based on
the condition.
What are the various decision making statements available in java?
Simple if, if..else, nested if..else, else if ladder and switch statement.

examkey.wordpress.com
LAB

Ex. No :3

25245 - JAVA PROGRAMMING

Armstrong Nnumber

Aim:
3

To write a java program to print the Armstrong numbers. (153 = 1 + 5 + 3 = 1 + 125


+27 =153 is an Armstrong number)
Algorithm:
1. Import the package java.io*
2.

Initialize sum=0

3.

Find n%10 and store it in variable s and add with sum.

4.

Repeat the above step till n!=0, Print Sum

Program:
import java.io.*;
class Armstrong
{
public static void main(String args[])throws IOException
{
System.out.println("Armstrong numbers");
System.out.println("*****************");
for(int i=100;i<=999;i++)
{
int n=i,sum=0;
while(n!=0)
{
int r=n%10;
sum=sum+(int)Math.pow(r,3);
n=n/10;
}
if(sum==i)
System.out.println(i);
5

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

}
}
}
Output:
D:\java>javac Armstrong.java
D:\java>java Armstrong
Armstrong numbers
*****************
153
370
371
407
Viva Question:
What is the use looping statement?
The looping statement is used to execute a block of repeatedly until the condition is true.
What are the various looping statements available in java?
While, do.. while and for statements.
What is the difference between while and do..while?
In case of while statement the block of code will not be executed atleast once if
the condition is false at the first run.
In case of do..while statement the block of code will be executed atleast once if
the condition is false at the first run.

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Ex. No :4 Largest and Smallest in the array


Aim:
To write a java program to find the largest and smallest number in an array.
Algorithm:
1. Import the package java.io*
2. Declare an array variable member
3. Initialize variable big =0,small=0
4. And check each element in array with big and also with small element
5. After finding biggest and smallest element in array. Print the element
Program:
import java.io.*;
class ArrBig
{

public static void main(String args[])throws IOException


{
int a[]=new int[20];
int n,big,small;
BufferedReader din=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter number of terms in the array:");
n=Integer.parseInt(din.readLine());
System.out.println("Enter array element:");
for(int i=0;i<n;i++)
{

System.out.print("a["+i+"]:");
a[i]=Integer.parseInt(din.readLine());

}
big=a[0]; small=a[0];
for(int i=1;i<n;i++)
{
if(a[i]>big)
big=a[i];
if(a[i]<small)
7

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING


small=a[i];

}
System.out.println("\nThe elements in the array");
for(int i=0;i<n;i++)
System.out.print("\t"+a[i]);
System.out.println("\nThe biggest element in the array is "+big);
System.out.println("The smallest element in the array is "+small);
}}
Output:
D:\java>javac ArrBig.java
D:\java>java ArrBig
Enter number of terms in the array:5
Enter array element:
a[0]:56
a[1]:78
a[2]:12
a[3]:4
a[4]:89
The elements in the array
56 78 12 4 89
The biggest element in the array is 89
The smallest element in the array is 4
Viva Questions:
Define array-An array is a collection of elements of same data type referred by a common
name. The elements are of the array are stored in consecutive memory locatons.
Types of arrays-One dimensional array, two dimensional array and multidimensional arrays.
How to declare a two dimensional array?
Datatype arrayname[][]=new datatype[ row size][column size]
How the individual elements of an array can be accessed?
The individual elements can be accessed using the index. The index of the first element
starts with 0.

examkey.wordpress.com
LAB

Ex.No.5

25245 - JAVA PROGRAMMING

String

Aim:
To write a java program that creates a string object and initializes it with your
name and performs the following operations
a) To find the length of the string object using appropriate String method.
b) To find whether the character a is present in the string. If yes find the
number of times a appear in the name and the location where it appears
Algorithm:
1. Initialize the string object
2. Find the length of the string
3. Find the number of occurrence of character a
4. Print the location of the occurence
Program:
class StringDemo
{
public static void main(String args[])
{
String name="Java Programming";
int count=0;
System.out.println("The given name is "+name);
System.out.println("The length of name is "+name.length());
if(name.indexOf('a')<0)
System.out.println("The character 'a' is not present in my name");
else
{
System.out.println("The character 'a' is present in the locations");
int loc=0;
while(loc<name.lastIndexOf('a'))
9

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

{
int x=name.indexOf('a',loc);
System.out.println(x);
loc=x+1;
count++;
}
System.out.println("The character 'a' is present "+count+" times");
}
}
}
Output:
D:\java>javac StringDemo.java
D:\java>java StringDemo
The given name is Java Programming
The length of name is16
The character 'a' is present in the locations
1
3
10
The character 'a' is present 3 times
D:\java>

10

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Ex. No:6 Classes and Objects (Students Mark


Sheet)
Aim:
To write a java program to display total marks of 5 students using student class.

Given

the following attributes: Regno(int), Name(string), Marks in subjects(Integer Array), Total (int).
Algorithm:
1. Initialize 5 student register no,name and marks of 3 subjects
2. Find the total marks of each student
3. Print the register no,name and marks and total of 5 students
Program:
import java.io.*;
/* Student class */
class Student
{
int regno,total;
String name;
int mark[]=new int[3];
void readinput() throws IOException
{
BufferedReader

din=new

InputStreamReader(System.in));
System.out.print("\nEnter the Reg.No: ");
regno=Integer.parseInt(din.readLine());
System.out.print("Enter the Name: ");
name=din.readLine();
System.out.print("Enter the Mark1: ");
mark[0]=Integer.parseInt(din.readLine());
System.out.print("Enter the Mark2: ");
mark[1]=Integer.parseInt(din.readLine());
System.out.print("Enter the Mark3: ");
mark[2]=Integer.parseInt(din.readLine());
total=mark[0]+mark[1]+mark[2];
}

BufferedReader(new

void display()
{
System.out.println(regno+"\t"+name+"\t"+mark[0]+"\t"+mark[1]+"\t"+ma
rk[2]+"\t"+total);
}
}
/* Main class */
class Mark
{
public static void main(String args[]) throws IOException
{
Student s[]=new Student[5];
for(int i=0;i<5;i++)
{
s[i]=new Student();
s[i].readinput();
}
System.out.println("\t\t\tMark List");
System.out.println("\t\t\t*********");
System.out.println("RegNo\tName\tMark1\tMark2\tMark3\tTotal");
for(int i=0;i<5;i++)
s[i].display();
}
}
Output:
D:\java>javac Mark.java
D:\java>java Mark
Enter the Reg.No: 1
Enter the Name: Balu
Enter the Mark1: 67
Enter the Mark2: 90
Enter the Mark3: 56
Enter the Reg.No: 2
Enter the Name: Geetha
Enter the Mark1: 87
Enter the Mark2: 79

Enter the Mark3: 92


Enter the Reg.No: 3
Enter the Name: Vimal
Enter the Mark1: 87
Enter the Mark2: 60
Enter the Mark3: 71
Enter the Reg.No: 4
Enter the Name: Fancy
Enter the Mark1: 92
Enter the Mark2: 89
Enter the Mark3: 86
Enter the Reg.No: 5
Enter the Name: Janani
Enter the Mark1: 78
Enter the Mark2: 90
Enter the Mark3: 91
Mark List
********************************************
RegNo

Name

Mark1 Mark2 Mark3 Total

Balu

67

90

56 213

Geetha

87

79

92 258

Vimal

87

60

71 218

Fancy

92

89

86 267

Sriram

78 90

91

259

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Ex . No : 7 Interfaces (Class implementing two


interfaces)
Aim :
To write a java program to show how a class implements two interfaces.
Algorithm:
1. Create two interface A and B
2. Implement the two interface in the myclass
3. Create an object for myclass amd access the interface methods
Program:
/* Program to show a implementing two interfaces */
/* First interface */
interface One
{
int x=12;
}
/* Second interface */
interface Two
{
int y=10;
void display();
}
/* Class implementing the interfaces */
class Demo implements One,Two
{
public void display()
{

System.out.println("X in inteface One ="+x);


System.out.println("Y in interface Two="+y);
System.out.println("X+Y= "+(x+y));
}
}

/* Main class */
class TwoInterface
{
public static void main(String args[])
{
Demo d=new Demo();
d.display();
}
}
Output:
D:\java>javac TwoInterface.java
D:\java>java TwoInterface
X in inteface One =12
Y in interface Two=10
X+Y= 22
Viva Questions:
What is an interface?
Interface is just like a class which contains final variables and public abstract methods. It
is used to implement multiple inheritance in java.
What is an abstract method?
The method which has only declaration in the super class and defined in the subclass is
known as abstract method.
Syntax for defining an interface
interface interfacename
{

//define the static variables and declare abstract methods

}
How to implement interface?
The abstract methods should be implemented in a class to use the interface in our
program.
class className extends superclassname implements interface1, interface2,
{
}

//define the members

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Ex. No :8 Exception Handling (User Defined


Exception)
Aim:
To write a java program to create our exception subclass that throws exception if the sum
of two integers is greater than 99.
Algorithm:
1. Import the package java.io.*
2. Create user defined exception class
3. In main class, one error may occur related to user defined exception
4. If the error is caught the appropriate catch block executes
Program:
/* User defined exception class */
import java.io.*;
/* User defined exception class */
class MyException extends Exception
{
MyException(String mg)
{

super(mg);

}
}
/* Main class */
class UserExcep
{
public static void main(String args[])throws IOException
{
BufferedReader

bin=new

BufferedReader(new

InputStreamReader(System.in));
int a,b;
System.out.print("Enter the value of A:");
a=Integer.parseInt(bin.readLine());
16

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

System.out.print("Enter the value of B:");


b=Integer.parseInt(bin.readLine());
try
{

int c=a+b;
if(c>99)
throw new MyException("The numbers are too big");
System.out.println(a+"+"+b+"="+c);

}
catch(MyException e)
{

System.out.println("The sum of numbers should be less than 99");


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

}
}
}
Output:
D:\java>javac UserExcep.java
D:\java>java UserExcep
Enter the value of A:56
Enter the value of B:34
56+34=90
C:\javapgm>java UserExcep
Enter the value of A:56
Enter the value of B:90
The sum of numbers should be less than 99
The numbers are too big
Viva Questions:
What is an exception?
An exception means errors that occur during execution of the program that
disrupts normal flow of the program.
What are the steps in handling exception?
The following are the tasks in handling exceptions
17

Find the problem (Hit the exception )


Inform that an error has occurred (Throw the exception)
Receive the error (Catch the exception)
Take corrective action (Handle the exception )
Explain try..catch block?
The programmers can use the try.. catch block to handle the exceptions that suit
their programs. This avoids abnormal termination of the program.
Syntax
try
{
//Statements that may generate the exception
}
catch(exceptionclass object)
{
//Statements to process the exception
}
finally()
{
//Statements to be executed before exiting exception handler
}
Try block: Inside the try block we can include the statements that may cause an exception and
throw an exception.
The catch block: The catch block contains the code that handles the exceptions and may correct
the exceptions that ensure normal execution of the program. Catching the thrown exception
object from the try block by the corresponding catch block is called throwing an exception.
What is the use of finally block?
The finally block contains codes that will be executed when the exception occurs or not.
What is the use of multiple catch blocks?
The multiple catch blocks are used when there is a possibility of more then one type of
exception gets generated when a try block is executed
What is meant by user defined exception?
The exception class that is defined by the user to suit their need by deriving the Exception
as used in user defined exception .

18

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Ex .No: 9 Fi les using Byte Stream Class


Aim:
To write a java program to create a text file using ByteStream class.
Algorithm:
1. Import the package java.io.*
2. Create a string variable and assign value
3. Create a file object by using output strea class and specify the file name to be created
as argument
4. Write the string into a file using write()
5. Then display the file using type command
Program:
/* Program to create a text file using Byte Stream class */
import java.io.*;
class FileWriteDemo
{
public static void main(String srgs[])throws Exception
{
int len,size;
String s;
FileOutputStream fout=new FileOutputStream("Sample.txt");
BufferedReader din=new BufferedReader(new
InputStreamReader(System.in));
byte myarr[]=new byte[1024];
System.out.println("Enter the contents of the sample.txt file. Give
* in new line to end ");
while(true)
{
s=din.readLine();
19

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

if (s.equals("*")) break;
myarr=s.getBytes();
91
fout.write(myarr);
fout.write('\n');
}
fout.close();
System.out.println("The file is created");
}
}
Output:
D:\java>javac FileWriteDemo.java
D:\java>java FileWriteDemo
Enter the contents of the sample.txt file. Give * in new line to end
Sample file created
*
The file is created
Checking the created file
D:\java>type sample.txt
Sample file created
D:\java>

20

examkey.wordpress.com
LAB

Ex.No :10

25245 - JAVA PROGRAMMING

Files copy one file to another file)

Aim:
To write a java program to copy one file to another.
Algorithm:
1. Import the package java.io.*
2. Initialize two strings
3. Get the source file and store it in one string
4. Copy the source file into another file
Program:
import java.io.*;
class FileCopyDemo
{
public static void main(String srgs[])
{
String infile,outfile;
BufferedReader din=new BufferedReader(new
InputStreamReader(System.in));
try
{

System.out.print("Enter the name of the file to be copied:");


infile=din.readLine();
System.out.print("Enter the name of the new file :");
outfile=din.readLine();
FileOutputStream fout=new FileOutputStream(outfile);
FileInputStream fin=new FileInputStream(infile);
byte myarr[]=new byte[512];
while(fin.read(myarr) !=-1)
{

fout.write(myarr);

}
21

System.out.println("The file "+infile+" is copied to "+outfile);


fout.close();
fin.close();
}
catch(IOException e)
{
}

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

}
}
Output:
1. D:\java>javac FileCopyDemo.java
D:\java>java FileCopyDemo
Enter the name of the file to be copied:sample.txt
Enter the name of the new file :sa.txt
The file sample.txt is copied to sa.txt
2. Verifying the copied file
Viva Question:
What is a file?
The file is a collection of information.
What are the properties specified by the File class in java?
The File class abstracts properties like size, permission, time and date of creation and
modification.
What are streams?
Streams are logical entities that re linked with data source/ destination
What are input streams and output stream?
Input streams are used to read data from a keyboard, a disk file or from memory buffer.
Output streams are used to write data to a disk file, memory buffer or display screen etc.
How are streams classified according to the type of data?
The streams are classified into byte streams and character streams based on the
type of data they read or write.
Byte streams read and write bytes.
Character streams read and write characters and strings.

22

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Ex. No :1 Vectors
Aim:
To write a menu based java program that accepts a shopping list of four items
from the command line and store in a Vector and perform operations
1. To add an item at a specific location in the list.
2. To delete an item in the list.
3. To print the contents of the vector.
4. To delete all elements
5. To add an item at the end of the vector
Algorithm:
1. Import the package java.io.* and java.util.
2. Receive four input from the command line and store it in the vector
3. Using Switch statement, do all vector operations
4. Perform the operation by using vector.
Program:
import java.io.*;
import java.util.*;
class DemoVector
{
public static void main(String args[])throws IOException
{
BufferedReader din=new BufferedReader(new
InputStreamReader(System.in));
Vector v=new Vector();
int ch;
for(int i=0;i<4;i++)
v.addElement(args[i]);
System.out.println("\nThe items in the shopping list");
23

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

System.out.println("\n**********************");
for(int i=0;i<v.size();i++)
System.out.println(v.elementAt(i));
do
{
System.out.println("\n\t\t\tMenu");
System.out.println("\t\t\t******");
System.out.println("\t\t1. To add an item at a specific
location in the list.");
System.out.println("\t\t2. To delete an item in the list.");
System.out.println("\t\t3. To print the contents of the
vector.");
System.out.println("\t\t4. To delete all elements.");
System.out.println("\t\t5. To add an item at the end of the
vector.");
System.out.println("\t\t6. Exit");
System.out.print("\n\n\tEnter your choice:");
ch=Integer.parseInt(din.readLine());
switch(ch)
{
case 1:
System.out.print("\nEnter the item to be added to the list:");
String s=din.readLine();
System.out.print("\nEnter the position to be inserted:");
int pos=Integer.parseInt(din.readLine());
v.insertElementAt(s,pos);
break;
case 2:
System.out.print("\nEnter the item to be deleted from the
list:");
s=din.readLine();
24

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

v.removeElement(s);
break;
case 3:
if(v.isEmpty())
System.out.println("The shopping list is empty");
else
{
System.out.println("\nThe items in the shopping
list");
System.out.println("\n**********************");
or(int i=0;i<v.size();i++)
System.out.println(v.elementAt(i));
}
break;
case 4:
v.removeAllElements();
break;
case 5:
System.out.print("\nEnter the item to be
aded to the list:");
s=din.readLine();
v.addElement(s);
break;
}
}while(ch<=5);
}
}
Output:
D:\java>javac DemoVector.java
D:\java>java DemoVector LuxSoap Rin HairOil Rice
The items in the shopping list
25

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

**********************
LuxSoap
Rin
HairOil
Rice
Menu
******
1. To add an item at a specific location in the list.
2. To delete an item in the list.
3. To print the contents of the vector.
4. To delete all elements.
5. To add an item at the end of the vector.
6. Exit
Enter your choice:1
Enter the item to be added to the list:Dhal
Enter the position to be inserted:2
Menu
******
1. To add an item at a specific location in the list.
2. To delete an item in the list.
3. To print the contents of the vector.
4. To delete all elements.
5. To add an item at the end of the vector.
6. Exit
Enter your choice:3
The items in the shopping list
**********************
LuxSoap
Rin
Dhal
HairOil
26

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Rice
Menu
******
1. To add an item at a specific location in the list.
2. To delete an item in the list.
3. To print the contents of the vector.
4. To delete all elements.
5. To add an item at the end of the vector.
6. Exit
Enter your choice:5
Enter the item to be added to the list:ToothPaste
Menu
******
1. To add an item at a specific location in the list.
2. To delete an item in the list.
3. To print the contents of the vector.
4. To delete all elements.
5. To add an item at the end of the vector.
6. Exit
Enter your choice:3
The items in the shopping list
**********************
LuxSoap
Rin
Dhal
HairOil
Rice
ToothPaste
Menu
******
1. To add an item at a specific location in the list.
27

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

2. To delete an item in the list.


3. To print the contents of the vector.
4. To delete all elements.
5. To add an item at the end of the vector.
6. Exit
Enter your choice:2
Enter the item to be deleted from the list:Rice
Menu
******
1. To add an item at a specific location in the list.
2. To delete an item in the list.
3. To print the contents of the vector.
4. To delete all elements.
5. To add an item at the end of the vector.
6. Exit
Enter your choice:3
The items in the shopping list
**********************
LuxSoap
Rin
Dhal
HairOil
ToothPaste
Menu
******
1. To add an item at a specific location in the list.
2. To delete an item in the list.
3. To print the contents of the vector.
4. To delete all elements.
5. To add an item at the end of the vector.
6. Exit
28

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Enter your choice:6


Viva questions:
What is Vector?
Vector is just like an array that can store elements of different data types. The elements of
the vector can only be objects. So the primitive data type must be converted into object data type
before adding to the vector.
What is the difference between capacity and size of the Vector?
Capacity specifies the maximum number of objects that can be stored in the vector. Size
specifies the number of objects that are present in the Vector.
What are the difference between array and Vector?
The elements of the array are of same data type. The elements of the Vector can be
different data type. The elements of the array can be of primary data type. The elements of the
Vector can only be objects. The capacity of the array is fixed. The size of Vector can be changed
during run time.

29

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Ex.No.2. StringBuffer
Aim :
1. To write a java program to create a StringBuffer object and illustrate how to append
characters and to display the capacity and length of the string buffer
2. Create a StringBuffer object and illustrate how to insert characters at the beginning.
3. Create a StringBuffer object and illustrate the operations of the append() and
reverse() methods.
Algorithm:
1. Initialize the string
2. Find the length of the string
3. Insert the character at the beginning
4. Reverse the string and print
Program :
Class StringBuffer
{
Public static void main(String args[])
{

StringBuffer a = new StringBuffer(RAJ);


System.out.println(Length+a.length());
System.out.println(Capacity+a.capacity());
String b = new String(RAM);
a=a.append(b);
System.out.println(a);
System.out.println(a.reverse());

}
}
OUTPUT
Length 6
Capacity 22
RAJ RAM
C.RAJ RAM
30

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Ex. No :3 Classes and Objects (Matching


Rectangles)

Aim:
To write a program in java with a class Rectangle with the data fields width, length, area
and colour. The length, width and area are of double type and colour is of string type.The
methods are get_length(), get_width(), get_colour() and find_area().
Create two objects of Rectangle and compare their area and colour. If the area and colour
both are the same for the objects then display Matching Rectangles, otherwise display Nonmatching Rectangle.
Algorithm:
1. Initialize length and breadth,color of rectangles
2. Get input for 2 rectangles from the user
3. Find matching between rectangles
4. Print the status whether it is matching or not
Program:
/* Program in Java to compare the values in two objects*/
import java.io.*;
/* Rectangle class */
class Rectangle
{
private double length,width,area;
private String colour;
BufferedReader din=new BufferedReader(new InputStreamReader(System.in));
void get_length()throws IOException
{
System.out.print("Enter the length:");
length=Double.parseDouble(din.readLine());
31

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

}
void get_width()throws IOException
{
System.out.print("Enter the width:");
width=Double.parseDouble(din.readLine());
}
void get_colour()throws IOException
{
System.out.print("Enter the colour:");
colour=din.readLine();
}
double find_area()
{
area=length*width;
return area;
}
String put_colour()
{
return colour;
}
}
/* Main class */
class MatchRect
{
public static void main(String args[])throws IOException
{
Rectangle r1,r2;
r1=new Rectangle();
r2=new Rectangle();
System.out.println("Enter the data for Rectangle 1:");
r1.get_length();
32

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

r1.get_width();
r1.get_colour();
System.out.println("Enter the data for Rectangle 2:");
r2.get_length();
r2.get_width();
r2.get_colour();
String c1=r1.put_colour();
String c2=r2.put_colour();
if ((r1.find_area()==r2.find_area()) && (c1.compareTo(c2)==0))
System.out.println("\n\tMatching Rectangles");
else
System.out.println("\n\tNon-Matching Rectangles");
}
}
Output:
D:\java>javac MatchRect.java
D:\java>java MatchRect
Enter the data for Rectangle 1:
Enter the length:6
Enter the width:5
Enter the colour:Pink
Enter the data for Rectangle 2:
Enter the length:5
Enter the width:6
Enter the colour:Pink
Matching Rectangles
D:\java>javac MatchRect.java
D:\java>java MatchRect
Enter the data for Rectangle 1:
Enter the length:5
Enter the width:5
33

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Enter the colour:Green


Enter the data for Rectangle 2:
Enter the length:5
Enter the width:5
Enter the colour:Pink
Non-Matching Rectangles
Viva Questions
What is class?
A class is a collection of data and methods that defines an object. The variables and
methods (functions) of a class are called members of the class.
What is an object?
The variable of type class is called object.
Syntax for defining a class
class className
{
//Declaration of instance variables
//Constructors
//Instance Methods
}
How can we create objects?
The objects can be created using the new operator.
className objectNname=new className();
How the members of a class can be accessed?
The members of the class can be accessed using the dot operator
Objectname .variable
Or
Objectname.methodName(Arguments)

34

examkey.wordpress.com
LAB

Ex. No :4

25245 - JAVA PROGRAMMING

Passing Objects as Arguments

Aim:
To write a java program to define a class that represent Complex numbers with
constructor to enable an object of this class to be initialized when it is declared and a default
constructor when no argument is provided and define methods to do the following by passing
objects as arguments
a) Addition of two Complex numbers
b) Subtraction of two Complex numbers
c) Printing the Complex numbers in the form (a, b).
Algorithm:
1. Initialize two complex number
2. Find the sum of the two complex number
3. Find the subract of the two complex number
4. Print the complex number in form(a,b)
Program:
/* passing object as parameters */
class Complex
{
int r,i;
Complex()
{
r=i=0;
}
Complex(int a,int b)
{
r=a;
35

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

i=b;
}
void display( )
{
System.out.println("("+r+","+i+")");
}
Complex add(Complex c1,Complex c2)
{
Complex c3=new Complex();
c3.r=c1.r+c2.r;
c3.i=c1.i+c2.i;
return c3;
}
Complex sub(Complex c1,Complex c2)
{
Complex c3=new Complex();
c3.r=c1.r-c2.r;
c3.i=c1.i-c2.i;
return c3;
}
}
/* Main class */
class CompNum
{
public static void main(String args[])
{
Complex x1,x2,x3,x4;
x1=new Complex(7,5);
x2=new Complex(4,3);
x3=new Complex();
x4=new Complex();
36

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

x3=x1.add (x1,x2);
x4=x1.sub(x1,x2);
System.out.print("The first number :");
x1.display();
System.out.print("The second number :");
x2.display();
System.out.print("The sum :");
x3.display();
System.out.print("The difference :");
x4.display();
}
}
Output:
D:\java>javac CompNum.java
D:\java>java CompNum
The first number :(7,5)
The second number :(4,3)
The sum :(11,8)
The difference :(3,2)
Viva Questions:
What is a constructor?
Constructors are

special methods whose name is same

as the class name.

The

constructors do not return any value.


The constructors are automatically called when an object is created. They are usually
used to initialize the member variables.
What is a default constructor?
Constructor that does not take any argument is called default constructor.
What is meant by constructor overloading?
Defining more than one constructor for a class which differ in the number of arguments /
type of arguments or both is called constructor overloading

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Ex . No: 5 Inheritanceng.
Aim:
To write a java program to create a Player class and inherit three classes Cricket_Player,
Football_Palyer and Hockey_Player.
Algorithm:
1. Import the package java.io.*
2. Create a class player as a base class
3. Inherit Cricket,football,hockey classes from the player class.
Program
/* Hierarchical Inheritance */
/* Super class */
class Player
{
String name;
Player(String n) //Constructor
{
name=n;
}
void display()
{
System.out.println("Player name:"+name);
}
}
/*Sub class 1*/
class Cricket_Player extends Player
{
String pos;
Cricket_Player(String n,String s)
{
38

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

super(n); //Calling super class constructor


pos=s;
}
void print()
{
System.out.println("\n\n\tCricket Player");
display(); //Calling super class method
System.out.println("Category :"+pos);
}
}
/* Sub class 2 */
class Football_Player extends Player
{
String pos;
Football_Player(String n,String s)
{
super(n); //Calling super class constructor
pos=s;
}
void print()
{
System.out.println("\n\n\tFootball Player");
display(); //Calling super class method
System.out.println("Category :"+pos);
}
}
/* Sub class 3 */
class Hockey_Player extends Player
{
String pos;
Hockey_Player(String n,String s)
39

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

{
super(n); //Calling super class constructor
pos=s;
}
void print()
{
System.out.println("\n\n\tHockey Player");
display(); //Calling super class method
System.out.println("Category :"+pos);
}
}
/* Main class */
class DemoInher
{
public static void main(String args[])
{
Cricket_Player c=new Cricket_Player("Kumble","Bowler");
Football_Player f=new Football_Player("Anand","Football
receiver");
Hockey_Player h=new Hockey_Player("Parzan","Defence man");
c.print();
f.print();
h.print();
}
}
Output:
D:\java>javac DemoInher.java
D:\java>java DemoInher
Cricket Player
Player name:Kumble
Category :Bowler
40

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Football Player
Player name:Anand
Category :Football receiver
Hockey Player
Player name:Parzan
Category :Defence man
D:\java>
Viva Questions:
What is inheritance?
Inheritance is the process of deriving a new class from an existing class. The newly
created class is called sub class and the already existing class is called super class.
What are the types of inheritance?
Single inheritance: One super class and single sub class.
Multiple inheritance: More than one super class and single subclass.
Hierarchial inheritance: one super class and more than one subclass.
Multilevel inheritance : Deriving a sub class from another sub class
Explain multiple inheritance in java?
In java we can have only one super class for a sub class so we cannot directly implement
multiple inheritance. We use the concept of Interface which allows us to
extend more than one super class.
Syntax for deriving a sub class
class subclassName extends superclassname
{
//define the members
}

41

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Ex. No :6Packages
Aim:
To write a java program to create a package for Book details giving Book name, Author
name, price and year of publishing.
Program:
Step1:
Create a subdirectory inside the root directory which has the same name as the package
you are going to create.
D:\JAVA>md book
Step2:
Create the class of your package with the first statement as the package statement and
save the file with .java extension in the directory created.
/* BookDetails class in package Book */
package book;
public class BookDetails
{
String name,author;
float price;
int year;
public BookDetails(String n,String a,float p,int y)
{
name=n;
author=a;
price=p;
year=y;
}
public void display()
{
42

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

System.out.println("Book Name :"+name);


System.out.println("Book Author :"+author);
System.out.println("Book Price :Rs "+price);
System.out.println("Year of Publishing:"+year);
}
}
Step 3:
Compile the java file
D:\java>cd book
D:\java\book>javac BookDetails.java
Step 4:
Return to root directory
C:\javapgm\book>cd..
D:\JAVA >
Step 5:
In the main program import the created package into the program using the import
statement and key in the program where we can create instances of the classes in the package.
Save the program in the root directory
Main class:
/* Class that imports book package */
import book.*;
class BookDemo
{
public static void main(String args[])
{
BookDetails b=new BookDetails("Java Programming", "Balguruswamy",
190.00f, 2007);
b.display();
}
}

43

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Step 6:
Compile and execute the program.
Output:
D:\java>javac BookDemo.java
D:\java>java BookDemo
Book Name :Java Programming
Book Author :Balguruswamy
Book Price :Rs 190.0
Year of Publishing:2007
D:\java>
Viva questions:
What is package?
Package is a collection of interfaces and classes.
How a package can be created?
A package can be created using the package statement.
How a package can be imported into the program?
A package can be imported using the import statement.

44

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Ex. No :7Applets and AWT (Scroll bars)


Aim:
To write a java applet program to change the color of a rectangle using scroll bars to
change the value of red, green and blue.
Algorithm:
1. Import the package Java.awt.*,java.awt.event.*;
2. Create a class that extends Applet and implement Adjustment listener and mouse
motion listener
3. Create three scroll bars
4. Using the scrollbar select value and pass value as argument to the color class
5. Using the color selected draw and fill rectangle
Program:
/* Colour using Scroll bar */
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <applet code="Sbar.class" width=400 height=250 > </applet> */
public class Sbar extends Applet implements AdjustmentListener
{

Scrollbar red,green,blue;
Label l1,l2,l3;
Color col=Color.pink;
int r,g,b;
public void init()
{

setBackground(Color.white);
l1=new Label("Red");

l2=new Label("Green");

l3=new Label("Blue");
red=new Scrollbar(Scrollbar.HORIZONTAL,0,0,0,255);
green=new Scrollbar(Scrollbar.HORIZONTAL,0,0,0,255);
blue=new Scrollbar(Scrollbar.HORIZONTAL,0,0,0,255);
45

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

setLayout(new FlowLayout());
add(l1);

add(red);

add(l2);

add(green);

add(l3);

add (blue);

red.addAdjustmentListener(this);
green.addAdjustmentListener(this);
blue.addAdjustmentListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{

r=red.getValue();
g=green.getValue();
b=blue.getValue();
col=new Color(r,g,b);
repaint();

}
public void paint(Graphics g)
{

g.setColor(col);
g.fillRect(150,100,100,70);
showStatus("Adjust the Scroll bars to change the color of the
Rectangle");

}
}
Output

46

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Ex. No :8 Creating a Calculator using Applet

Aim :
To write an applet program for creating a simple calculator to perform Addition,
Subtraction, Multiplication and Division using Button, Label and TextField component.
Algorithm:
1. Import the package Java.awt.*, java.awt.event.*;
2. Create a class that extends Applet
3. Create two text boxes to enter number
4. Create check box group which contains add, sub, mul, div check boxes.
5. Create a OK button
6. Do the appropriate operations according to the selected check boxes

Program:
/* Calculator using applet */
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <applet code="calci.class" width=400 height=250 > </applet> */

47

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

public class calci extends Applet implements ActionListener


{
String num[]={"1","2","3","4","5","6","7","8","9",".","0","C"};
String opt[]={"+","-","*","/","="};
Button b1[],b2[];
Panel numpan,oprpan,butpan;
TextField tf=new TextField(20);
double reg1,reg2;
String text,operator;
boolean isNew;
public void init()
{
numpan=new Panel();
numpan.setLayout(new GridLayout(4,3));
b1=new Button[12];
for(int i=0;i<12;i++) //Creating number buttons
{
b1[i]=new Button(num[i]);
numpan.add(b1[i]);
}
oprpan=new Panel();
oprpan.setLayout(new GridLayout(5,1));
b2=new Button[5];
for(int i=0;i<5;i++) //Creating operator buttons
{
b2[i]=new Button(opt[i]);
oprpan.add(b2[i]);
}
setLayout(new BorderLayout());
butpan=new Panel(new GridLayout(1,2));
butpan.add(numpan);
48

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

butpan.add(oprpan);
add("North",tf);
add("Center",butpan);
reg1=reg2=0.0;
operator=" ";
tf.setText("0");
isNew=true;
for(int i=0;i<12;i++) //Registering the Listeners
b1[i].addActionListener(this);
for(int i=0;i<5;i++)
b2[i].addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String cmd=e.getActionCommand();
if(cmd.equals("C")) // Clearing the registers
{
reg1=0.0;
reg2=0.0;
operator="";
tf.setText("0");
isNew=true;
}
else if(isNumber(cmd))
{
if(isNew)
text=cmd;
else
text=tf.getText()+cmd;
tf.setText(text);
isNew=false;
49

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

}
else if(isOperator(cmd))
{
String val=tf.getText();
reg2=Double.parseDouble(val);
reg1=calculation(operator,reg1,reg2);
Double temp=new Double(reg1);
text=temp.toString();
tf.setText(text);
operator=cmd;
isNew=true;
}
}
/*Method to check whether the button pressed is a number*/
boolean isNumber(String s)
{
for(int i=0;i<11;i++)
{
if (s.equals(num[i]) )
return true;
}
return false;
}
/*Method to check whether the button pressed is a operator*/
boolean isOperator(String s)
{
for(int i=0;i<5;i++)
{
if (s.equals(opt[i]) )
return true;
}
50

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

return false;
}
/*Method to perform calculation and return the value*/
double calculation(String op,double r1,double r2)
{
if (op.equals("+"))
reg1=reg1+reg2;
else if (op.equals("-"))
reg1=reg1-reg2;
else if (op.equals("*"))
reg1=reg1*reg2;
else if (op.equals("/"))
reg1=reg1/reg2;
else
reg1=reg2;
return reg1;
}
}
Output:

51

examkey.wordpress.com
LAB

Ex. No :9

25245 - JAVA PROGRAMMING

To draw a bar chart using Applet

Aim :
To write an applet program to draw a bar chart for the following details:

Algorithm:
1. Import the package Java.awt.*, java.awt.event.*;
2. Write the Applet within comment tag in that pass some argument
3. Create a class that extends Applet
4. Draw the bar chart by using the value received by the argument

Program:
Applet Program:
/* Applet to draw a bar chart */
import java.applet.* ;
import java.awt.*;
public class BarChart extends Applet
52

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

{
int n=0;
String label[];
int value[];
public void init()
{
try
{
n= Integer.parseInt(getParameter("columns"));
label= new String[n];
value= new int[n];
label[0]= getParameter("label1");
label[1]= getParameter("label2");
label[2]= getParameter("label3");
label[3]= getParameter("label4");
value[0]= Integer.parseInt(getParameter("m1"));
value[1]= Integer.parseInt(getParameter("m2"));
value[2]= Integer.parseInt(getParameter("m3"));
value[3]= Integer.parseInt(getParameter("m4"));
}
catch(NumberFormatException e)
{
}
}
public void paint(Graphics g)
{
String msg=label[0];
for(int i=0;i<n;i++)
{
g.setColor(Color.red);
g.drawLine(100,50,100,350);
53

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

g.drawLine(100,350,300,350);
g.setColor(Color.blue);
g.drawString(label[i],40,145+(50*i));
g.setColor(Color.green);
g.fillRect(100,125+(50*i),value[i] ,30);
showStatus("Bar chart Applet");
}
}
}

HTML files to pass parameter:


<HTML>
<BODY>
<APPLET CODE="BarChart.class" HEIGHT=400 WIDTH=500>
<PARAM name="columns" VALUE=4>
<PARAM name="label1" VALUE="Tamil">
<PARAM name="label2" VALUE="English">
<PARAM name="label3" VALUE="Maths">
<PARAM name="label4" VALUE="Physics">
<PARAM name="m1" VALUE="78">
<PARAM name="m2" VALUE="85">
<PARAM name="m3" VALUE="98">
<PARAM name="m4" VALUE="56">
</APPLET>
</BODY>
</HTML>
Output:

54

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Viva Questions:
What is an applet?
Applet is a small interactive java programs that are used for web application.
What are the two packages that are needed to create an applet?
Java.awt and java.applet
What is an applet tag?
Applet tag is an HTML tag that is used to run the java applets.
What is an event?
Events is an interruption given to the running program using input devices such
as mouse, keyboard etc.
What package is needed to handle an event?
java.awt.event
What is the purpose of Scrollbar class?
Scroll bars provide a user interface that is used to scroll through a range of
integer values and also provide methods to read and set these values.
What are the steps needed to handle the event?
1. Import java.awt.event
2. Implement the corresponding Event Listener interfaces
3. Register the Event Listeners with the event source.
4. Override the appropriate methods of the listener interfaces.

examkey.wordpress.com

25245 - JAVA PROGRAMMING LAB

Ex. No :10 Multithreading (Thread to generate even


&oddnumber)

Aim:
To write a java program for generating two threads, one for generating even number and
one for generating odd number.
Algorithm:
1. Create the classes even,odd that extends Thread
2. Even Thread class is used to print even number
3. Odd Thread class is used to print odd number
4. In the main program start two thread
Program:
class even extends Thread
{
public void run()
{
for(int i=0;i<=10;i+=2)
{
System.out.println("Even numbers"+i);
}
}
}

56

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

class odd extends Thread


{
public void run()
{
for(int i=1;i<=10;i+=2)
{
System.out.println("Odd numbers"+i);
}
}
}
class mt
{
public static void main(String args[])
{
even e=new even();
odd o=new odd();
e.start();
o.start();
}
}
Output:
Even numbers0
Odd numbers1
Even numbers2
Odd numbers3
Even numbers4
Odd numbers5
Even numbers6
Odd numbers7
Even numbers8
Odd numbers9
Even numbers10
57

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

Viva Questions:
What is thread?
A thread is a single sequential flow of control within a program.
What is multithreading?
Multithreading is the process of running more than one thread at a time.
What are the two ways of creating thread?
A thread can be created by extending Thread class or implementing Runnable
interface.
What are the steps in creating and running thread?
Declare a class that extends Thread class.
Implement the run( ) method that is responsible for executing the sequence of
code that the thread will execute.
Create a thread object in the main class and call the start( ) method to initiate
execution.

58

examkey.wordpress.com
LAB

25245 - JAVA PROGRAMMING

What is meant by a synchronization?


In multithreaded application, multiple threads might access the data and call methods
simultaneously and this may create problems such as violation of data and unpredictable result.
These problems are referred to as concurrency problems.
Synchronization is the technique that can be used to overcome the concurrency problem
that may arise when two or more threads need to access the shared resources.
Java uses the concept of semaphores (also called monitors) for synchronization. This is
similar to a lock. Whenever a thread is making an attempt to use shared resources, it will lock the
resource (if it is free) and then after using, it will release (open the lock ) the resource.
The keyword synchronized in Java is used for synchronization. This keyword can be used
in two ways ie., a method can synchronized or a block of code can be synchronized.

What is the use of wait and notify methods?


The wait() method is used to move the thread from running state to blocked state. The
notify() method is used to move the thread from blocked state to ready to run state.

***********ALL THE BEST************

59