0% found this document useful (0 votes)
25 views34 pages

Java Programming Lab Manual for MCA

This document is a lab manual for a Java programming course at SRM Institute of Science and Technology, detailing various exercises. Each exercise includes an aim, algorithm, and coding example for tasks such as displaying messages, performing arithmetic operations, sorting, and using classes and methods. The manual serves as a guide for students to practice and implement Java programming concepts.

Uploaded by

318Giri Prasad C
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views34 pages

Java Programming Lab Manual for MCA

This document is a lab manual for a Java programming course at SRM Institute of Science and Technology, detailing various exercises. Each exercise includes an aim, algorithm, and coding example for tasks such as displaying messages, performing arithmetic operations, sorting, and using classes and methods. The manual serves as a guide for students to practice and implement Java programming concepts.

Uploaded by

318Giri Prasad C
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SRM INSTITUTE OF SCIENCE AND TECHNOLOGY, VADAPALANI,

CHENNAI

LAB MANUAL

Course Code : PCA20C01J


Course Name: PROGRAMMING USING JAVA
Department : MCA
YEAR : I
FACULTY INCHARGE : Dr S MURUGANANDAM

Lab Manual for JAVA PROGRAMMING – MCA Page 1


Exercise 1: Program to display “Welcome to JAVA”
Aim :
Write JAVA program to display the welcome message as
Welcome to JAVA
Algorithm:
Step 1: Create a main class, MyClass
Step 2: Include the built in method in the main() method to display
Welcome to Java
CODING
public class MyClass
{
public static void main(String args[])
{

[Link]("Welcome to JAVA");
}
}
Exercise 2: Program to perform arithmetic operations
Aim :
Write JAVA program to do all arithmetic operations

Lab Manual for JAVA PROGRAMMING – MCA Page 2


Algorithm:
Step 1: Create a main class, MyClass
Step 2: Get the operands A and B
Step 3: Calculate C= A + B
Calculate D= A – B
Calculate E= A * B
Calculate F= A / B
Calculate G= A % B
Step 4: Display C,D,E, F and G
CODING
import [Link].*;
public class MyClass
{
public static void main(String args[])
{

int a,b,c,d,e,g;
float f;
Scanner S=new Scanner([Link]);
a=[Link]();
b=[Link]();

Lab Manual for JAVA PROGRAMMING – MCA Page 3


c=a+b;
d=a-b;
e=a*b;
f=(float)a/b;
g=a%b;
[Link]("A + B"+c);
[Link]("A - B"+d);
[Link]("A * B"+e);
[Link]("A / B"+f);
[Link]("A % B"+g);
[Link]("A + B"+c);
}
}
Exercise 3: PRIME NUMBERS
Aim :
Write JAVA program to do display prime numbers between 1 to 100
Algorithm:
Step 1: Create a main class, MyClass
Step 2: for i = 1 to 100
{
Prime = 1

Lab Manual for JAVA PROGRAMMING – MCA Page 4


For (j = 2 to I – 1)
If (i%j==0) Prime=0;
If (Prime =1) print I
}
CODING
import [Link].*;
public class MyClass
{
public static void main(String args[])
{

int i,j,prime;
for(i=1;i<=100;i++)
{
prime=1;
for(j=2;j<=i-1;j++)
if(i%j==0)prime=0;
if (prime==1)[Link](" "+i);
}
}
}

Lab Manual for JAVA PROGRAMMING – MCA Page 5


Exercise 4: MULTIPLICATION TABLE
Aim :
Write JAVA program to display the multiplication table of ‘n’
Algorithm:
Step 1: Create a main class, MyClass
Step 2: Get the value of n
Step 3: for I = 1 to n
Print I, ‘X’,n,’=’,I*n
CODING
import [Link].*;
public class MyClass
{
public static void main(String args[])
{

int i,n;
for(i=1;i<=100;i++)
{
Scanner S=new Scanner([Link]);
n=[Link]();
for (i=1;i<=15;i++)

Lab Manual for JAVA PROGRAMMING – MCA Page 6


[Link](i+" X "+n+" = "+(i*n));
}
}
}
Exercise 5: PATTERN DISPLAY
Aim :
Write JAVA program to display the following output
*
* *
* * *
* * * * (upto n rows)
Algorithm:
Step 1: Create a main class, MyClass
Step 2: Get the value of n
Step 3: for i = 1 to n
For j=1 to I Print ‘*’
CODING
import [Link].*;
public class MyClass
{
public static void main(String args[])

Lab Manual for JAVA PROGRAMMING – MCA Page 7


{
int i,j,n;
Scanner S=new Scanner([Link]);
n=[Link]();
for (i=1;i<=n;i++)
{
[Link](" ");
for(j=1;j<=i;j++)
[Link]("*\t");
}
}
}
Exercise 6: BUBBLE SORTING
Aim :
Write JAVA program to sort ‘n’ numbers using bubble sort
Algorithm:
Step 1: Create a main class, MyClass
Step 2: Get the value of n
Step 3: Get the elements of un sorted array A [ 0.. n-1 ] to sort
Step 4 : for I = 1 to n-2
For j=i+1 to n-1

Lab Manual for JAVA PROGRAMMING – MCA Page 8


If (A[i] > A[j]) then
Swap(A[i],A[j])
Step 5: Display the elements of the array

CODING
import [Link].*;
public class MyClass
{
public static void main(String args[])
{
int i,j,t,n;
int A[]=new int[20];
Scanner S=new Scanner([Link]);
n=[Link]();
[Link]("\n Enter the elements of array to sort");
for (i=0;i<=n-1;i++)A[i]=[Link]();
for(i=0;i<=n-2;i++)
for(j=i+1;j<=n-1;j++)
if (A[i]>A[j])
{
t=A[i];

Lab Manual for JAVA PROGRAMMING – MCA Page 9


A[i]=A[j];
A[j]=t;
}
[Link](" The sorted elements are.... ");
for(i=0;i<=n-1;i++)[Link](A[i]+"\t");
}
}
Exercise 7: CLASS and OBJECT
Aim :
Write JAVA program to calculate Simple Interest using class
Algorithm:

Step 1: Create a class, SIMPLE


Step 2: Declare the data members p,n,r and si
Step 3: Include the following methods:
get() – for getting p,n and r
calculate( ) – Calculate si=(p*n*r)/100
put() – display the value of si
Step 4 : Create the Main class,MainClass
Step 5: Create the object for SIMPLE
Step 6: call the methods, get(), calculate() and put()

Lab Manual for JAVA PROGRAMMING – MCA Page 10


CODING
import [Link].*;
class SIMPLE
{
float p,r,si;
int n;

public void get()


{
Scanner S=new Scanner([Link]);
p=[Link]();
n=[Link]();
r=[Link]();
}
public void calculate()
{
si=(p*n*r)/100;
}
public void put()
{

Lab Manual for JAVA PROGRAMMING – MCA Page 11


[Link](" The Simple Interest is Rs"+si);
}
}
public class MyClass
{
public static void main(String args[])
{

SIMPLE ob=new SIMPLE();


[Link]();
[Link]();
[Link]();
}
}
Exercise 8: METHOD OVERLOADING
Aim :
Write JAVA program to demonstrate method overloading
Algorithm:

Step 1: Create a class, SAMPLE


Step 2: Include the following methods:

Lab Manual for JAVA PROGRAMMING – MCA Page 12


area(radius) – To find area of the circle ( ∏ r 2 )
area(side) – To find area of the square ( Side * side )
area(length,breadth) – To find area of the rectangle ( length * breadth)
Step 4 : Create the Main class,MainClass
Step 5: Create the object for SAMPLE
Step 6: call the methods to calculate areas of different shapes

CODING
import [Link].*;
class SAMPLE
{
void area(int r)
{
[Link](" AREA OF THE CIRCLE "+(3.14*r*r));
}
void area(float s)
{
[Link](" AREA OF THE SQUARE "+(s*s));
}
void area(float l,float b)
{

Lab Manual for JAVA PROGRAMMING – MCA Page 13


[Link](" AREA OF THE RECTANGLE "+(l*b));
}
}
public class MyClass
{
public static void main(String args[])
{

SAMPLE ob=new SAMPLE();


[Link](10);
[Link](7.5f);
[Link](11,15);
}
}
Exercise 9: CONSTRUCTOR OVERLOADING
Aim :
Write JAVA program to demonstrate constructor overloading
Algorithm:

Step 1: Create a class, SAMPLE


Step 2: Include the data members a,b and c

Lab Manual for JAVA PROGRAMMING – MCA Page 14


Step 3: Include the following constructors:
SAMPLE(x) – Assign , a=x, b=1.0f and c=’*’
SAMPLE(x,y) – Assign , a=x, b=y and c=’#’
SAMPLE(x,y,z) – Assign , a=x, b=y and c=z
Step 4: Include method display() to display the data members
Step 5 : Create the Main class,MainClass
Step 6: Create the objects for SAMPLE for three constructors
Step 7: Call display methods
CODING
class SAMPLE
{
int a;
float b;
char c;
SAMPLE(int x)
{
a=x;
b=1.0f;
c='*';
}
SAMPLE(int x,float y)

Lab Manual for JAVA PROGRAMMING – MCA Page 15


{
a=x;
b=y;
c='#';
}
SAMPLE(int x,float y,char z)
{
a=x;
b=y;
c=z;
}
void display()
{
[Link](" A = "+a+" B = "+b+" C= "+c);
}
void area(float l,float b)
{
[Link](" AREA OF THE RECTANGLE "+(l*b));
}
}
public class MyClass

Lab Manual for JAVA PROGRAMMING – MCA Page 16


{
public static void main(String args[])
{

SAMPLE ob1=new SAMPLE(1);


SAMPLE ob2=new SAMPLE(10,20.50f);
SAMPLE ob3=new SAMPLE(100,200.50f,'%');
[Link]();
[Link]();
[Link]();
}
}
Exercise 10: USING STRING CLASS FOR ALPHABETICAL ORDER
Aim :
Write JAVA program to demonstrate do alphabetical order
Algorithm:
Step 1 : Create the Main class,MainClass
Step 2: Get the value of ‘n’
Step 3: Create an array of strings for getting names with String class
Step 4: Get the unsorted names
Step 5: Sort the names

Lab Manual for JAVA PROGRAMMING – MCA Page 17


Step 6: Display the names
Coding:
import [Link].*;
public class Main
{
public static void main(String args[])
{
Scanner S=new Scanner([Link]);
String names[]=new String[20];
String t;
int i,j,n;
n=[Link]();
for(i=0;i<=n-1;i++)
{
names[i]=[Link]();
}
for(i=0;i<=n-2;i++)
for(j=i+1;j<=n-1;j++)
if(names[i].compareTo(names[j])>0)
{
t=names[i];

Lab Manual for JAVA PROGRAMMING – MCA Page 18


names[i]=names[j];
names[j]=t;
}
[Link]("The Sorted Names are");
for(i=0;i<=n-1;i++)[Link](names[i]+" ");
}
}
Exercise 11: COMMAND LINE ARGUMENTS
Aim :
Write JAVA program to get the input in command line argument to find the average of marks of a students
Algorithm:
Step 1 : Create the Main class,Main
Step 2: Get the value of name,regno and marks of three subjects (m1,m2 and m3) using command arguments
Step 3: Find the average , average= (m1+m2+m3) / 3
Step 4: Display the data
CODING
public class Main
{
public static void main(String args[])
{
String name,regno;

Lab Manual for JAVA PROGRAMMING – MCA Page 19


int m1,m2,m3;
float avg;
name=args[0];
regno=args[1];
m1=[Link](args[2]);
m2=[Link](args[3]);
m3=[Link](args[4]);
avg=(float)(m1+m2+m3)/3;
[Link](" Average Marks is"+avg);
}
}
Exercise 12: METHOD OVERRDIDING
Aim :
Write JAVA program to create two threads for displaying odd and even numbers
Algorithm:
Step 1 : Create a class Animal with a method , display()
Step 2: Create another class Tiger with a method , display() inheriting the Animal class
Step 3: Create main class, Main
Step 4: Create an object for Tiger class
Step 5: Call the method display() with the references of the object of Tiger class
CODING

Lab Manual for JAVA PROGRAMMING – MCA Page 20


class Animal
{
void display()
{
[Link](“ I am an Animal “);
}
}
class Tiger extends Animal
{
void display()
{
[Link](“ I am a Tiger “);
}
}
class Demo
{
public static void main(String aa[])
{
Tiger T = new Tiger();
[Link]();
}

Lab Manual for JAVA PROGRAMMING – MCA Page 21


}
Exercise 13: ABSTRACT CLASS
Aim :
Write JAVA program to demonstrate abstract
Algorithm:
Step 1 : Create an abstract class shape. Make it as a super class
Step 2: Include an abstract nethod, Area() and a non abstract method display()
Step 3 : Create the sub classes for circle,rectangle and triangle by inheritance and specify the body of the abstract methods
Step 3: Create main class, Main
Step 4: Create an object for any of the sub class
Step 5: Call the method area() with the references of the object of Tiger class and the parameters
CODING
abstract class shape
{ float a=3.0f,b=4.0f;
void display()
{
[Link](“ Abstract Class”);
}
abstract public void Area();
}
class rectangle extends shape
{
public float AR;
public void Area()
{
AR=a*b;

Lab Manual for JAVA PROGRAMMING – MCA Page 22


[Link]("The area of rectangle is:"+AR);
}
}
class triangle extends shape
{
float AT;
public void Area()
{
AT=0.5*a*b;
[Link]("The area of triangle is:"+AT);
}
}
class circle extends shape
{
float AC;

public void Area()


{
AC=3.14*a*a;
[Link]("The area of circle is:"+AC);
}
}
public class Demo
{
public static void main(String[] args)
{
rectangle r=new rectangle();
[Link]();
triangle t=new triangle();
[Link]();
circle r1=new circle();
[Link]();
}

Lab Manual for JAVA PROGRAMMING – MCA Page 23


}

Exercise 14: MULTITHREDAING


Aim :
Write JAVA program to create two threads for displaying odd and even numbers
Algorithm:
Step 1 : Create a Thread class Odd for displaying odd number
Step 2: Create a Thread class Even for displaying even number
Step 3: Create main class, Main
Step 4: Create the objects for Odd and Even classes
Step 5: Call the method start() with the references of the objects of Odd and Even

CODING
class odd extends Thread
{
public void run()
{
for(int i=1;i<=25;i=i+2)[Link](" Odd "+i);
}
}
class even extends Thread

Lab Manual for JAVA PROGRAMMING – MCA Page 24


{
public void run()
{
for(int i=50;i<=75;i=i+2)[Link](" Even "+i);
}
}
public class Main
{
public static void main(String args[])
{
odd t1=new odd();
even t2=new even();
[Link]();
[Link]();
}
}

Exercise: 15 INTERFACE
Aim :
Write JAVA program to demonstrate INTERFACE

Lab Manual for JAVA PROGRAMMING – MCA Page 25


Algorithm:
Step 1 : Create an interface Shape consisting of an abstract method DisplayArea( ) and a final data member PI.
Step 2: The Shape interface is implemented in the classes such as Circle, Rectangle and Square.
Step 3: Implement DisplayArea()according to the formula used for finding the area for various shapes (Circle, Rectangle and Square).
Area Circle = PI * r * r [r-radius]
Area of Rectangle = l * b [ l-length and b-breadth]
Area of Square = a * a [a is the side ]
Step 4: Create main class, Main
Step 5: Create the objects for the as Circle, Rectangle and Square.

Step 5: Call the methods Area() with the parameters


CODING
import [Link].*;
interface shape
{
final float PI=3.1417f;
abstract void DisplayArea();
}
class Circle implements shape
{
float r,A;

Lab Manual for JAVA PROGRAMMING – MCA Page 26


public void DisplayArea()
{
Scanner S=new Scanner([Link]);
}
}
class DemoInterface
{
public static void main(String aa[])
{
Circle C = new Circle();
[Link]();
Square S = new Square();
[Link]();
Rectangle R = new Rectangle();
[Link]();
}
}
Exercise: 16 EXCEPTIONS
Aim :
Write JAVA program to create our own exception
Algorithm:

Lab Manual for JAVA PROGRAMMING – MCA Page 27


Step 1 : Create a class MyException by extending Thread class
Step 2: Include the constructor
Step 3: Create a main class DemoException and include a function check() whether an element is present inside the array or not by throwing our own
exception MyException
Step 4: Call the method check() with an array and element to be checked
CODING
class MyException extends Exception
{
MyException(String s)
{
Super(s);
}
}
Class DemoException
{
static void check(int a[ ],int e) throws MyException
{
boolean found=false;
for(int i=0;i<[Link];i++)
if (a[i]==e) found=true;
if(!found) throw new MyException(“ Element is not found”);
else

Lab Manual for JAVA PROGRAMMING – MCA Page 28


[Link](“\n Element is present “);
}
public static void main(String aa[ ])
{
int [ ] a [ ] = {10, 15, 20, 35, 40 };
try
{
check(a,25);
}
catch(MyException e)
{
[Link]( “Caught :”+e );
}
}
}

Exercise: 17 EVENT HANDLING


Aim :
Write JAVA program to demonstrate event handling
Algorithm:
Step 1 : Create a class AEvent implementing ActionListener interface

Lab Manual for JAVA PROGRAMMING – MCA Page 29


Step 2: Create the objects for TextField and Button
Step 3: Add the objects into the layout
Step 4: Include the method for actionPerformed()
CODING
import [Link].*;
import [Link].*;
class AEvent extends Frame implements ActionListener
{
TextField t;
AEvent()
{
t=new TextField();
[Link](60,50,170,20);
Button b=new Button(“Click Me”);
[Link](100,120,80,30);
[Link](this);
add(t);
add(b);
setSize(300,300);
setLayout(null);
setVisible(true);

Lab Manual for JAVA PROGRAMMING – MCA Page 30


}
public void actionPerformed(ActionEvent e)
{
[Link](“Welcome”);
}
public static void main(String a[])
{
new AEvent();
}
}

Exercise: 18 UTILITY CLASSES


Aim :
Write JAVA program to create a vector and to implement various methods
Algorithm:
Step 1 : Create an object for Vector class [ vector class is for a type of data structure that maintains insertion order, that is elements are retrieved in same
order as they are added into it. It is very much similar to ArrayList].
Step 2: Add the elements into the vector by calling methods add()
Step 3: Create an object for generic Vector
Step 4: Add the elements into the vector by calling methods add()
Step 5 : Display the elements of both the vectors
CODING

Lab Manual for JAVA PROGRAMMING – MCA Page 31


import [Link].*;
import [Link].*;
class AddElementsToVector
{
public static void main(String[] arg)
{
// create default vector
Vector v1 = new Vector();
// Add elements using add() method
[Link](1);
[Link](2);
[Link](“Java");
[Link]("forAll");
[Link](3);
// print the vector to the console
[Link]("Vector v1 is " + v1);
// create generic vector
Vector<Integer> v2 = new Vector<Integer>();
[Link](1);
[Link](2);
[Link](3);

Lab Manual for JAVA PROGRAMMING – MCA Page 32


[Link]("Vector v2 is " + v2);
}
}
Exercise: 19 CHARACTER STREAMS
Aim :
Write JAVA program to copy the content of a text file to another text file
Algorithm:
Step 1 : Open the input file “[Link]” by creating the object for FileInputStream
Step 2: Open the input file “[Link]” by creating the object for FileOutputStream
Step 3: Do the steps 3.1 to 3.2 until the input file is end
Step 3.1 : Read a character C from the input file
Step 3.2 : Write the character C into the output file

import [Link].*;
CODING
class StreamDemo1
{
public static void main(String aa[ ] )
{
FileInputStream fis=new FileInputStream(“[Link]”);
FileOutputStream fos=new FileOutputStream(“[Link]”);

Lab Manual for JAVA PROGRAMMING – MCA Page 33


int c;
While( (c=[Link]()) !=-1) [Link](c);
[Link]();
[Link]();
}
}

Lab Manual for JAVA PROGRAMMING – MCA Page 34

Common questions

Powered by AI

Event handling in Java detects and manages user interactions in GUI applications. It involves listening for events and responding accordingly. The lab manual demonstrates this using a button click event, where pressing a button updates a text field. This model separates GUI from logic, enhancing modularity and responsiveness in applications .

The bubble sort algorithm is easy to implement and understand due to its simple comparison and swapping operations. However, its time complexity is O(n²) in the average and worst case, which makes it inefficient for large datasets. It repeatedly traverses the list and swaps adjacent elements, leading to high computational cost. For better performance with large datasets, more efficient algorithms like quicksort or mergesort (O(n log n) complexity) are preferable .

Command line arguments allow users to pass information into the program at runtime, making it dynamic. For example, in the lab manual, a program calculates the average of three marks by reading values inputted as command line arguments, allowing users to specify different inputs without changing the program code .

Encapsulation is demonstrated by defining class 'SIMPLE' with private variables for principal, time, rate, and interest, exposing only required methods to manipulate these variables, like 'get' for input, 'calculate' for processing, and 'put' for output. This prevents unauthorized access or modification. Encapsulation is crucial for maintaining object integrity and simplifying control over data and operations .

Multithreading allows concurrent execution of two or more threads, potentially improving program performance by better CPU utilization. The lab manual demonstrates this with classes for odd and even numbers running concurrently. However, challenges include managing thread synchronization and avoiding issues such as deadlocks and race conditions, which can arise from concurrent thread access to shared resources .

The String class in Java provides a convenient way to handle and manipulate text, enabling efficient sorting of names using methods like 'compareTo'. The lab manual uses this for alphabetizing names. Challenges include potential performance issues with large datasets, as sorting operations may require additional memory and time. Furthermore, mismanaging mutable strings could toughen tracking changes or intents .

Exception handling in Java helps manage runtime errors, allowing a program to continue execution. Custom exceptions refine error management by enabling precise identification of specific conditions. For example, the lab manual demonstrates a custom exception ‘MyException’ for checking if an element exists in an array. If not found, the custom exception is thrown and caught, thereby providing a meaningful error message related to program logic rather than system-generated errors .

Method overloading allows different methods to share the same name but differ in parameters (number, type, or both), thereby enhancing code flexibility and reusability. For instance, in calculating the area of different shapes, you can create a class with multiple 'area' methods: one for the circle using the formula πr², another for the square with side², and a third for the rectangle using length × breadth. This way, the same method name 'area' is reused but behaves differently depending on the shape's parameters .

Interfaces define methods without implementations, acting as a contract for classes. They offer multiple inheritance capabilities. In the lab manual, the 'Shape' interface contains an abstract 'DisplayArea' method implemented differently across 'Circle', 'Rectangle', and 'Square', facilitating a common interface while allowing specific logic per shape. This abstraction supports consistency and flexibility across implementations .

Abstract classes in Java can have both complete implementations or abstract methods without a body. They are used when subclasses share common methods but also have specific behaviors. Interfaces, on the other hand, can only declare methods. Abstract classes may have states or fields, unlike interfaces. In the lab manual, an abstract class 'shape' defines a method 'Area()' and is extended by subclasses like 'rectangle,' 'triangle,' and 'circle,' each providing specific implementations for calculating area .

You might also like