0% found this document useful (0 votes)
4 views18 pages

JavaLab Part B

The document contains a series of Java programming exercises focused on Object-Oriented Programming (OOP) concepts, including creating user-defined packages, abstract classes, arrays of objects, string manipulation, exception handling, and synchronized threads. Each exercise includes code examples, explanations, and expected output. The programs demonstrate practical applications of OOP principles and Java features.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views18 pages

JavaLab Part B

The document contains a series of Java programming exercises focused on Object-Oriented Programming (OOP) concepts, including creating user-defined packages, abstract classes, arrays of objects, string manipulation, exception handling, and synchronized threads. Each exercise includes code examples, explanations, and expected output. The programs demonstrate practical applications of OOP principles and Java features.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OOP’s LAB PROGRAMS

11 Write a JAVA program to implement the concept of


importing classes from user-defined package and creating
packages.

// File: [Link]
package mypackage;

public class Calculator


{
public static int add(int a, int b)
{
return a + b;
}

public static int subtract(int a, int b)


{
return a - b;
}

public static int multiply(int a, int b)


{
return a * b;
}

public static int divide(int a, int b) throws ArithmeticException


{
if (b == 0)
{
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
}
}

// File: [Link]
import [Link];

public class Main


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

1
OOP’s LAB PROGRAMS

int num1 = 10;


int num2 = 5;

int sum = [Link](num1, num2);


[Link]("Sum: " + sum);

int difference = [Link](num1, num2);


[Link]("Difference: " + difference);

int product = [Link](num1, num2);


[Link]("Product: " + product);

int quotient = [Link](num1, num2);


[Link]("Quotient: " + quotient);
} catch (ArithmeticException e) {
[Link]("An arithmetic exception occurred: " +
[Link]());
}
}
}

OUTPUT:
Sum: 15
Difference: 5
Product: 50
Quotient: 2

12 Write a program to demonstrate abstract class and abstract


methods.

abstract class Students


{
abstract void sName() throws UnsupportedOperationException;
}

class Student1 extends Students


{
void sName()
{
[Link]("Student Name: Arjun");
}
}

2
OOP’s LAB PROGRAMS

class Student2 extends Students


{
void sName() {
[Link]("Student Name: Ram");
}
}

public class Main {


public static void main(String[] args)
{
try {
Student1 s1 = new Student1();
[Link]();

Student2 s2 = new Student2();


[Link]();
} catch (UnsupportedOperationException e) {
[Link]("Unsupported operation: " + [Link]());
}
}
}

OUTPUT:
Student Name: Arjun
Student Name: Ram

13 Write a JAVA program to implement an array of objects of a


class.

import [Link].*;
class Book
{
String title;
String author;
Book(String ti, String au)
{
[Link]=ti;
[Link]=au;
}
void showDetails()
{
[Link](title+" Written by "+author);
}
}

3
OOP’s LAB PROGRAMS

class ArOfOb
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
int i=0,n=0;
Book books[] = new Book[10];
[Link]("Enter number of books:");
do{
try{
n = [Link]();
if(n==0)
[Link]("Number should be greater than zero");
if(n<0)
[Link]("Enter a positive number:");
for(i=0;i<n;i++)
{
[Link]("Enter the book title:");
String ti = [Link]();
[Link]("Enter the author name:");
String au = [Link]();
books[i]= new Book(ti,au);
}
}catch(Exception e){
[Link]("Enter an integer:");
[Link]();
}
}while(n<=0 || n>=10);
[Link]();
[Link]("------Books------");
for(i=0;i<n;i++)
books[i].showDetails();
}
}

OUTPUT:
Enter number of books:
n
Enter an integer:
0
Number should be greater than zero
2

4
OOP’s LAB PROGRAMS

Enter the book title:


Matagathi
Enter the author name:
Ravi Belagere
Enter the book title:
Light
Enter the author name:
M John Harrison
–-----Books–-----
Matagathi Written by Ravi Belagere
Light Written by M John Harrison

14 Write a JAVA program to demonstrate String class and its


methods.

class StrClass
{
public static void main(String args[])
{
String str1 = "Bangalore";
String str2 = "University";
String str4 = " The Rat ";

[Link]("First String: "+str1);


[Link]("Second String: "+str2);
[Link]("1. Length of First String: "+len(str1));
[Link]("2. Character at 7th position in Second String:
"+cAt(str2));
[Link]("3. Substring of First String: "+substr(str1));
String str3 = con(str1,str2);
[Link]("4. Concatenation of two Strings: "+str3);
[Link]("5. First String in Upper Case: "+upper(str1));
[Link]("6. Second String in Lower Case: "+lower(str2));
[Link]("7. Index of (U) in Third String: "+index(str3));
[Link]("8. Trimming the Fourth String: "+trim(str4));
[Link]("9. Replacing (t) in Fourth String: "+replace(str4));
[Link]("10. Checking if Second String starts with (I) or not:
"+[Link](“I”));
[Link]("11. Checking if Third String ends with (y) or not:
"+[Link](“y”));
[Link]("12. Checking if (Bengaluru) equals to First String:
"+[Link](“Bengaluru”));

5
OOP’s LAB PROGRAMS

[Link]("13. Checking if (UNIVERSITY) equals to second


String: "+[Link](“UNIVERSITY”));
[Link]("14. Comparing First String and Second String:
"+[Link](str2));
[Link]("15. Comparing (bangalore) with First String:
"+[Link](“bangalore”));
[Link]("16. Checking if Third String contains (Bangalore):
"+[Link]("Bangalore"));
[Link]("17. Joining Third String: "+[Link]("
",str3,"Jnanabharathi","Campus"));
[Link]("18. Checking if Fourth String is empty or not:
"+[Link]());
[Link]("19. Checking the last index of (i) in Second String:
"+[Link]("i"));
[Link]("20. Substring of First String: "+[Link](0,3));
}
public static int len(String s1)
{
return [Link]();
}
public static char cAt(String s2)
{
return [Link](7);
}
public static String substr(String s1)
{
return [Link](5);
}
public static String con(String s1,String s2)
{
return [Link](s2);
}
public static String upper(String s1)
{
return [Link]();
}
public static String lower(String s2)
{
return [Link]();
}
public static int index(String s3)
{
return [Link]("U");
}

6
OOP’s LAB PROGRAMS

public static String trim(String s4)


{
return [Link]();
}
public static String replace(String s4)
{
return [Link]("t","i");
}
}

OUTPUT:
First String: Bangalore
Second String: University
1. Length of First String: 9
2. Character at 7th position in Second String: i
3. Substring of First String: lore
4. Concatenation of two Strings: BangaloreUniversity
5. First String in Upper Case: BANGALORE
6. Second String in Lower Case: university
7. Index of (U) in Third String: 9
8. Trimming the Fourth String: The Rat
9. Replacing (t) in Fourth String: The Rai
10. Checking if Second String starts with (I) or not: false
11. Checking if Third String ends with (y) or not: true
12. Checking if (Bengaluru) equals to First String: false
13. Checking if (UNIVERSITY) equals to second String: true
14. Comparing First String and Second String: -19
15. Comparing (bangalore) with First String: 0
16. Checking if Third String contains (Bangalore): true
17. Joining Third String: BangaloreUniversity Jnanabharathi Campus
18. Checking if Fourth String is empty or not: false
19. Checking the last index of (i) in Second String: 7
20. Substring of First String: Ban

15 Write a JAVA program to implement the concept of


exception handling by creating user-defined exceptions.

import [Link].*;

class PerValid
{
Scanner s = new Scanner([Link]);
public void valid(int p)

7
OOP’s LAB PROGRAMS

{
try{
if((p>0)&&(p<=128))
{
int wdraw=1;
[Link]("Valid User");
while((wdraw>0)&&(wdraw<=20000))
{
try{
[Link]("Enter amount to withdraw:");
wdraw = [Link]();
withdraw(wdraw);
}catch(InputMismatchException n)
{
[Link]("Enter an integer:");
[Link]();
}
}
}
else
throw new Exception("Wrong pin. Invalid User");
}catch(Exception e)
{
[Link]([Link]());
}
}
public static void withdraw(int wdraw)
{
int balance=100000;
int bal2 = (balance-wdraw);
try{
if(wdraw>20000)
throw new Exception("Withdraw limit exceeded. \n"+"The available
balance is: "+balance);
if(balance==0)
throw new Exception("Sorry you cannot withdraw. Zero balance");
else
{
[Link]("Balance="+balance);
[Link]("Withdrawn amount is: "+wdraw);
[Link]("Available balance after withdrawn is: "+bal2);
}
}catch(Exception w)
{

8
OOP’s LAB PROGRAMS

[Link]([Link]());
}
}
}
class Bank
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
int pin=1;
while((pin>0)&&(pin<=128))
{
try{
[Link]("Enter 0 to exit:");
[Link]("Enter 1 to continue:");
int n=[Link]();
if(n==0)
break;
if(n==1)
[Link]("Total Pins:128");
[Link]("Enter the pin:");
pin=[Link]();
PerValid PV = new PerValid();
[Link](pin);
}catch(InputMismatchException a)
{
[Link]("Enter an integer:");
[Link]();
}
}
}
}

OUTPUT:
Enter 0 to exit:
Enter 1 to continue:
0

Enter 0 to exit:
Enter 1 to continue:
1
Total Pins:128
Enter the pin:
E

9
OOP’s LAB PROGRAMS

Enter an integer:
Enter 0 to exit:
Enter 1 to continue:
1
Total Pins:128
Enter the pin:
23
Valid User
Enter amount to withdraw:
y
Enter an integer:
Enter amount to withdraw:
10000
Balance=100000
Withdrawn amount is: 10000
Available balance after withdrawn is: 90000
Enter amount to withdraw:
25000
Withdraw limit exceeded
The available balance is:100000
Enter 0 to exit:
Enter 1 to continue:
1
Total Pins:128
Enter the pin:
0
Wrong pin. Invalid User

16 Write a JAVA program using synchronized threads, which


demonstrate producer consumer concept.

import [Link].*;

public class ProCon


{
public static void main(String args[])
{
List<Integer>sharedList = new ArrayList<Integer>();
Thread thread1 = new Thread(new Pro(sharedList));
Thread thread2 = new Thread(new Con(sharedList));
[Link]();
[Link]();
}
}

10
OOP’s LAB PROGRAMS

class Pro implements Runnable


{
List<Integer>sharedList=null;
final int MAX_SIZE=3;
private int i=0;
public Pro(List<Integer>sharedList)
{
super();
[Link] = sharedList;
}
public void run()
{
while(true)
{
try{
produce(i++);
}catch(InterruptedException e)
{}
}
}

public void produce(int i)throws InterruptedException


{
synchronized(sharedList)
{
while([Link]()==MAX_SIZE)
{
[Link]("Shared List is full..... waiting for consumer to
consume");
[Link]();
}
}
synchronized(sharedList)
{
[Link]("Producer produced element:"+i);
[Link](i);
[Link](1000);
[Link]();
}
}
}

11
OOP’s LAB PROGRAMS

class Con implements Runnable


{
List<Integer>sharedList=null;
public Con(List<Integer>sharedList)
{
super();
[Link] = sharedList;
}
public void run()
{
while(true)
{
try{
consume();
}catch(InterruptedException e)
{}
}
}
public void consume()throws InterruptedException
{
synchronized(sharedList)
{
while([Link]())
{
[Link]("Shared List is empty..... waiting for producer to
produce");
[Link]();
}
}
synchronized(sharedList)
{
[Link](1000);
[Link]("Consumer element:"+[Link](0));
[Link]();
}
}
}

OUTPUT:
Producer produced element: 0
Producer produced element: 1
Producer produced element: 2
Shared List is full..... waiting for consumer to consume

12
OOP’s LAB PROGRAMS

Consumer element: 0
Consumer element: 1
Consumer element: 2
Shared List is empty..... waiting for producer to produce

17 Write a JAVA program that creates three threads. First


thread displays “Good Morning” every one second, second
thread displays “Hello” every two seconds and the third
thread displays “Welcome” every three seconds.

class GM extends Thread


{
synchronized public void run()
{
try{
int i=0;
while(i<=3)
{
[Link](1000);
[Link]("Good Morning");
i++;
}
}catch(Exception e)
{
[Link]("Error handled");
}
}
}

class Hello extends Thread


{
synchronized public void run()
{
try{
int i=0;
while(i<=3)
{
[Link](2000);
[Link]("Hello");
i++;
}
}catch(Exception e)
{
[Link]("Error handled");

13
OOP’s LAB PROGRAMS

}
}
}

class Welcome extends Thread


{
synchronized public void run()
{
try{
int i=0;
while(i<=3)
{
[Link](3000);
[Link]("Welcome");
i++;
}
}catch(Exception e)
{
[Link]("Error handled");
}
}
}

class MultiThread
{
public static void main(String args[])
{
GM t1 = new GM();
[Link]();
Hello t2 = new Hello();
[Link]();
Welcome t3 = new Welcome();
[Link]();
}
}

OUTPUT:
Good Morning
Hello
Good Morning
Welcome
Good Morning
Hello
Good Morning

14
OOP’s LAB PROGRAMS

Hello
Welcome
Hello
Welcome
Welcome

18 Write a JAVA program which uses FileInputStream /


FileOutputStream Classes.

import [Link].*;

public class FIO


{
public static void main(String args[]) throws FileNotFoundException
{
int i;
try{
FileInputStream fis;
fis = new FileInputStream("/home/bub/Documents/Java/[Link]");
do{
i = [Link]();
if(i != 1)
[Link]((char)i);
}while(i != -1);
[Link]();
FileOutputStream fos;
fos = new
FileOutputStream("/home/bub/Documents/Java/[Link]");
String str = "BANGALORE UNIVERSITY";
char ch[] = [Link]();
for(i=0;i<[Link]();i++)
{
[Link](ch[i]);
}
[Link]();
}catch(Exception ex)
{
[Link]("File not found");
}
}
}

15
OOP’s LAB PROGRAMS

OUTPUT1:
N
D
K

OUTPUT2:
B
A
N
G
A
L
O
R
E

U
N
I
V
E
R
S
I
T
Y

19 Write a JAVA program to list all the files in a directory


including the files present in all its subdirectories.

import [Link].*;

public class FinDir


{
public void printFileName(File[] a,int i,int lvl)
{
if(i == [Link])
return;
for(int j=0; j<lvl; j++)
{
[Link]("\t");
if(a[i].isFile())
[Link](a[i].getName()+" is file");
else if(a[i].isDirectory())

16
OOP’s LAB PROGRAMS

{
[Link]("["+a[i].getName() +"]"+" is directory");
printFileName(a[i].listFiles(),0,lvl+1);
}
}
printFileName(a,i+1,lvl);
}
public static void main(String args[])
{
String path = "/home/bub/Documents/JavaLab";
File fobj = new File(path);
FinDir obj = new FinDir();
if([Link]() && [Link]())
{
File a[] = [Link]();
[Link]("Display files from directory: "+fobj);
[Link](a,0,1);
}
else
{
[Link](fobj+"is not directory");
}
}
}

OUTPUT:
Display files from directory: /home/bub/Documents/JavaLab
JL is directory
[Link] is file
[Link] is file
[Link] is file
[Link] is file

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


applet.

import [Link];
import [Link].*;
/* <applet code ="[Link]" width="300" height="300">
</applet> */
public class SimpleApplet extends Applet
{
public void init()
{

17
OOP’s LAB PROGRAMS

[Link]("Initialization");
}
public void start()
{
[Link]("Applet started");
}
public void paint(Graphics g)
{
[Link]("A Simple Applet",50,50);
}
public void stop()
{
[Link]("Applet Stopped");
}
public void destroy()
{
[Link]("Applet Destroyed");
}
}

OUTPUT:
Initialization
Applet started

Applet Stopped
Applet Destroyed

18

You might also like