0% found this document useful (0 votes)
22 views22 pages

Java Lab Manual-2022 - Part B

The document is a lab manual for OOP and Design with Java, detailing various programming exercises. It covers concepts such as arrays, string manipulation, inheritance, abstraction, interfaces, exception handling, and file operations with Java. Each program includes code examples, outputs, and explanations to illustrate the respective concepts.

Uploaded by

panchamisri.01
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)
22 views22 pages

Java Lab Manual-2022 - Part B

The document is a lab manual for OOP and Design with Java, detailing various programming exercises. It covers concepts such as arrays, string manipulation, inheritance, abstraction, interfaces, exception handling, and file operations with Java. Each program includes code examples, outputs, and explanations to illustrate the respective concepts.

Uploaded by

panchamisri.01
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 and Design with Java Lab Manual-20CS43P

Program No.11: Code, execute and debug programs that uses array concept.

a) Java Program to illustrate how to declare, instantiate, initialize and traverse the Java array.

class OneDimArray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
[Link]("Elements of array are");
for(int i=0;i<[Link];i++) //length is the property of array
[Link](a[i]);
}
}
Output:
Elements of array are
10
20
70
40
50

b) Java Program to illustrate the use of multidimensional array

class MultiDimArray
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //declaring and initializing 2D array
//printing 2D array
[Link]("Elements of 2D array are");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
[Link](arr[i][j]+" ");
}
[Link]();
}

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 1


OOP and Design with Java Lab Manual-20CS43P

}
}

Output:
Elements of 2D array are
1
2
3

2
4
5

4
4
5

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 2


OOP and Design with Java Lab Manual-20CS43P

Program No.12: Code, execute and debug programs to perform string manipulation.
import [Link];
class StringDemo
{
public static void main(String arg[])
{
String s1 = new String("gpt athani");
String s2 = "GPT ATHANI";
[Link]("The string s1 is : " + s1);
[Link]("The string s2 is : " + s2);
[Link]("Length of the string s1 is : " + [Link]());
[Link]("Length of the string s2 is : " + [Link]());
[Link]("The String s1 in Upper Case : " + [Link]());
[Link]("The String s2 in Lower Case : " + [Link]());
[Link]("The first occurrence of a is at the position : "+ [Link]('a'));
[Link]("s1 equals to s2 : " + [Link](s2));
[Link]("s1 equals ignore case to s2 : " + [Link](s2));
[Link]("Character at an index of 6 is :" + [Link](6));
String s3 = [Link](4, 8);
[Link]("Extracted substring is :" + s3);
[Link]("After Replacing a with b in s1 : "+ [Link]('a', 'b'));
[Link]("After string concat :" + [Link](" Karnataka"));
String s4 = " This is a book "; //White space before This word.
[Link]("The string s4 is :" + s4);
[Link]("After string trim :" + [Link]());
int result = [Link](s2);
[Link]("After compareTo");
if (result == 0)
[Link](s1 + " is equal to " + s2);
else if (result > 0)
[Link](s1 + " is greater than " + s2);
else
[Link](s1 + " is smaller than " + s2);
}
}

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 3


OOP and Design with Java Lab Manual-20CS43P

Output:
The string s1 is : gpt athani
The string s2 is : GPT ATHANI
Length of the string s1 is : 10
Length of the string s2 is : 10
The String s1 in Upper Case : GPT ATHANI
The String s2 in Lower Case : gpt athani
The first occurrence of a is at the position : 4
s1 equals to s2 : false
s1 equals ignore case to s2 : true
Character at an index of 6 is :h
Extracted substring is :atha
After Replacing a with b in s1 : gpt bthbni
After string concat :gpt athani Karnataka
The string s4 is : This is a book
After string trim :This is a book
After compareTo
gpt athani is greater than GPT ATHANI

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 4


OOP and Design with Java Lab Manual-20CS43P

Program No.13: Code, execute and debug a program that implements the concept of
inheritance.
class Room
{
int length,breadth;
Room(int x, int y)
{
length = x;
breadth = y;
}
int area()
{
return (length * breadth);
}
}
class ClassRoom extends Room
{
int height;
ClassRoom(int x, int y, int z)
{
super(x, y);
height = z;
}
int volume()
{
return (length * breadth * height);
}
}
class SubClass
{
public static void main(String args[])
{
ClassRoom cr = new ClassRoom(20, 30, 10);
int area = [Link]();
int volume =[Link]();

[Link]("Area=" + area);
[Link]("Volume=" + volume);
}
}
Output
Area = 600
Volume = 6000

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 5


OOP and Design with Java Lab Manual-20CS43P

Program No.14: Design a class & implement like file parser and check compliance
with OCP.
class Cuboid
{
public double length;
public double breadth;
public double height;
}
class Application
{
public double get_total_volume(Cuboid geo_objects[])
{

double vol_sum = 0;
for (Cuboid geo_obj : geo_objects)
{
vol_sum += geo_obj.length * geo_obj.breadth * geo_obj.height;
}
return vol_sum;
}
}

public class OCP


{
public static void main(String args[])
{
Cuboid cb1 = new Cuboid();
[Link] = 5;
[Link] = 10;
[Link] = 15;

Cuboid cb2 = new Cuboid();


[Link] = 2;
[Link] = 4;
[Link] = 6;

Cuboid cb3 = new Cuboid();


[Link] = 3;
[Link] = 12;
[Link] = 15;

Cuboid c_arr[] = new Cuboid[3];


c_arr[0] = cb1;

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 6


OOP and Design with Java Lab Manual-20CS43P

c_arr[1] = cb2;
c_arr[2] = cb3;

Application app = new Application ();


double volume = app.get_total_volume(c_arr);
[Link] ("The total volume is " + volume);
}
}

Output:

The total volume is 1338.0

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 7


OOP and Design with Java Lab Manual-20CS43P

Program No.15: Code, execute and debug programs that uses


a. static binding
b. dynamic binding

a) Static binding
class Dog
{
private void eat()
{
[Link]("Dog is eating...");
}
public static void main(String args[])
{
Dog d1=new Dog();
[Link]();
}
}

Output:
Dog is eating...

b) Dynamic binding
class Animal
{
void eat()
{
[Link]("animal is eating...");
}
}
class Dog1 extends Animal
{
void eat()
{
[Link]("dog is eating...");
}
public static void main(String args[])
{
Animal a=new Dog1();
[Link]();
}
}

Output:
Dog is eating...

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 8


OOP and Design with Java Lab Manual-20CS43P

Program No.16: Code, execute and debug program that uses abstract class to
achieve abstraction.

abstract class Shape


{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape
{
void draw()
{
[Link]("drawing rectangle");
}
}
class Circle extends Shape
{
void draw()
{
[Link]("drawing circle");
}
}
//In real scenario, method is called by programmer or user
class TestAbstraction
{
public static void main(String args[])
{
Shape s=new Circle();
//In a real scenario, object is provided through method, e.g., getShape() method
[Link]();
}
}

Output: drawing circle

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 9


OOP and Design with Java Lab Manual-20CS43P

Program No.17: Code, execute and debug program that uses interface to
achieve abstraction.
interface Area
{
final static float pi = 3.142F;
float compute(float x, float y);
}

class Rectangle implements Area


{
public float compute(float x, float y)
{
return ( x * y);
}
}
class Circle implements Area

{
public float compute(float x, float y)
{
return (pi * x * x);
}
}

class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Circle cir = new Circle();
Area area;
area= rect;
[Link]("Area of Rectangle = " + [Link](10, 20));
area = cir;
[Link]("Area of Circle = " + [Link](30, 0));

}
}
Output:
Area of Rectangle = 200
Area of Circle =3070.8

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 10


OOP and Design with Java Lab Manual-20CS43P

Program No.18: Code, execute and debug program to read the content of the file and
write the content to another file.

(First create one text file- [Link] and another text file [Link] in C:drive\test folder )

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
class CopyContent
{
public static void main(String[] args) throws IOException
{
File file = new File("C:\\test\\[Link]");
FileInputStream inputStream = new FileInputStream(file);
Scanner sc = new Scanner(inputStream);
StringBuffer buffer = new StringBuffer();
while([Link]())
{
[Link](" "+[Link]());
}
[Link]("Contents of the file: "+buffer);
File dest = new File("C:\\test\\[Link]");
FileWriter writer = new FileWriter(dest);
[Link]([Link]());
[Link]();
[Link]("File copied successfully.......");
}
}
Output:
Contents of the file: Welcome to GPT Athani This is example for checked exceptions. It uses throws
keyword. Welcome to CS dept
File copied successfully.......

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 11


OOP and Design with Java Lab Manual-20CS43P

Program No.19: Code, execute and debug program that handles checked and
unchecked exceptions

a) Checked Exceptions:
import [Link].*;
class Checked
{
public static void main(String[] args)
{
FileReader file = new FileReader("C:\\test\\[Link]");
BufferedReader fileInput = new BufferedReader(file);
for (int counter = 0; counter < 3; counter++)
[Link]([Link]());
[Link]();
}
}
Output:

• To fix the above program, we either need to specify a list of exceptions using throws, or we
need to use a try-catch block. We have used throws in the below program.
Since FileNotFoundException is a subclass of IOException, we can just specify IOException in
the throws list and make the above program compiler-error-free.
import [Link].*;
class Checked
{
public static void main(String[] args) throws IOException
{
FileReader file = new FileReader("C:\\test\\[Link]");
BufferedReader fileInput = new BufferedReader(file);
for (int counter = 0; counter < 3; counter++)
[Link]([Link]());
[Link]();
}
}

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 12


OOP and Design with Java Lab Manual-20CS43P

Output:
Welcome to GPT Athani
This is example for checked exceptions.
It uses throws keyword.

a) Unchecked Exceptions:

class Unchecked
{
public static void main(String args[])
{
// Here we are dividing by 0 which will not be caught at compile time
// as there is no mistake but caught at runtime because it is mathematically incorrect
int x = 0;
int y = 10;
int z = y / x;
}
}
Output:

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 13


OOP and Design with Java Lab Manual-20CS43P

Program No.20: Code, execute and debug program to illustrate throwing our own
exceptions or user defined exceptions.

import [Link];
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class TestMyException
{
public static void main(String args[])
{
int x=5,y=1000;
try
{
float z=(float) x/(float) y;
if(z < 0.01)
{
throw new MyException(“Number is too small”);
}
}
catch(MyException e)
{
[Link](“Caught my exception”);
[Link]([Link]());
}
finally
{
[Link](“I am always here”);
}
}
}

Output:
Caught my exception
Number is too small
I am always here

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 14


OOP and Design with Java Lab Manual-20CS43P

Program No.21: Design an interface & implement it like one that builds different
types of toys and check compliance with ISP.
interface Toy
{
void setPrice(double price);
void setColor(String color);
}
interface Movable
{
void move();
}
interface Flyable
{
void fly();
}
class ToyHouse implements Toy
{
double price;
String color;
@Override
public void setPrice(double price)
{
[Link] = price;
}
@Override
public void setColor(String color)
{
[Link]=color;
}
@Override
public String toString()
{
return "ToyHouse: Toy house- Price: "+price+" Color: "+color;
}
}

class ToyCar implements Toy, Movable


{
double price;
String color;
@Override
public void setPrice(double price)
{
[Link] = price;
}
@Override
public void setColor(String color)
{
[Link]=color;
}

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 15


OOP and Design with Java Lab Manual-20CS43P

@Override
public void move()
{
[Link]("ToyCar: Start moving car.");
}
@Override
public String toString()
{
return "ToyCar: Moveable Toy car- Price: "+price+" Color: "+color;
}
}

class ToyPlane implements Toy, Movable, Flyable


{
double price;
String color;
@Override
public void setPrice(double price)
{
[Link] = price;
}
@Override
public void setColor(String color)
{
[Link]=color;
}
@Override
public void move()
{
[Link]("ToyPlane: Start moving plane.");
}
@Override
public void fly()
{
[Link]("ToyPlane: Start flying plane.");
}
@Override
public String toString()
{
return ("ToyPlane: Moveable and flyable toy plane- Price: "+price+"Color: "+color);
}
}

class ToyBuilder
{
public static ToyHouse buildToyHouse()
{
ToyHouse toyHouse=new ToyHouse();
[Link](15.00);
[Link]("green");

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 16


OOP and Design with Java Lab Manual-20CS43P

return toyHouse;
}
public static ToyCar buildToyCar()
{
ToyCar toyCar=new ToyCar();
[Link](25.00);
[Link]("red");
[Link]();
return toyCar;
}
public static ToyPlane buildToyPlane()
{
ToyPlane toyPlane=new ToyPlane();
[Link](125.00);
[Link]("white");
[Link]();
[Link]();
return toyPlane;
}
}

public class ToyISPTest


{
public static void main(String[] args)
{
// TODO Auto-generated method stub
ToyHouse toyHouse=[Link]();
[Link](toyHouse);
ToyCar toyCar=[Link]();;
[Link](toyCar);
ToyPlane toyPlane=[Link]();
[Link](toyPlane);
}
}

Output:
ToyHouse: Toy house- Price: 15.0 Color: green
ToyCar: Start moving car.
ToyCar: Moveable Toy car- Price: 25.0 Color: red
ToyPlane: Start moving plane.
ToyPlane: Start flying plane.
ToyPlane: Moveable and flyable toy plane- Price: 125.0 Color: white

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 17


OOP and Design with Java Lab Manual-20CS43P

Program No.22: Code, execute and debug programs to connect to database through
JDBC and perform basic DB operations.

Step 1: In addition to JDK and Eclipse environment, install Xampp software for Apache server and
MySql service.
Step 2: Now open Xampp control panel to start Apache and MySql services as shown below. Then click
on MySql-Admin button to open MySql [Link] in brower.

Step 3: To connect MySql databse in Java using Eclipse, follow below steps.

 Open Eclipse IDE and create new Java project named JavaJDBC and click finish.
 Create a new Java class with DBTest and click on the finish button.
 In order to connect Java program ([Link]) with MySQL database, we need to download and
include MySQL JDBC driver which is a JAR file, namely [Link].
 Now right click on JavaJDBC project to include connector and go to properties.
 Click on Java build path option-> click on libraries and then click on Add External JARS.
 Now select downloaded jar file [Link]. & click open.
 Click on OK and close.

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 18


OOP and Design with Java Lab Manual-20CS43P

Step 4: Now in browser go to myphpadmin page and create student table in test database with following
fields as shown below and click save.

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 19


OOP and Design with Java Lab Manual-20CS43P

Connecting Java Program with MySQL Database


 After adding jar file, connect the Java program with MySQL Database.
i)Establish a connection using [Link](String URL) and it returns a
Connection reference.
ii) In String URL parameter write like this :
jdbc:mysql://localhost:3306/test”, “root”, “password”
Where,
 jdbc is the API.
 mysql is the database.
 localhost is the name of the server in which MySQL is running.
 3306 is the port number.
 test is the database name. If the database name is different, then replace this name with the
correct database name.
 root is the username of the MySQL database. It is the default username for the MySQL
database.
 password is the password that is given while installing the MySQL database.
 SQL Exception might occur while connecting to the database, try-catch block must be used.

Step 5: Write below code in DBTest class Eclipse environment.

import [Link].*;
public class DBTest
{
public static void main(String[] args)
{
String url= "jdbc:mysql://localhost:3306/test"; // table URL
String uname = "root"; // MySQL credentials
String pw = "";
try
{
//Loading MySQL Driver
[Link]("[Link]");
// Establishing connection with MySQL
Connection con = [Link](url,uname,pw);
[Link]("Java Connection to MySQL Established successfully");
// Creating Statement object for query execution
Statement st=[Link]();
// Delete the table student if already present in the test database
String deltbl= "DROP TABLE STUDENT";
[Link](deltbl);
// Create a table STUDENT in database test

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 20


OOP and Design with Java Lab Manual-20CS43P

String qrytbl= "CREATE TABLE STUDENT(regno int,name varchar(30),sem int)";


[Link](qrytbl);
// Insert values into the STUDENT table
String qry1="INSERT INTO STUDENT values(2001,'Anand',4)";
[Link](qry1);
String qry2="INSERT INTO STUDENT values(2002,'Santosh',4)";
[Link](qry2);
String qry3="INSERT INTO STUDENT values(2003,'Ullas',4)";
[Link](qry3);
[Link]("Table Values insertion is successful");
// Query to retrieve values from table
String query= "SELECT * FROM STUDENT";
ResultSet rs = [Link](query);//Execute query
while ([Link]())
{
//Retrieve row-wise values of regno, name and sem columns
int regno = [Link]("regno");
String name= [Link]("name");
int sem=[Link]("sem");
// Display the result on console
[Link](regno + " " + name+ " "+ sem);
}
[Link](); // close statement
[Link](); // close connection
[Link]("MySQL Connection Closed successfully!");
}
catch(Exception e)
{
[Link]("Error while executing program:" + e);
}
}
}
Output:

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 21


OOP and Design with Java Lab Manual-20CS43P

Govt. Polytechnic Athani-591304 Dist: Belgaum Page 22

You might also like