100% found this document useful (2 votes)
2K views

BSC IV Sem JAVA Lab Programs

The document outlines 14 lab programs for an Object Oriented Programming course through Java, including programs to calculate student details, perform string operations, add and multiply matrices, demonstrate constructors, calculate area using method overloading, implement inheritance between person and student classes, implement interfaces, demonstrate multiple inheritance, create threads, handle exceptions, create an applet to display shapes, create a book structure to store and manipulate book details in a file, create a method to accept multiple parameters, and count vowels, consonants, digits and spaces in a program. The programs cover core Java concepts like OOPs, inheritance, polymorphism, exceptions and file handling.

Uploaded by

Teller Person
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
2K views

BSC IV Sem JAVA Lab Programs

The document outlines 14 lab programs for an Object Oriented Programming course through Java, including programs to calculate student details, perform string operations, add and multiply matrices, demonstrate constructors, calculate area using method overloading, implement inheritance between person and student classes, implement interfaces, demonstrate multiple inheritance, create threads, handle exceptions, create an applet to display shapes, create a book structure to store and manipulate book details in a file, create a method to accept multiple parameters, and count vowels, consonants, digits and spaces in a program. The programs cover core Java concepts like OOPs, inheritance, polymorphism, exceptions and file handling.

Uploaded by

Teller Person
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Emerald’s Degree College

BSc IV Semester Lab Programs


Object Oriented Programming through JAVA

1. Write a program to read Student Name, Reg.No, Marks[5] and calculate Total,
Percentage, Result. Display all the details of students
2. Write a program to perform the String Operations
3. Java program to implements Addition and Multiplication of two N X N matrices.
4. Java program to demonstrate the use of Constructor.
5. Calculate area of the following shapes using method overloading.
a. Triangle
b. Rectangle
c. Circle
d. Square
6. Implement inheritance between Person (Aadhar, Surname, Name, DOB, and Age)
and Student (Admission Number, College, Course, Year) classes where ReadData(),
DisplayData() are overriding methods.
7. Java program for implementing Interfaces
8. Java program on Multiple Inheritance.
9. Java program for to display Serial Number from 1 to N by creating two Threads
10. Java program to demonstrate the following exception handlings
a. Divided by Zero
b. Array Index Out of Bound
c. File Not Found
d. User Defined Exception
11. Create an Applet to display different shapes such as Circle, Oval, Rectangle,
Square and Triangle.
12. Write a program to create Book (ISBN,Title, Author, Price, Pages,
Publisher)structure and store book details in a file and perform the following
operations
a. Add book details
b. Search a book details for a given ISBN and display book details, if available
c. Update a book details using ISBN
d. Delete book details for a given ISBN and display list of remaining Books
13. Write a program to create a method which can accept n number of
parameters.
14. Program to count vowels, consonants, digits, and spaces
15. Write java program to reserve seats in a bus.
1.
Aim: Write a program to read Student Name, Reg.No, Marks[5] and calculate
Total, Percentage, Result. Display all the details of students

Procedure:
import java.io.*;
import java.lang.*;
import java.util.Scanner;
class StudentDetails
{
public static void main(String args[])
{
String name;
int roll, total;
int marks[]=new int[6];
Scanner SC=new Scanner(System.in);
System.out.print("Enter Name: ");
name=SC.nextLine();
System.out.print("Enter Roll Number: ");
roll=SC.nextInt();
System.out.print("Enter marks in six subjects: ");
for(int i=0;i<6;i++)
{
marks[i]=SC.nextInt();
total=marks[i];
}
float perc=(float)total/600*100;
System.out.println("Roll Number:" + roll +"\tName: "+name);
System.out.println("Total: "+total +"\tPercentage: "+perc);
System.out.print("Result: ");
if(marks[0]<35||marks[1]<35||marks[2]<35||marks[3]<35||
marks[4]<35||marks[5]<35)
System.out.print("Fail\tGrade:---------");
else
{
System.out.print("Pass\t\t");
System.out.print("\tGrade: ");
if(perc>=80)
System.out.print("A");
else
if(perc>=60 && perc<80)
System.out.print("B");
else
if(perc>=40 && perc<60)
System.out.print("C");
else
System.out.print("D");
}
}
}
2.
Aim: Write a program to perform String Operations
Procedure:

import java.io.*;
import java.lang.*;
class StringMethods
{
public static void main(String args[])
{
String greet = "Hello! World";
System.out.println("String: " + greet);
int len = greet.length();
System.out.println("Length: " + len);

String first = "Java ";


String second = "Programming";
String third = first.concat(second);
System.out.println("Joined String: " + third);

first = "java programming";


second = "java programming";
third = "JAVA programming";
System.out.println("Strings first and second are equal: " + first.equals(second));
System.out.println("Strings first and third are equal: " + first.equals(third));
System.out.println("Strings first and third are equal: " +
first.equalsIgnoreCase(third));

String str1 = "Java String Data";


boolean result = str1.contains("Java");
System.out.println(result);

str1 = "java is fun";


System.out.println(str1.substring(0, 4));
str1 = "I";
String str2 = "love";
String str3 = "Java";
String joinedStr = String.join(" ", str1, str2, str3);
System.out.println(joinedStr);

str1 = "bat ball";


System.out.println(str1.replace('b', 'c'));
System.out.println(str1.charAt(2));

str1 = "Java is fun";


int res = str1.indexOf('s');
System.out.println(res);

str1 = " Learn Java Programming ";


System.out.println("this is"+str1+"given string");
System.out.println("this is"+str1.trim()+"given string");

String text = "Java is a fun programming language";


String[] results = text.split(" ");
System.out.print("result = ");
for (String str : results)
System.out.print(str + ", ");
System.out.println(str1.toLowerCase());
System.out.println(str1.toUpperCase());

}
}
3.
Aim: Java program to implement Addition and multiplication of two N X N
matrices

Procedure:
import java.io.*;
import java.lang.*;
import java.util.Scanner;

class Matrix
{
public static void main(String args[])
{
int N,i,j;
Scanner in = new Scanner(System.in);
System.out.println("Enter the size of matrix");
N = in.nextInt();
int mat1[][] = new int[N][N];
int mat2[][] = new int[N][N];
int res[][] = new int[N][N];
System.out.println("Enter the elements of matrix1");
for ( i= 0 ; i < N ; i++ )
{
for ( j= 0 ; j < N ;j++ )
mat1[i][j] = in.nextInt();
System.out.println();
}
System.out.println("Enter the elements of matrix2");
for ( i= 0 ; i < N ; i++ )
{
for ( j= 0 ; j < N ;j++ )
mat2[i][j] = in.nextInt();
System.out.println();
}
for ( i= 0 ; i < N ; i++ )
for ( j= 0 ; j < N ;j++ )
res[i][j] = mat1[i][j] + mat2[i][j] ;
System.out.println("Sum of matrices:-");
for ( i= 0 ; i < N ; i++ )
{
for ( j= 0 ; j < N ;j++ )
System.out.print(res[i][j]+"\t");
System.out.println();
}
System.out.println("Matrix multiplication is : \n");
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
{
res[i][j]=0;
for(int k = 0; k < N; k++)
{
res[i][j] += mat1[i][k] * mat2[k][j];
}
System.out.print(res[i][j] + "\t");
}
System.out.println();
}
}
}

4.
Aim: Java program to demonstrate the use of Constructor.
Procedure:
import java.io.*;
import java.lang.*;
class TestCon1
{
String name;
TestCon1()
{
System.out.println("Constructor1 Called:");
name = "BCom II Sem";
}
public static void main(String args[])
{
TestCon1 obj = new TestCon1();
System.out.println("The name is " + obj.name);
}
}
class TestCon2
{
String language;
TestCon2(String lang)
{
language = lang;
System.out.println(language + " Programming Language");
}
public static void main(String[] args)
{
TestCon2 obj1 = new TestCon2("Java");
TestCon2 obj2 = new TestCon2("Python");
}
}
5.
Aim: Calculate area of the following shapes using method overloading.
a. Triangle b. Rectangle b. Circle c. Square
Procedure:
import java.io.*;
import java.lang.*;
class OverloadFun
{
void area(float a, float b, float c)
{
float s=(a+b+c)/2;

System.out.println("the area of the Triangle is "+Math.sqrt(s*(s-a)*(s-b)*(s-


c)));
}

void area(float x)
{
System.out.println("the area of the Square is "+Math.pow(x, 2));
}

void area(float x, float y)


{
System.out.println("the area of the rectangle is "+x*y);
}

void area(double x)
{
double z = 3.14 * x * x;
System.out.println("the area of the circle is "+z+);
}
public static void main(String args[])
{
OverloadFun ob = new OverloadFun();
ob.area(2,4,3);
ob.area(5);
ob.area(11,12);
ob.area(2.5);
}
}
6.
AIM: Implement inheritance between Person (Aadhar, Surname, Name, DOB,
and Age) and Student (Admission Number, College, Course, Year) classes
where ReadData(), DisplayData() are overriding methods.
Procedure:

import java.io.*;
import java.lang.*;
import java.util.Scanner;
class Person
{
String Surname, Name, DOB;
long Adhar;
int Age;
void readData()
{
Scanner i=new Scanner(System.in);
System.out.print(“enter the surname:”);
Surname=i.nextLine();
System.out.print(“enter the name:”);
Name=i.nextLine();
System.out.print(“enter the DOB(dd/mm/yyyy):”);
DOB=i.nextLine();
System.out.print(“enter the age:”);
Age=i.nextInt();
System.out.print(“enter the adhar number:”);
Adhar=i.nextLong();
}
void displayData()
{
System.out.println(“Surname\t:”+Surname);
System.out.println(“Name\t\t:”+Name);
System.out.println(“DOB\t\t:”+DOB);
System.out.println(“Age\t\t:”+Age);
System.out.println(“Adhar Number\t:”+Adhar);
}
}

class Student extends Person


{
String College, Course;
int Adm_no,Year;
void readData()
{
super.readData();
Scanner i=new Scanner(System.in);
System.out.print(“enter the college name:”);
College=i.nextLine();
System.out.print(“enter the course:”);
Name=i.nextLine();
System.out.print(“enter the admission number:”);
Adm_no=i.nextInt();
System.out.print(“enter the year:”);
Year=i.nextInt();
}
void displayData()
{
super.displayData();
System.out.println(“College Name\t:”+College);
System.out.println(“Course\t\t:”+Name);
System.out.println(“Admission Number:”+Adm_no);
System.out.print(“Year\t\t:”+Year);
}
public static void main(String args[])
{
Student t=new Student();
t.readData();
t.displayData();
}
}
7.
Aim: Java program for implementing Interfaces
Procedure:
interface Sam
{
void m(String... s);
int n=5;
}
class UseSam1 implements Sam
{
public void m(String... s)
{
System.out.println("first Five words are");
for(int i=0;i<n;i++)
{
System.out.println(s[i]);
}
}
public static void main(String args[])
{
UseSam1 q=new UseSam1();
q.m("hello","this","is","sample","text","for","method");
}
}

class UseSam2 implements Sam


{
public void m(String... s)
{
System.out.println("given words are");
for(String a:s)
{
System.out.println(a);
}
}
public static void main(String args[])
{
UseSam2 q=new UseSam2();
q.m("hello","this","is","sample","text","for","method");
}
}
8.
Aim: Implement multilevel inheritance
Procedure:
import java.io.*;
import java.lang.*;
class Students
{
private int sno;
private String sname;
public void setstud(int no,String name)
{
sno = no;
sname = name;
}
public void printstud()
{
System.out.println("Student No : " + sno);
System.out.println("Student Name : " + sname);
}
}
class Marks extends Students
{
protected int mark1,mark2;
public void setmarks(int m1,int m2)
{
mark1 = m1;
mark2 = m2;
}
public void printmarks()
{
System.out.println("Mark1 : " + mark1);
System.out.println("Mark2 : " + mark2);
}
}
class Result extends Marks
{
private int total;
public void calc()
{
total = mark1 + mark2;
}
public void printtotal()
{
System.out.println("Total : " + total);
}
public static void main(String args[])
{
Result f = new Result();
f.setstud(100,"Nithya");
f.setmarks(78,89);
f.calc();
f.printstud();
f.printmarks();
f.printtotal();
}
}
9.
Aim: Java program for to display Serial Number from 1 to 10 by creating two
Threads
Procedure:

class NumberGenerator
{
static int counter = 1;

public synchronized int getNextNumber()


{
return counter++;
}
}
class FirstThreadClass
extends Thread
{
NumberGenerator num;

FirstThreadClass(NumberGenerator num)
{
this.num = num;
}
public void run()
{
System.out.println("thread 1:" + num.getNextNumber());
}
}
class SecondThreadClass
extends Thread
{
NumberGenerator num;
SecondThreadClass(NumberGenerator num)
{
this.num = num;
}

public void run()


{
System.out.println("thread2 :" + num.getNextNumber());
}
}
public class ThreadTesting
{
public static void main(String[] args)
{
FirstThreadClass ftc = new FirstThreadClass(new NumberGenerator());
SecondThreadClass stc = new SecondThreadClass(new
NumberGenerator());
for (int k = 1; k <= 5; k++)
{
ftc.run();
stc.run();
}
}
}
10. (a)
Aim: Java program to demonstrate the Divided by Zero exception handling
Procedure:
import java.io.*;
import java.lang.*;
class DZExp {
public static void main(String args[])
{
int a=10;
int b=0;
try
{
System.out.println(a / b);
}
catch (ArithmeticException e)
{
System.out.println("Divided by zero operation cannot possible");
}
}
}
10. (b)
Aim: Java program to demonstrate the Array Index Out of Bound exception
handling
Procedure:
import java.io.*;
import java.lang.*;
import java.util.Scanner;
class AIOBExp
{
public static void main(String args[])
{
int[] myArray = {897, 56, 78, 90, 12, 123, 75};
System.out.println("Elements in the array are:: ");
System.out.println(Arrays.toString(myArray));
Scanner sc = new Scanner(System.in);
System.out.println("Enter the index of the required element ::");
try
{
int element = sc.nextInt();
System.out.println("Element in the given index is :: "+myArray[element]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("The index you have entered is invalid");
System.out.println("Please enter an index number between 0 and 6");
}
}
}
10. (c)
Aim: Java program to demonstrate the FileNotFound Exception handling
Procedure:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

class FileExample
{
public static void main(String[] args)
{
File file = new File("D:/JavaProgram/myfile.txt");
FileInputStream fis = null;
try
{
fis = new FileInputStream(file);
while (fis.read()!=-1)
{
System.out.println(fis.read());
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{

try
{
fis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
10. (d)
Aim: Java program to demonstrate the Userdefined Exception handling
Procedure:
import java.util.*;
import java.io.*;
import java.lang.*;

class Validate extends Exception


{
static boolean check(String s) throws Exception
{
char c=s.charAt(0);
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u')
throw new Exception("Error: username starts with vowel...");
else
return true;
}

class Users
{
String user[]=new String[5];

void getUsers()
{
Scanner i=new Scanner(System.in);
System.out.println("enter user names:");
for(int a=0;a<5;a++)
user[a]=i.next();
}

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


{
Users n=new Users();
System.out.println("enter names which starts with consonant:");
n.getUsers();
System.out.println("given names are:");
for(String s:n.user)
{
if(Validate.check(s))
System.out.println(s);
}
}
}
11.
Aim: Create an Applet to display different shapes such as Circle, Oval,
Rectangle, Square and Triangle.

Procedure:

import java.applet.*;
import java.awt.*;
/*
<applet code = "ShapeClass" width=600 height=600>
</applet>
*/

public class ShapeClass extends Applet


{
//Function to initialize the applet
public void init()
{
setBackground(Color.white);
}
//Function to draw and fill shapes
public void paint(Graphics g)
{

//Draw a square
g.setColor(Color.black);
g.drawString("Square",75,200);
int x[]={50,150,150,50};
int y[]={50,50,150,150};
g.drawPolygon(x,y,4);
g.setColor(Color.yellow);
g.fillPolygon(x,y,4);

//Draw a circle
g.setColor(Color.black);
g.drawString("Circle",400,200);
g.drawOval(350,50,125,125);
g.setColor(Color.yellow);
g.fillOval(350,50,125,125);

//Draw an oval
g.setColor(Color.black);
g.drawString("Oval",100,380);
g.drawOval(50,250,150,100);
g.setColor(Color.yellow);
g.fillOval(50,250,150,100);

//Draw a rectangle
g.setColor(Color.black);
g.drawString("Rectangle",300,380);
x=new int[]{250,450,450,250};
y=new int[]{250,250,350,350};
g.drawPolygon(x,y,4);
g.setColor(Color.yellow);
g.fillPolygon(x,y,4);

//Draw a triangle
g.setColor(Color.black);
g.drawString("Traingle",100,525);
x=new int[]{50,50,200};
y=new int[]{500,400,500};
g.drawPolygon(x,y,3);
g.setColor(Color.yellow);
g.fillPolygon(x,y,3);
}
}
12.
Aim: Write a program to handle a deadlock in java
Description:

Procedure:
public class TestThread {
public static Object L1 = new Object();
public static Object L2 = new Object();

public static void main(String args[]) {

ThreadDemo1 T1 = new ThreadDemo1();


ThreadDemo2 T2 = new ThreadDemo2();
T1.start();
T2.start();
}

private static class ThreadDemo1 extends Thread {


public void run() {
synchronized (L1) {
System.out.println("Thread 1: Holding L 1...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for L 2...");
synchronized (L2) {
System.out.println("Thread 1: Holding L 1 & 2...");
}
}
}
}
private static class ThreadDemo2 extends Thread {
public void run() {
synchronized (L1) {
System.out.println("Thread 2: Holding L 2...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for L 1...");
synchronized (L2){
System.out.println("Thread 2: Holding L 1 & 2...");
}
}
}
}
}
13.
Aim: Write a program to create a method which can accept n number of parameters.

Procedure:

class TestForEach

void sumof(int... x)

int r=0;

System.out.print("sum of ");

for(int a:x)

System.out.print(a+",");

r=r+a;

System.out.printf("\b is "+r+"\n");

public static void main(String args[])

TestForEach t=new TestForEach();

t.sumof(3,4);

t.sumof(4,5,6);

t.sumof(6,6,8,9,7,55);

t.sumof(4);

}
14.

Aim: Program to count vowels, consonants, digits, and spaces

Procedure:

import java.io.*;

import java.lang.*;

class Counting

public static void main(String[] args)

String line = "I am Studying 2nd Bcom 4th semester.";

int vowels = 0, consonants = 0, digits = 0, spaces = 0;

line = line.toLowerCase();

for (int i = 0; i < line.length(); ++i)

char ch = line.charAt(i);

// check if character is any of a, e, i, o, u

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')

++vowels;

// check if character is in between a to z

else

if ((ch >= 'a' && ch <= 'z'))

++consonants;
}

// check if character is in between 0 to 9

else if (ch >= '0' && ch <= '9')

++digits;

// check if character is a white space

else if (ch == ' ')

++spaces;

System.out.println("Vowels: " + vowels);

System.out.println("Consonants: " + consonants);

System.out.println("Digits: " + digits);

System.out.println("White spaces: " + spaces);

}
15.
Aim: Write java program to reserve seats in a bus.
Procedure:

import java.io.*;

import java.lang.*;

import java.util.Scanner;
class BusRes
{
int seat[]=new int[40];
String name[]=new String[40];
Scanner in=new Scanner(System.in);
BusRes()
{
for(int i=0;i<40;i++)
{
seat[i]=0;
name[i]=" ";
}
}
boolean isAvl(int n)
{
if(seat[n]==0)
return true;
else
return false;
}
void resSeat(int n)
{
if(isAvl(n))
{
System.out.println("Seat is Available");
System.out.print("Enter your name:");
name[n]=in.next();
seat[n]=1;
System.out.println("Seat has been reserved to "+name[n]);
}
else
System.out.println("Sorry seat is not available");
}
void canSeat(int n)
{
if(!isAvl(n))
{
String temp;
System.out.print("Confirm your name:");
temp=in.next();
if(temp.equals(name[n]))
{
seat[n]=0;
System.out.println("Seat has been cancelled ");
}
else
System.out.println("Please check your details");
}
else
System.out.println("Sorry seat not yet reserved");
}
void viewAvl()
{
System.out.println("list of available seats");
for(int i=0;i<40;i++)
if(seat[i]==0)
System.out.print(" "+(i+1));
}
void viewRes()
{
System.out.println("list of reserved seats");
for(int i=0;i<40;i++)
if(seat[i]==1)
System.out.print(" "+(i+1));
}
void viewAll()
{
System.out.println("Seat No.\t\tStatus\t\tName");
for(int i=0;i<40;i++)
{
System.out.print(i+1+"\t\t");
if(seat[i]==0)
System.out.println("Available");
else
System.out.println("Reserved\t\t"+name[i]);
}
}
void menu()
{
int ch,n;
while(true)
{
System.out.println("1.Reservation");
System.out.println("2.Cancel");
System.out.println("3.View Aailable Seats");
System.out.println("4.View Reserved Seats");
System.out.println("5.View All Deatils");
System.out.println("6.exit");
System.out.println("Choice:");
ch=in.nextInt();
switch(ch)
{
case 1: System.out.print("enter the seat number:");
n=in.nextInt();
resSeat(n-1);
break;
case 2: System.out.print("enter the seat number:");
n=in.nextInt();
canSeat(n-1);
break;
case 3: viewAvl();
break;
case 4: viewRes();
break;
case 5: viewAll();
break;
case 6: System.exit(0);
default: System.out.println("wrong choice");
}
}
}
public static void main(String args[])
{
BusRes b=new BusRes();
b.menu();
}
}

You might also like