0% found this document useful (0 votes)
103 views24 pages

Java Lab Manual for MCA I Sem

The document is a Java lab manual for MCA I semester, containing various programming exercises. It includes tasks such as demonstrating operator precedence, validating dates, generating Fibonacci series, and implementing object-oriented concepts like inheritance and exception handling. Each exercise is accompanied by example code and expected output.

Uploaded by

Sinchana
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)
103 views24 pages

Java Lab Manual for MCA I Sem

The document is a Java lab manual for MCA I semester, containing various programming exercises. It includes tasks such as demonstrating operator precedence, validating dates, generating Fibonacci series, and implementing object-oriented concepts like inheritance and exception handling. Each exercise is accompanied by example code and expected output.

Uploaded by

Sinchana
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

MCA I SEM - JAVA LAB MANUAL

PART A
1. Develop a JAVA program to demonstrate the precedence and
associativity among arithmetic operators. The program should also
demonstrate how the default precedence can be overridden.
import [Link];
public class OperatorPrecedence{
public static void main(String[] args){
int a,b,c;
[Link]("Enter values of a, b, c ");
Scanner sc = new Scanner([Link]);
a = [Link]();
b = [Link]();
c = [Link]();

int result1 = a + b * c;
int result2 = (a + b) * c;
int result3 = a / b * c;
int result4 = (a * b) / c;
int result5 = a - ++b - ++c;

[Link]("Result 1 is " +result1);


[Link]("Result 2 is " +result2);
[Link]("Result 3 is " +result3);
[Link]("Result 4 is " +result4);
[Link]("Result 5 is " +result5);
}
}

OUTPUT:
Enter values of a, b, c
4 5 6
Result 1 is 34
Result 2 is 54
Result 3 is 0
Result 4 is 3
Result 5 is -9

Radhika L 1
MCA I SEM - JAVA LAB MANUAL

2. Write a JAVA program to validate a date. The program should accept


day, month and year and it should report whether they form a valid date
or not.
import [Link].*;
public class DateValidator
{

public static boolean isLeapYear(int n)


{
if(n%400==0 || ( n%4==0 && n%100!=0))
{
return true;
}
else
return false;
}
public static void validate(int d, int m, int y)
{
int no_of_days=0;
if(m==1 || m==3 || m==5 || m==7 || m==8 || m==10 || m==12)
{
no_of_days=31;
}
else
{
if(m==4 || m==6 || m==9 || m==11)
{
no_of_days=30;
}
else
{
if(m==2)
{
if(isLeapYear(y))
{
no_of_days=29;
}
else
{
no_of_days=28;
}
}
}
}
if(d>=1 && d<=no_of_days)
{
[Link]("Entered date is valid........");
}
else
{

Radhika L 2
MCA I SEM - JAVA LAB MANUAL

[Link]("Enetered date is not valid.....");


}
}
public static void main(String[] args)
{
[Link]("Enter the date....");
Scanner sc =new Scanner([Link]);
int d = [Link]();
int m = [Link]();
int y = [Link]();

validate(d,m,y);
}
}

OUTPUT:
Enter the date....
29
2
2023
Entered date is not valid.....

Enter the date....


29
2
2024
Entered date is valid........

Radhika L 3
MCA I SEM - JAVA LAB MANUAL

3. Write a JAVA program to display the following pattern.


1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
public class NumberPattern
{
public static void main(String[] args)
{
int i,j,k;
for (i = 1; i <= 5; i++)
{
for(j = 5; j >= i; j--)
{
[Link](" ");
}
for(k = 1; k <= i; k++)
{
[Link](i + " ");
}
[Link]();
}
}
}

OUTPUT:
1
22
333
4444
55555

Radhika L 4
MCA I SEM - JAVA LAB MANUAL

4. Write a JAVA program to print the first n members of Fibonacci series.


import [Link];
public class Fibonacci
{
public static void main(String[] args)
{
int n, first=0, next=1;
[Link]("Enter how many fibonacci numbers to print");
Scanner sc = new Scanner([Link]);
n=[Link]();
[Link]("The first " + n + "Fibonacci numbers are: " );
[Link](first + " " + next);
for (int i = 1; i <= n-2; ++i)
{
int sum = first + next;
first = next;
next = sum;
[Link](" " + sum);
}
}
}

OUTPUT:
Enter how many fibonacci numbers to print
5
The first 5 Fibonacci numbers are: 0 1 1 2 3

Enter how many fibonacci numbers to print


10
The first 10 Fibonacci numbers are: 0 1 1 2 3 5 8 13 21 34

Radhika L 5
MCA I SEM - JAVA LAB MANUAL

5. Write a program to generate the multiplication tables of a range of


numbers between m and n inclusive and m < n.
import [Link];
public class MultiplicationTable
{
public static void main(String[] args)
{
int m, n;

Scanner sc =new Scanner([Link]);


[Link]("Enter value for m: ");
m = [Link]();
[Link]("Enter value for n: ");
n = [Link]();
if(m<n)
{
for (int i=m; i<=n; i++)
{
for(int j=1; j<=10; j++)
{
[Link](i + " * " + j + " = " + (i*j));
}
[Link]();
}
}
else
[Link]("m value should be less than n");
}

OUTPUT:
Enter value for m: 3
Enter value for n: 2
m value should be less than n

Enter value for m: 2


Enter value for n: 3
2*1=2 3*1=3
2*2=4 3*2=6
2*3=6 3*3=9
2*4=8 3 * 4 = 12
2 * 5 = 10 3 * 5 = 15
2 * 6 = 12 3 * 6 = 18
2 * 7 = 14 3 * 7 = 21
2 * 8 = 16 3 * 8 = 24
2 * 9 = 18 3 * 9 = 27
2 * 10 = 20 3 * 10 = 30

Radhika L 6
MCA I SEM - JAVA LAB MANUAL

6. Write a JAVA program to define a class, define instance methods for


setting and retrieving values of instance variables and instantiate its
object.
public class MyClass
{
private int value;

public void setValue(int value)


{
[Link] = value;
}

public int getValue()


{
return value;
}

public static void main(String[] args)


{
MyClass obj = new MyClass();

[Link](10);

int retrievedValue = [Link]();

[Link]("Retrieved Value: " + retrievedValue);


}
}

OUTPUT:
Retrieved Value: 10

Radhika L 7
MCA I SEM - JAVA LAB MANUAL

7. Write a JAVA program to demonstrate static member data and static


member methods
public class StaticDemo
{
static int count = 0;

static void incrementCount()


{
count++;
}
public static void main(String[] args)
{
[Link]("Initial count: " + [Link]);
[Link]();
[Link]("Count after increment: " + [Link]);
}
}

OUTPUT:
Initial count: 0
Count after increment: 1

Radhika L 8
MCA I SEM - JAVA LAB MANUAL

8. Write a JAVA Program to demonstrate nested classes


public class OuterClass
{
private int outerValue;
public OuterClass(int outerValue)
{
[Link] = outerValue;
}
public void outerMethod()
{
[Link]("Outer method is called");
}
public class InnerClass
{
public void innerMethod()
{
[Link]("Inner method is called");
[Link]("Outer value accessed from InnerClass: " +
outerValue);
outerMethod();
}
}
public static void main(String[] args)
{
OuterClass outerObj = new OuterClass(5);

[Link] innerObj = [Link] InnerClass();

[Link]();
}
}

OUTPUT:
Inner method is called
Outer value accessed from InnerClass: 5
Outer method is called

Radhika L 9
MCA I SEM - JAVA LAB MANUAL

9. Write a JAVA program to demonstrate dynamic method dispatch.


class Animal
{
public void makeSound()
{
[Link]("Animal makes a sound");
}
}
class Dog extends Animal
{
@Override
public void makeSound()
{
[Link]("Dog barks");
}
}
class Cat extends Animal
{
@Override
public void makeSound()
{
[Link]("Cat meows");
}
}
public class DynamicMethodDispatch
{
public static void main(String[] args)
{
Animal animal = new Animal();
Animal dog = new Dog();
Animal cat = new Cat();
[Link]();
[Link]();
[Link]();
}
}

OUTPUT:
Animal makes a sound
Dog barks
Cat meows

Radhika L 10
MCA I SEM - JAVA LAB MANUAL

10. Write a JAVA program to implement inheritance and demonstrate use


of method overriding.
class Animal
{
public void makeSound()
{
[Link]("Animal makes a sound");
}
}
class Dog extends Animal
{
@Override
public void makeSound()
{
[Link]("Dog barks");
}
}
class Cat extends Animal
{
@Override
public void makeSound()
{
[Link]("Cat meows");
}
}
public class InheritanceDemo
{
public static void main(String[] args)
{
Dog dog = new Dog();
Cat cat = new Cat();

[Link]();
[Link]();
}
}

OUTPUT:
Dog barks
Cat meows

Radhika L 11
MCA I SEM - JAVA LAB MANUAL

PART-B

11. Write a JAVA program to implement the concept of importing classes


from user defined packages and creating packages.
package myPackage;
public class MyClass
{
public void display()
{
[Link]("This is a class from myPackage");
}
}

import [Link];
public class ImportDemo
{
public static void main(String[] args)
{
MyClass obj = new MyClass();
[Link]();
}
}

OUTPUT:
This is a class from myPackage

Radhika L 12
MCA I SEM - JAVA LAB MANUAL

12. Write a program to demonstrate abstract class and abstract methods


abstract class Person
{
protected String name;
public Person(String name)
{
[Link] = name;
}
abstract void displayRole();
}
class Teacher extends Person
{
public Teacher(String name)
{
super(name);
}
void displayRole()
{
[Link](name + " is a Teacher");
}
}
class Student extends Person
{
public Student(String name)
{
super(name);
}
void displayRole()
{
[Link](name + " is a Student");
}
}
public class CollegeDemo{
public static void main(String[] args){
Person teacher = new Teacher("Mr. Smith");
[Link]();
Person student = new Student("Alice");
[Link]();
}
}

OUTPUT:
Mr. Smith is a Teacher
Alice is a Student

Radhika L 13
MCA I SEM - JAVA LAB MANUAL

13. Write a JAVA Program to implement an array of objects of a class.


class Student
{
private String name;
private int age;
public Student(String name, int age)
{
[Link] = name;
[Link] = age;
}
public void displayDetails()
{
[Link]("Name: " + name + ", Age: " + age);
}
}
public class ArrayOfObject
{
public static void main(String[] args)
{
Student[] students = new Student[3];
students[0] = new Student("Alice", 20);
students[1] = new Student("Bob", 22);
students[2] = new Student("Charlie", 19);
students[0].displayDetails();
students[1].displayDetails();
students[2].displayDetails();
}
}

OUTPUT:
Name: Alice, Age: 20
Name: Bob, Age: 22
Name: Charlie, Age: 19

Radhika L 14
MCA I SEM - JAVA LAB MANUAL

14. Write a JAVA program to demonstrate String class and its methods
public class StringMethod
{
public static void main(String[] args)
{
String str = "Hello, World!";
[Link]("Length of the string: " + [Link]());
[Link]("Character at index 7: " + [Link](7));
[Link]("Substring from index 7: " + [Link](7));
String anotherStr = " Welcome!";
[Link]("Concatenated string:" + [Link](anotherStr));
[Link]("Index of 'W': " + [Link]('W'));
[Link]("Contains 'World': " + [Link]("World"));
[Link]("Replaced'l' with 'p':" + [Link]('l', 'p'));
[Link]("Upper case: " + [Link]());
[Link]("Lower case: " + [Link]());
String str2 = "hello, world!";
[Link]("Is str equal to str2 (case-sensitive): " + [Link](str2));
[Link]("Is str equal to str2 (case-insensitive): " + [Link](str2));
}
}

OUTPUT:
Length of the string: 13
Character at index 7: W
Substring from index 7: World!
Concatenated string: Hello, World! Welcome!
Index of 'W': 7
Contains 'World': true
Replaced 'l' with 'p': Heppo, World!
Upper case: HELLO, WORLD!
Lower case: hello, world!
Is str equal to str2 (case-sensitive): false
Is str equal to str2 (case-insensitive): true

Radhika L 15
MCA I SEM - JAVA LAB MANUAL

15. Write a JAVA program to implement the concept of exception handling


by creating user defined exceptions.
class MyException extends Exception
{
public MyException(String s)
{
super(s);
}
}
public class UserException
{
public static void main(String args[])
{
int x = 5, y = 10;
try
{
int z = x / y;
if ( z < 1)
{
throw new MyException("Number is less than 1");
}
}
catch (MyException ex)
{
[Link]("Caught");
[Link]([Link]());
}
}
}

OUTPUT:
Caught
Number is less than 1

Radhika L 16
MCA I SEM - JAVA LAB MANUAL

16. Write a JAVA program using synchronized threads, which demonstrates


producer consumer concept.
class Producer extends Thread
{
Buffer b;
public Producer(Buffer br)
{
b = br;
}
public void run()
{
for(int i=1;i<=5;i++)
{
[Link](i);
[Link]("Produce value: " + i);
try
{
[Link](1000);
}
catch(Exception e){ }
}
}
}
class Buffer
{
int n;
boolean available = false;
public synchronized int consume()
{
while(available == false)
{
try
{
wait();
}
catch(Exception e){ }
}
available = false;
notifyAll();
return n;
}
public synchronized void produce(int value)
{
while(available == true)
{
try
{
wait();
}

Radhika L 17
MCA I SEM - JAVA LAB MANUAL

catch(Exception e){ }
}
n = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread
{
Buffer b;
public Consumer(Buffer br)
{
b=br;
}
public void run()
{
int value = 0;
for(int i=1;i<=5;i++)
{
value = [Link]();
[Link]("Consumed value: " + value);
}
}
}
public class Demo
{
public static void main(String[] args)
{
Buffer br = new Buffer();
Producer p1 = new Producer(br);
Consumer c1 = new Consumer(br);
[Link]();
[Link]();
}
}

OUTPUT:
Consumed value: 1
Produce value: 1
Consumed value: 2
Produce value: 2
Produce value: 3
Consumed value: 3
Produce value: 4
Consumed value: 4
Produce value: 5
Consumed value: 5

Radhika L 18
MCA I SEM - JAVA LAB MANUAL

Radhika L 19
MCA I SEM - JAVA LAB MANUAL

17. Write a JAVA program that creates three threads. First thread displays
“Good Morning” every one second, the second thread displays “Hello”
every two seconds and the third thread displays “Welcome” every three
seconds.
class MessagePrinter implements Runnable
{
private String message;
private int interval;
public MessagePrinter(String message, int interval)
{
[Link] = message;
[Link] = interval;
}
public void run()
{
try
{
while (true)
{
[Link](message);
[Link](interval);
}
}
catch (InterruptedException e)
{
[Link]().interrupt();
}
}
}
public class MultiThreadMessage
{
public static void main(String[] args)
{
Thread t1 = new Thread(new MessagePrinter("Good Morning", 1000));
Thread t2 = new Thread(new MessagePrinter("Hello", 2000));
Thread t3 = new Thread(new MessagePrinter("Welcome", 3000));
[Link]();
[Link]();
[Link]();
}
}
OUTPUT:
Good Morning
Hello
Welcome
Good Morning
Hello
Good Morning

Radhika L 20
MCA I SEM - JAVA LAB MANUAL

Welcome
Good Morning
Hello
Good Morning
Good Morning
Welcome
Hello

Radhika L 21
MCA I SEM - JAVA LAB MANUAL

18. Write a JAVA program which uses FileInputStream / FileOutPutStream


Classes.
import [Link];
import [Link];
import [Link];
import [Link];
public class FileInputStreamExample
{
public static void main(String[] args) throws IOException
{
File f1 = new File("/Users/radhikaladagi/Documents/JAVA/[Link]");
FileInputStream s1 = new FileInputStream(f1);
byte bytes[] = new byte[(int) [Link]()];

int numOfBytes = [Link](bytes);

[Link]("Data Copied Successfully");

File f2 = new File("/Users/radhikaladagi/Documents/JAVA/[Link]");


FileOutputStream s2 = new FileOutputStream(f2);
[Link](bytes);
[Link]("Data Written Successfully");
}
}

OUTPUT:
Data Copied Successfully
Dta Written Successfully

Radhika L 22
MCA I SEM - JAVA LAB MANUAL

19. Write a JAVA program to list all the files in a directory including the
files present in all its subdirectories.
import [Link];
import [Link];
public class ListOfFiles
{
public static void main(String[] args) throws IOException
{
File f1 = new File("/Users/radhikaladagi/Documents/New");

File list[] = [Link]();

String contents[] = [Link]();


[Link]("List of files and directories in the specified directory:");
for(File file :list)
{
[Link]("File name:" + [Link]());
[Link]("File path:" + [Link]());
[Link]();
}
}
}

OUTPUT:
List of files and directories in the specified directory:
File name:Untitled [Link]
File path:/Users/radhikaladagi/Documents/New/Untitled [Link]
File name:[Link]
File path:/Users/radhikaladagi/Documents/New/[Link]
File name:[Link]
File path:/Users/radhikaladagi/Documents/New/[Link]

Radhika L 23
MCA I SEM - JAVA LAB MANUAL

20. Write a JAVA program to demonstrate the life cycle of an applet.


import java. applet.*;
import java. awt.*;
import [Link];
/*<applet code="[Link]" width="350" height="350"></applet>*/
public class AppletLifeCycle extends Applet
{
String s;
public void init()
{
setBackground([Link]);
s = "Welcome to Java Applet";
[Link]("init() is called......");
}
public void start()
{
[Link]("start() is called......");
}
public void paint(Graphics g)
{
[Link]([Link]);
[Link](s, 50, 50);
}
public void stop()
{
[Link]("stop() is called......");
}
public void destroy()
{
[Link]("destroy() is called......");
}
}

Radhika L 24

Common questions

Powered by AI

A Java applet's life cycle comprises several stages: initialization ('init'), starting ('start'), painting ('paint'), stopping ('stop'), and destruction ('destroy'). The 'AppletLifeCycle' example in Source 6 illustrates these with corresponding methods. 'init' sets up initial state; 'start' begins or resumes after pausing; 'paint' handles rendering, called whenever the applet refreshes; 'stop' halts periodic actions upon user exit from the page; and 'destroy' cleans resources before permanent shutdown. Each stage has specific roles, ensuring the applet manages its execution state efficiently across various interactions.

User-defined packages in Java organize classes and interfaces into namespaces, preventing naming conflicts and improving modularity. In Source 4, 'myPackage' contains 'MyClass', which is then imported into another program using the 'import' keyword. This setup allows structured code maintenance, logical grouping of classes with related functionality, and controlled access. It promotes code reusability and encapsulation by providing a clear framework for managing large codebases, making collaborative development and application scaling more effective and manageable.

In Java, operator precedence determines the order in which operators are evaluated in expressions. By default, multiplication and division have higher precedence than addition and subtraction. The given program in Source 1 demonstrates this by evaluating expressions with different operator arrangements: 'a + b * c' uses default precedence, resulting in the multiplication of 'b * c' being performed first. To override precedence, you can use parentheses, e.g., '(a + b) * c', which forces addition to happen first. This is shown by different results in 'result1' and 'result2', indicating the impact of default and overridden precedence.

Nested classes in Java, specifically non-static inner classes, allow access to all fields and methods of their enclosing class, enabling encapsulation and reduced namespace pollution. The 'OuterClass' and 'InnerClass' in Source 3 exemplify this interaction. 'InnerClass' accesses 'outerValue' directly and can call 'outerMethod' from 'OuterClass', demonstrating tight coupling of classes and encapsulation. The use of an instance of 'OuterClass' to create 'InnerClass' ensures proper context for accessing private members in 'OuterClass', showcasing nested class utility while maintaining object-oriented design principles.

Java uses classes to implement inheritance, where a subclass can inherit fields and methods from a superclass. Method overriding occurs when a subclass provides a specific implementation for a method already defined in its superclass. Dynamic method dispatch, a run-time concept, enables calling overridden methods based on the object's actual class, rather than reference type. In the described program, 'Animal', 'Dog', and 'Cat' illustrate inheritance. 'Dog' and 'Cat' override the 'makeSound' method. An 'Animal' reference to 'Dog' or 'Cat' objects demonstrates dynamic dispatch, invoking overridden versions during execution despite the reference type being 'Animal'.

The Fibonacci series logic uses a sequence where each number is the sum of the two preceding ones. In Java, a loop initializes with two numbers, 'first' and 'next', representing the starting sequence (0 and 1, respectively). Inside the loop, a temporary 'sum' is calculated, updating the 'first' and 'next' variables iteratively. The loop continues for 'n-2' times, as the first two numbers are already initialized manually. Each iteration updates these values, progressively printing out the series until the desired count is reached.

Date validation in Java involves checking correctness based on rules for days in each month and leap years. The program defines a method 'isLeapYear' to determine leap years by checking divisibility rules (400 or 4 but not 100). Days in months are checked using conditions: months with 31 days (like January, March), with 30 (April, June), and for February, whether it's a leap year affecting day count (29 or 28). The 'validate' method uses these to decide a date's validity. This process is ensured by passing user inputs through these logical evaluations, resulting in valid/invalid feedback.

Synchronized threads ensure coordinated access to shared resources to avoid data inconsistency. For the producer-consumer problem, Java uses a 'Buffer' class that enables synchronized 'produce' and 'consume' methods. With synchronization, the 'produce' method waits if data is available and notifies once new data is added, changing its status. The 'consume' method waits for data availability, consumes it, resets the state, and notifies once consumed. The 'Producer' and 'Consumer' threads operate repeatedly, using these methods to interact without conflict due to synchronization locks and proper wait/notify mechanisms, ensuring a seamless data flow.

Static member data and methods belong to the class, rather than any object instance. This means that they are shared among all instances and can be accessed without creating an object of the class. An instance in 'StaticDemo' uses 'count' as a static variable, modified by the static method 'incrementCount'. Unlike instance variables, static variables retain their most recent value across all instances. The main advantage is when variables or methods do not depend on instance data, enabling memory efficiency and easy global access to class-specific configurations or counters.

Java allows for creation of user-defined exceptions to handle specific scenarios more effectively than standard exceptions. This involves extending the 'Exception' class and adding specific behaviors. In the provided 'UserException' example, a custom exception 'MyException' is thrown when an arithmetic condition is met (division result is less than 1). This showcases tailored handling for context-specific exceptions. By catching 'MyException', the program demonstrates controlled error management and meaningful feedback to users or developers, beyond what standard exceptions may offer.

You might also like