0% found this document useful (0 votes)
6 views55 pages

Oop With Java Lab Manual

The document provides a comprehensive guide for setting up and using Java with Eclipse IDE, covering installation of JDK, configuration of environment variables, and creating Java projects. It includes step-by-step instructions for writing and executing Java programs, along with examples for calculating areas of geometric shapes and implementing classes. The document is structured into weeks, detailing various programming exercises to enhance understanding of Object Oriented Programming concepts in Java.

Uploaded by

chiru JM
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)
6 views55 pages

Oop With Java Lab Manual

The document provides a comprehensive guide for setting up and using Java with Eclipse IDE, covering installation of JDK, configuration of environment variables, and creating Java projects. It includes step-by-step instructions for writing and executing Java programs, along with examples for calculating areas of geometric shapes and implementing classes. The document is structured into weeks, detailing various programming exercises to enhance understanding of Object Oriented Programming concepts in Java.

Uploaded by

chiru JM
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

Object Oriented Programming and Design with Java

Week 1 :

1. Install and Setup java environment


You can download the JDK 8 from this link click (CTRL + CLICK) here  jdk software
or
You can download from [Link]
For versions other than latest versions we need to have to create an account on Oracle

Step 1: click on the jdk-23_windows-x64_bin.exe file and click on Next button

Step 2: if you want to change the path change it or else let it be default depends on your convenience. And click on
to Next

Step 3: This gives the window for installing wait till it goes to another window.
Step 4: if you want to change the JRE path you can change it or let it be default depends on your convenience and
click on to Next
Step 5: wait until it completes
Step 6: Now you have successfully installed JDK software only when you click Finish/close button. After
installing your JDK your work is not done Still lot more things to do….

Open the command prompt and give javac command you get the above error as javac is not recognized as an internal
or external command. So you need to set the path.
Here how it goes…
After installing the JDK, you must set environment variables to ensure the P6 EPPM installation scripts can locate your Java
libraries
To set Java environment variables:
 JAVA_HOME
 PATH
Setting the Environment Variables in Microsoft Windows
To set the JAVA_HOME and PATH environment variables in Microsoft Windows:
1. Click Start, Control Panel, System, and then Advanced system settings.
2. In the System Properties dialog box, on the Advanced tab, click Environment Variables.
3. Add the JAVA_HOME environment variable:
a. In the System Variables section, click New.
b. In the Variable name field, enter JAVA_HOME.
c. In the Variable value field, enter the location where the JDK software is installed (for example, C:\
Program Files\Java\<java_version>)
d. Click OK.
4. Update the PATH environment variable to include the location of the Java executable files:
a. In the System Variables section, select the PATH variable, and click Edit.
b. In the Variable value field, insert %JAVA_HOME%\bin; in front of all the existing directories. Do not
delete any existing entries; otherwise, some existing applications may not run.
c. Click OK.
5. Exit the Control Panel.
Setting the Environment Variables with Unix or Linux
To set the JAVA_HOME and PATH environment variables with Unix or Linux:
1. Set the JAVA_HOME environment variable by typing the following command:
export JAVA_HOME=<JDK_installation_path>
2. Set the PATH environment variable by typing the following command:
export PATH=$PATH:$JAVA_HOME/bin
[Link] java editor (Eclipse for Enterprise Java) and configure workspace
[Link] to the Oracle Java downloads page for Eclipse Java download.
[Link] the JDK that you want to download and install. As you scroll down on the page, you will see multiple versions of
JDK available, choose the one that fits your needs based on the Eclipse that you want to download.
[Link] the installation instructions and install the Eclipse JDK. Once you have JDK on your system, you are set to
install Eclipse.

To install and configure Eclipse, you can do the following:


Go to the [Link] and you will see something like below.

On that page the latest version will be displayed for download, you can directly click on download 64 bit (this depends on
the OS you have on your machine) or click on download packages to view more packages available.

On clicking download packages, the following page will be displayed with multiple Eclipse versions.
You can choose to go with the latest version, or if you want to go with a previous version, click on the one you want from
the highlighted other versions. Once you click on that a similar list of available Eclipse IDE download links will be
displayed for that version.

Select Eclipse IDE for Java developers and select the download link from one of the below depending on the operating
system of your machine.

Once you select the OS type download link, you will be redirected to the following page.

As soon as you click the highlighted link, the download begins and after some time the downloaded zipped file will be
saved in your machines downloads folder.

Extract the contents of this Zip folder, and you will get a folder by the name of “Eclipse” and place this in the C drive.
You should see the below folder structure once you are done with the above steps.

Eclipse IDE does not require installation, once you have this folder structure look for the Eclipse executable file
highlighted above. Launching this executable file opens the IDE for your use.

Setting Up Your Eclipse Workspace

Once you have the Eclipse application on your machine, you can launch the IDE simply by clicking on the executable
file. However, the first time you open Eclipse, you will be asked to create a workspace.

A workspace is a location on your machine where all the work you do through Eclipse will be stored as files. It is easier
to create one workspace and save it as default so that your application remembers your past work.

Once you open Eclipse, you will see the below image.

The following window will show up after a few seconds.


Here you can see the highlighted default workspace location. If you are fine with this, then simply click the launch button.
If you want to create a workspace in a specific location on your machine, then browse to that folder and then click launch.

You can see the checkbox asking to use the location as default checked, this is to ensure that the next time when you
launch Eclipse it automatically opens the same workspace, so that you have access to all the work saved in this location.

After clicking the launch button, it may take some time for the Eclipse workbench to open. This is because the workspace
is being created or in case of an existing workspace, the projects, etc. maybe fetched. Hence, do not worry if it takes a few
minutes.

Once the workbench is launched, you will see the following default view.

This default view is the welcome page of Eclipse. As a beginner, you may want to read through some of the links given
regarding the tutorials or samples to gain a better or detailed understanding. You can also read through the “What’s new”
section to see what this latest version of Eclipse has.

If you do not want to see the welcome page when you launch Eclipse in future, then you can turn it off by unchecking the
checkbox highlighted at the bottom of the page or you can simply close the welcome page by clicking on the closed sign
on the title of the welcome page.

After closing the welcome page, you will see the following view.
At this point, you have successfully launched your Eclipse IDE workbench and are ready to start creating your first code.

Before we get into creating projects and writing actual codes, there are few more setup related things that you must know.
These are environment variables. Eclipse automatically configures itself to the available JRE in the system, if you have
set the environment variables at the time of setting up Java.

The primary environment variables include:


1. JAVA_HOME: Point to JDK folder.
2. JRE_HOME: Point to JRE folder
3. Path: It is added above the locations to an existing variable. Please ensure that you do not delete anything that is
already present in this variable, just add your new folder locations. In Eclipse, if you want to update any path related to
Java files, then you can do this by going to preferences (Go to top menu item Window-> Preferences) and the below
window will open up.
3. Execution of first java program

Creating and Running Your First Java Project in Eclipse


To create a simple first Java project follow the steps:
Step 1) Click on File -> New -> Java project.

Step 2) The following window will open:


Give a name to your project in the highlighted text field. While creating a formal project the name should
have a logical sense, however as we are in the learning process, for now, you can name your project as
“MyFirstProject” and leave the rest of the fields as default and click next.

Step 3) The following screen opens up:


Leave all the options as it is and click on finish.

You will see the following structure created in your project explorer.

Here you can see two sub-items under your project name. The JRE system library is the default Java library
that Eclipse adds to your project. This library provides Java support and without this, you cannot proceed
with creating a Java project. The other folder is the “src” folder or the source folder. Your project structure
will get created inside this.
Step 4) You now have your base project structure, let’s add more to this. In Java, we have packages and
classes. Packages provide logical separation for classes. Packages are just folders, whereas classes are
where you write your actual code.
To create a package right-click on your project name as shown below. Click on the package:

Java says package names should be in a small case, so give any name such as “myfirstpackage” and click on
finish.

Check your Project Structure.

Step 5) Next, you need to create a class, and this is where your actual code will go. Right-click on the
package name as shown below.
Click on the class: Give a name to your class and keep the modifier selected as public. While creating a
simple Java project, ensure to check the checkbox for creating the method “public static void
main(String[]args)”.

Click on finish, and now your project will look as shown below.
You can see that the class is created and as we selected the main method to be added, the method signature
is added to the class. Similar to a class you can also create an interface by following the same steps and by
selecting “New Interface”.

Step 6) As we have successfully created a project and class, let’s put a simple print statement in it and run
the same to check the output.

Write the below code and save :


package myfirstpackage;
public class MyFirstClass
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
[Link]("This is my first code");
}
}

Once you have saved the file there are multiple places from where you can run it as a Java application.

a) Keep your cursor on the class that you want to run and click on this icon:
b) Right-click on the class name in the project explorer and select Run as and click as shown below.

c) Select the class name in the project explorer and then select the Run option from the top menu -> select
Run As and then click on Java application.
Step 7) As soon as you run your class from any of the above places, a console window opens up in the
bottom pane of your workbench and displays the output of your program.

The console in Eclipse displays the runtime logs while your application is running. In a simple application
like ours, it is simply the output of the print statement, however, in complex projects, there may be a lot
more information displayed.
The console also displays error information if your program encounters any exceptions while running. So
in this section, we have created a simple project and seen how we can run it and see the output generated by
your code.
Apart from classes, there are many other types of files that you can create in Eclipse which can be used in a
Java project such as XML files, interfaces, or even simple files.

You can explore the types of files or types of projects that you can create by clicking on File-> New->
Others, and the following wizard will open up.
However, as a beginner, you may leave these for a while and work with the simple Java project by adding
more packages and classes as you need.
Week 2:

Program 3. Develop a Java program to calculate the area of the circle.

import [Link];

class Circle
{
public static void main(String args[])
{
Scanner s = new Scanner([Link]);
double radius;
double area ;
double PI = 3.142;
[Link]("Enter the radius:");
radius = [Link]();
area = PI * radius * radius ;
[Link]("The area of the circle is = " + area);

output:

Program 4 : Develop a Java program to calculate the area of the Triangle.

import [Link];
class Triangle
{

public static void main(String args[])


{
Scanner s = new Scanner([Link]);
double base;
double height;
double area;
[Link]("Enter the base of the triangle:");
base = [Link]();
[Link]("Enter the height of the triangle:");
height = [Link]();

area = 0.5 * base * height;


[Link]("The area of triangle is " + area);
}
}
Output:

Program 5: Develop a Java Program to calculate Simple interest for the given principal , time and rate of
interest.

import [Link];
class SimpleInterest
{

public static void main(String args[])


{
Scanner s = new Scanner([Link]);
double p,t,r,si;

[Link]("Enter the Principal amount:");


p = [Link]();
[Link]("Enter the time in years:");
t = [Link]();
[Link]("Enter the rate of interest:");
r = [Link]();
si = (p * t * r) / 100 ;
[Link]("The Simple interest is " + si);
}
}

Output:
Program 6: Develop a Java Program to convert given temperature in Fahrenheit to Celsius scale.
import [Link];
class Celsius
{

public static void main(String args[])


{
Scanner s = new Scanner([Link]);
double f , c ;

[Link]("Enter the temperature in Farenheit:");


f = [Link]();
c = ( f - 32 ) * 5/ 9 ;

[Link]("Thetemperature in celsius is " + c);


}
}

Output:

Program 7: Develop a java program to create class called Student


a) with attributes regno , sem , name and age .
b) with methods setdata() , displaydata() and promote() .
create an object of Student class and demonstrate using methods with sample data.

class Student
{
int regno;
int sem;
double age;
String name;

int promote()
{
sem = sem + 1;
return sem;
}

void setdata( int reg , int semester, double sage , String sname)
{
regno = reg;
sem = semester;
age = sage;
name = sname;

}
void displaydata()
{
[Link]("Register number = " + regno);
[Link]("Semester = " + sem);
[Link]("Age = "+ age);
[Link]("Name = " + name);
}
}

class StudentTest
{
public static void main( String args[])
{
Student sobj ;
int newsem;
sobj = new Student();
[Link]("Student details with Default values " );
[Link]();
[Link](1234, 4, 17 , "MS Dhoni");
[Link]("Student details with values " );
[Link]();
newsem = [Link]();
[Link]("After calling promote " );
[Link]("New semester is = " + newsem);
[Link]();
}
}

Output:
Week 3:

Program 8: Develop a java program to create class called Employee


a) With attributes empid, empsalary , empname , empemailid ,
b) With methods setdata() and displaydata() .
c) Design different types of constructors (default and parameterized).
Create objects of class Employee using different constructors with sample data.

class Employee
{
int empid;
double empsalary;
String empname;
String empemailid;

Employee()
{
[Link]("No arguments constructor called");

Employee(int id , double salary, String name, String emailid)


{
this(salary,name,emailid);
[Link]("4 arguments constructor called");
empid = id;
}

Employee( double salary, String name, String emailid)


{
[Link]("3 arguments constructor called");
empsalary = salary;
empname = name;
empemailid = emailid;

void setdata(int id , double salary , String name, String emailid )


{
empid = id;
empsalary = salary;
empname = name;
empemailid = emailid;

void displaydata()
{ [Link]("Employee details");
[Link]("Emp id = " + empid);
[Link]("Empsalary = " + empsalary);
[Link]("Emp name = " + empname);
[Link]("Emp emailid = " + empemailid);
}
}
class EmpTest
{

public static void main(String args[])


{

Employee empobj , obj2 ;


empobj = new Employee(1111,500000,"kohli", "asdf@[Link]" );
[Link]();
obj2 =new Employee();
[Link]();
[Link](2222, 750000, "gayle", "cg@[Link]");
[Link]();

}
}

Output:

Program 9: Develop a java program to demonstrate expression evaluation.

class Expression

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

int a = 10, b = 5, c = 8, d = 2;
float x = 6.4f, y = 3.0f;

// precedence
int answer1 = a * b + c/d;
int answer2 = a * (b + c) / d;

// Type conversions
float answer3 = a / c;
float answer4 = (float) a / c;
float answer5 = a / y;

// Modulo operations
int answer6 = a % c;
float answer7 = x % y;

//Logic operations
boolean bool1 = a > b && c > d;
boolean bool2 = a < b || c > d;
boolean bool3 = !( a - b == c);

[Link]("order of evaluation");

[Link]("a * b + c/d = " + answer1);


[Link]("a * (b + c) / d = " + answer2);

[Link]("Type Conversion");
[Link]("a / c = " + answer3);
[Link]("(float) a / c = " +answer4 );
[Link]("a / y = " + answer5);

[Link]("Modulo operation");
[Link]("a % c =" + answer6);
[Link]("x % y =" + answer7);

[Link]("Logical operations");
[Link]("a > b && c > d =" + bool1);
[Link]("a < b || c > d =" + bool2);
[Link]("!( a - b == c)" + bool3);

}
}

Output:

Program 10: Develop a java program to perform Autoboxing and unboxing.

class Autoboxing
{
public static void main(String args[])
{
byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c='a';
boolean b2=true;

//Autoboxing: Converting primitives into objects


Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;

//Printing objects
[Link]("---Printing object values---");
[Link]("Byte object: "+byteobj);
[Link]("Short object: "+shortobj);
[Link]("Integer object: "+intobj);
[Link]("Long object: "+longobj);
[Link]("Float object: "+floatobj);
[Link]("Double object: "+doubleobj);
[Link]("Character object: "+charobj);
[Link]("Boolean object: "+boolobj);

//Unboxing: Converting Objects to Primitives


byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;

//Printing primitives
[Link]("---Printing primitive values---");
[Link]("byte value: "+bytevalue);
[Link]("short value: "+shortvalue);
[Link]("int value: "+intvalue);
[Link]("long value: "+longvalue);
[Link]("float value: "+floatvalue);
[Link]("double value: "+doublevalue);
[Link]("char value: "+charvalue);
[Link]("boolean value: "+boolvalue);
}
}
Output:

Week 4:

Program 11: Install memory monitoring tool and observe how JVM allocates memory.
VisualVM provides detailed information about Java applications while they are running on the Java Virutal
Machine (JVM). VisualVM's graphical user interface enables you to quickly and easily see information about
multiple Java applications.

Installing VisualVM
 Download the VisualVM installer from the VisualVM project page.
 Extract the VisualVM installer to an empty directory on your local system.

Starting VisualVM
 To start VisualVM on Windows, run the [Link] program that is in the \bin folder under the
VisualVM install folder.
 After opening VisualVM, we can double click on icons of the different java applications which appears
on left panel in the Applications window.
 We run the java sample program [Link]

Exploring VisualVM

 We can click on the application icon which needs to be explored further in the Left panel (Application
window)
 Click on overview tab to know more about JVM arguments, System Properties etc.
 Click on monitor tab to understand about CPU usage, Heap Space, Classes and Threads. Observe how
memory is managed by JVM.
 Click on Heap Dump (right-side corner) in monitor tab to know about classes, instances, and
environment.
 Click on threads to know how many types threads are running in live and finished threads.
 Click on sampler to know CPU samples, Memory Samples.

Snapshot of the monitor tab of the Running program:


Snapshot of Heap Dump of the Program:

Source code of [Link]:


class Sample
{

String name ;

Sample()
{

Sample( String val)


{

name = val;
}

class Infinity

{
public static void main(String args[])

{ Sample[] obj = new Sample[1000000] ;


int i = 0;
while(i < 999999)
{

obj[i] = new Sample("Hello");


[Link]("Hi");
i++;

Week 5: Code, execute and debug programs that uses different control statements.
Identify and resolve issues in the given code snippet.

Program 12: Develop a java program to print the Result of the student according to the conditions below using
if – else – if Ladder control statement.
i) Percentage 40 – 50 ----- Pass Class
ii) Percentage 51 – 60 ----- Second Class
iii) Percentage 61 – 70 ----- First Class
iv) Percentage 71– 100 ----- Distinction

import [Link];

class Result{

public static void main(String args[])


{

Scanner s = new Scanner([Link]);


double per;

[Link]("Enter the percentage of student:");


per = [Link]();

if(per >= 40 && per < 50)


[Link]("pass class");
else if ( per >= 50 && per < 60)
[Link]("Second class");
else if(per >= 60 && per < 70)
[Link]("First class");
else if( per >= 70 && per <= 100)
[Link]("Distinction");
else
[Link]("Better luck next time");

}
}

Output:

Program 13: Develop a java program to implement Basic calculator using Switch statement.
import [Link];

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

Scanner s = new Scanner([Link]);


double a ,b ,res;
int choice;

[Link]("Please enter first number :");


a = [Link]();
[Link]("Please enter second number :");
b = [Link]();

[Link]("1:Add ,2: subtract 3: Multiply 4: Divide");


[Link]("Please enter your choice:");
choice = [Link]();

switch(choice)
{
case 1 : res = a + b;
[Link]("sum of numbers is :" + res);
break;

case 2 : res = a - b;
[Link]("Difference of numbers is :" + res);
break;

case 3 : res = a * b;
[Link]("product of numbers is :" + res);
break;

case 4: res = a / b;
[Link]("quotient of division is :" + res);
break;
default :[Link]("Invalid choice");
break;

}
Output:

Program 14: Develop a java program to find whether the given 3-digit number is Armstrong number or not.
An Armstrong number is a number that is equal to the sum of the cubes of its digits.
For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.

import [Link];

class Armstrong
{

public static void main(String args[])


{
Scanner s = new Scanner([Link]);
int num , org ,rem,sum;
[Link]("Enter the 3 digit number:");
num = [Link]();
org = num;
sum = 0;

while( num > 0)


{

rem = num % 10;


sum = sum + (int)[Link](rem,3);
num = num / 10;
}
if( org == sum)
[Link]("The given num " + org + " is Armstrong number") ;
else
[Link]("The given num " + org + " is not an Armstrong number") ;
}
}

Output:

Program 15: Develop a java program to find the factorial of a given number.
import [Link];

class Factorial
{

public static void main(String args[])


{
Scanner s = new Scanner([Link]);
int i, num, fact = 1;
[Link]("Enter the number to find factorial:");
num = [Link]();

for ( i = num ; i >= 1 ; i--)


{
fact = fact * i;
}

[Link]("The factorial of number " + num + " is " + fact);


}
}

Output:

Program 16: Develop a java program to find whether the given number is prime or not.
import [Link];

class Prime
{
public static void main(String args[])
{
int num , i , flag = 0;

Scanner s = new Scanner([Link]);


[Link]("Enter the number:");
num = [Link]();

for( i = 2 ; i < num/2 -1; i++)


{
if( num % i == 0)
{ flag = 1;
break;
}
}

if(flag == 1)
[Link]("The given num " + num + " is not a prime number");
else
[Link]("The given num " + num + " is a prime number");
}
}

Output:

Week 6: a ) Code, execute and debug programs that uses encapsulation concept.
b) Define class & implement like simple calculator and check compliance with SRP.

Program 17: Develop a java program to create a class called Person with getters and setters to demonstrate
Encapsulation.

import [Link];
class Person {

private String name;


private int age;

public String getName() { return name; }


public void setName(String name) { [Link] = name; }
public int getAge() { return age; }
public void setAge(int age) { [Link] = age; }
}

public class Encapsulation {

public static void main(String[] args)


{
Scanner s = new Scanner([Link]);
String name;
int age;
Person p = new Person();
[Link]("Please enter the name of person:");
name = [Link]();
[Link](name);
[Link]("Please enter the age of person:");
age = [Link]();
[Link](age);

[Link]("Name: " + [Link]());


[Link]("Age: " + [Link]());
}
}

Output:
Program 18: Develop a java program to create a user defined package and demonstrate using it.

Step1: Create a sub directory under the directory where main source files are stored. ( create folder Mypack)
Step 2: Create the classes that are to be put in the package and declare them public. Declare the package at the
beginning of a file.
Step 3: Store the files by naming them using their class names “Classname”.java ([Link] and
[Link]). in the sub directory(Mypack) created.
Step 4: Compile the files. This creates .class files in the sub directory.

File [Link] :
package mypack;

public class ClassA


{

public void displayA()


{
[Link](" this is from mypack package Class A");

File [Link]:
package mypack;

public class ClassB


{
public void displayB()
{
[Link](" this is from mypack package Class B");
}

Create a file [Link] outside the package sub directory to demonstrate package importing.

import mypack.*;

class PackageTest
{
public static void main(String args[])
{
ClassA obja = new ClassA();
ClassB objb = new ClassB();
[Link]();
[Link]();

Output:
Program 19: Develop a java program to define a Class and implement Simple calculator and check compliance
with Single Responsibility Principle.

class Calculator
{
public static int add(int x, int y) { return x + y; }
public static int sub(int x, int y) { return x - y; }
public static int mul(int x, int y) { return x * y; }
public static int div(int x, int y) { return x / y; }
}

class ResultPrinter {
public static void printResult(int value)
{
[Link]("The value is="+value);
}
}

public class CalcDemo


{
public static void main(String args[])
{ int res;
res = [Link](20, 30);
[Link](res);
res = [Link](20, 30);
[Link](res);
res = [Link](20, 30);
[Link](res);
res = [Link](20, 30);
[Link](res);

}
}

Output:
Week 7: a) Code, execute and debug programs that uses array concept
b) Code, execute and debug programs to perform string manipulation.

Program 20: Develop a java program to perform Linear Search on a array of integers.

import [Link];

class LinearSearch
{
public static void main(String args[])
{
Scanner s = new Scanner([Link]);
int nums[] , n , i , val, key ,flag = 0;

[Link]("Enter the size of array:");


n = [Link]();
nums = new int[n];

for( i = 0;i < [Link];i++)


{
[Link]("Enter the " + (i + 1) + " number:");
val = [Link]();
nums[i] = val;
}
[Link]("Enter the key element to search:");
key = [Link]();

for(i =0;i< [Link];i++)


{
if( key == nums[i])
{ flag = 1;
break;
}
}

if(flag == 1)
[Link]("Search successful item is found at position " + (i+1));
else
[Link]("Search unsuccessful item is not found ");
}

Output:

Program 21: Develop a java program to perform String manipulation.


import [Link];

class StringExample1
{

public static void main(String args[])


{
int choice;
String s1 , s2;
char ch , ch2;
Scanner s = new Scanner([Link]);
for(;;)
{
[Link]("1: concat 2: Find Char 3:Replace char 4:Check if equal");
[Link]("Please enter your choice:");
choice = [Link]();

switch(choice)
{
case 1: [Link]("Enter the first string:");
s1 = [Link]();
[Link]("Enter the second string:");
s2 = [Link]();
[Link]("result is " + [Link](s2));
break;
case 2: [Link]("Enter the string:");
s1 = [Link]();
[Link]("Enter the character to find:");
ch = [Link]().charAt(0);
[Link]("character is found at " + [Link](ch));
break;
case 3: [Link]("Enter the string:");
s1 = [Link]();
[Link]("Enter the character to replace:");
ch = [Link]().charAt(0);
[Link]("Enter the new character:");
ch2 = [Link]().charAt(0);
[Link]("result is " + [Link](ch , ch2));
break;
case 4: [Link]("Enter the first string:");
s1 = [Link]();
[Link]("Enter the second string:");
s2 = [Link]();
[Link]("result is " + [Link](s2));
break;
default: [Link]("Invalid choice");
[Link](0);

}
}
}
Output:
Week 8: a) Code, execute and debug programs that uses inheritance concept.
b) Design a class, implement and check compliance with OCP.

Program 22: Develop a java program to develop a class called Room and extend it to demonstrate Inheritance.

class Room
{ double length;
double breadth;

Room( double l , double b)


{
length = l;
breadth = b;
}

double area()
{ return length * breadth;
}
}

class OfficeRoom extends Room


{
double height;

OfficeRoom( double l , double b , double h)


{ super(l , b);
height = h;
}

double volume()
{ return length * breadth * height;
}
}

class InheritanceTest
{
public static void main( String args[])
{
OfficeRoom orobj = new OfficeRoom(10,20,11);
double rarea;
double rvol;

rarea = [Link]();
rvol = [Link]();

[Link]("The area of office room is" + rarea);


[Link]("The volume of office room is" + rvol);
}
}
Output:

Program 23: Develop a java program to demonstrate Open closed Principle.


abstract class Shape
{
abstract double calculateArea();
}

class Circle extends Shape {


private double radius;

public Circle(double radius) {


[Link] = radius;
}

public double calculateArea() {


return [Link] * radius * radius;
}
}

class Rectangle extends Shape {


private double width;
private double height;

public Rectangle(double width, double height) {


[Link] = width;
[Link] = height;
}

public double calculateArea() {


return width * height;
}
}

class AreaCalculator {
public double calculateArea(Shape shape) {
return [Link]();
}
}

public class OCP {


public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 5);

AreaCalculator calculator = new AreaCalculator();


[Link]("Circle area: " + [Link](circle));
[Link]("Rectangle area: " + [Link](rectangle));
}
}

Output:

Week 9: Code, execute and debug programs that uses


a. static binding b. dynamic binding.
Program 24: Develop a java program to demonstrate Static Binding.

class Adder{
public int add(int a, int b){
return a + b;
}
public int add(int a, int b, int c){
return a + b + c;
}
}

public class StaticBinding {


public static void main(String args[]){
Adder adderobj = new Adder();
[Link]([Link](20, 40));
[Link]([Link](40, 50, 60));
}
}

Output:

Program 25: Develop a java program to demonstrate Dynamic binding.

class A
{

void callme()
{
[Link]("Inside A call me method");
}
}

class B extends A
{

void callme()
{ [Link]("Inside B call me method");
}
}

class C extends A
{
void callme()
{
[Link]("Inside C call me method");
}
}

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

A a = new A();
B b = new B();
C c = new C();
Ar;

r=a;
[Link]();
r = b;
[Link]();
r = c;
[Link]();

}
}

Output:
Week 10: Code, execute and debug programs that uses
a) abstract class to achieve abstraction
b) interface to achieve abstraction

Program 26: Develop a java program to design abstract class to achieve abstraction.

abstract class Account


{
abstract double withdraw(double amount);
abstract double deposit(double amount);
}

class SbAccount extends Account


{
private double balance;

SbAccount( double bal)


{
balance = bal;
}

double withdraw(double w_amount)


{
if(balance >= w_amount)
{ balance = balance - w_amount;
[Link]("withdrawn rupees" + w_amount);
}
else
[Link]("Insufficient balance");

return balance;
}
double deposit(double d_amount)
{
balance = balance + d_amount;
[Link]("deposited rupees"+ d_amount);
return balance;

double getbalance()
{ return balance;
}
}

class AbstractClassDemo
{
public static void main(String args[])
{
SbAccount accobj = new SbAccount(50000);
[Link]("Balance in account is = " + [Link]());
[Link](5000);
[Link]("Balance in account is = " + [Link]());
[Link](10000);
[Link]("Balance in account is = " + [Link]());
}
}

Output:
Program 27: Develop a java program to design interface to achieve abstraction.

interface Vehicle {
void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}

class Bike implements Vehicle {


int speed;
int gear;

Bike( int sp , int gr)


{
speed = sp;
gear = gr;
}

public void changeGear(int newGear){


gear = newGear;
}

public void speedUp(int increment){


speed = speed + increment;
}

public void applyBrakes(int decrement){


speed = speed - decrement;
}

public void printStates() {


[Link]("speed: " + speed
+ " gear: " + gear);
}

class InterfaceDemo
{
public static void main (String[] args)
{
Bike bike = new Bike(25 , 1);
[Link](2);
[Link](3);
[Link](4);
[Link]("Bike present state : ");
[Link]();
}
}

Output:
Week 11: Code, execute and debug programs in java to
a) handles checked and unchecked exceptions.
b) read the content of the file and write the content to another file
Program 28: Develop a java program to demonstrate checked exception

import [Link].*;
import [Link];

class CheckedException {

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


{
Scanner s = new Scanner([Link]);
String ifn;
String str="";
[Link]("Enter the file name to read:");
ifn = [Link]();

FileReader fr = new FileReader(ifn);


int i;
while ((i = [Link]()) != -1)
{
str += (char)i;
}
[Link]();
[Link]("File reading done");
[Link]("contents of file:");
[Link](str);
}
}

Output:
Program 29: Develop a java program to demonstrate unchecked exception.

import [Link];
class UncheckedException
{
public static void main( String args[])
{

int a = 0,b = 0,c = 0,x,y;


Scanner s = new Scanner([Link]);

try
{ [Link]("Enter the value for a:");
a = [Link]();
[Link]("Enter the value for b:");
b = [Link]();
[Link]("Enter the value for c:");
c = [Link]();
x = a /( b-c);
[Link]("The value of x = " + x);
}

catch( ArithmeticException e)
{
[Link]("Division by zero");
}

y = a/ (b+c);
[Link]("y = " + y);
}
}

Output:
Program 30: Develop a java program to read the content of the file and write the content to another file.

import [Link].*;
import [Link];

class FileHandling {

public static void main(String[] args)


{
Scanner s = new Scanner([Link]);
String ifn ,ofn ;
[Link]("Enter the file name to read:");
ifn = [Link]();
[Link]("Enter the file name to write:");
ofn = [Link]();
try {
FileReader fr = new FileReader(ifn);
FileWriter fw = new FileWriter(ofn);

int i;
while ((i = [Link]()) != -1)
{
[Link](i);
}

[Link]();
[Link]();
[Link]("File reading and writing both done");
}

catch (IOException e) {

[Link]("There are some IOException" + e);


}
}
}

Output:
Make sure that the file name given to be read is present in the current directory where the program is [Link]
this case [Link] file should be present with some content.

Upon successfull execution you should get a file created in the current directory where the program is saved .In
this case we should be able to see a file by name [Link] got created and the contents of it as same as the file
read.
Week 12: Design an interface & implement it like one that builds different types of toys
and check compliance with ISP

Program 31: Develop a java program to design an interface and implement it like one that builds different types
of toys and check compliance with Interface Segregation principle.

interface toy{
void setprice(double price);
void setcolor(String color);
}

interface move{
void move();
}

interface fly{
void fly();
}

class Car implements toy,move{


double price;
String color;
public void setprice(double price)
{
[Link]=price;
[Link]("The car Toy");
[Link]("price =" +price);
}
public void setcolor(String color)
{
[Link]=color;
[Link]("color =" +color);
}
public void move()
{
[Link]("start to move forward and backward ");
}
}

class Plane implements toy,fly,move{


double price;
String color;
public void setprice(double price)
{
[Link]=price;
[Link]("The Plane Toy");
[Link]("price =" +price);
}
public void setcolor(String color)
{
[Link]=color;
[Link]("color =" +color);
}
public void move()
{
[Link]("plane can move forward and backward ");
}
public void fly()
{
[Link]("starts flying");
}
}

public class ToyBuilder{


public static void main(String args[])
{
Car c=new Car();
[Link](12.0);
[Link]("red");
[Link]();
Plane p=new Plane();
[Link](15.0);
[Link]("yellow");
[Link]();
[Link]();
}
}

Output:
Week 13: Code, execute and debug programs to connect to database through JDBC and
perform basic DB operations.

Refer the links


How to install Mysql.
[Link]
Java Database Programming (JDBC) by Examples with MySQL
[Link]

Program 32: Develop a java program to connect to database (Mysql) through JDBC and perform basic DB
operations.

Step 1 : Check whether Mysql has been installed and configured correctly.

Step 2 : Install MySql JDBC Driver. ( we need to install the JDBC driver version which matches the version of
MYsql . please choose accordingly)
You need to install an appropriate JDBC (Java Database Connectivity) driver to run your Java database
programs. The MySQL's JDBC driver is called "MySQL Connector/J" and is available at MySQL mother site.

1. Download the "latest" MySQL JDBC driver from [Link] ⇒ "Connector/J" ⇒


For Windows

Connector/J 8.03.{xx}, where {xx} is the latest update number ⇒ In "Select Operating System", choose
"Platform Independent" ⇒ ZIP Archive (e.g., "mysql-connector-j-8.3.{xx}.zip" ⇒ "No thanks, just
start my download".
2. UNZIP (right-click and extract all) the download file into your project directory "C:\myWebProject".
3. Open the unzipped folder. Look for the JAR file "mysql-connector-j-8.3.{xx}.jar".
The Absolute Full-path Filename for this JAR file is "C:\myWebProject\mysql-connector-j-3.0.{xx}\
mysql-connector-j-8.3.{xx}.jar". Take note of this super-long filename that you will need later. COPY
and SAVE in a scratch pad so that you can retrieve later.

(For Advanced User Only) CLASSPATH


You can compile Java database programs without the JDBC driver. But to run the JDBC programs, the JDBC
driver's JAR-file must be included in the environment variable CLASSPATH, or in the java's command-line
option -cp (or -classpath or --class-path).
You can set the -cp option for Java runtime as follows:
// For windows
java -cp .;/path/to/mysql-connector-j-8.3.{xx}.jar JDBCClassToRun

Prior to JDK 9, you can copy the JAR file into JDK's extension directory at "<JAVA_HOME>\jre\lib\ext"
(Windows) or "/Library/Java/Extensions" (macOS). JDK 9 removes this extension mechanism.

Step 3 : Setup DataBase


We have to set up a database before embarking on our database programming. We shall call our database
"studentdb" which contains a table called "class101",
A JDBC program comprises the following 5 steps:
 STEP 1: Connect to the database via a Connection object.
 STEP 2: Allocate a Statement object, under the Connection created earlier, for holding a SQL
command.
 STEP 3: Write a SQL query and execute the query via the [Link]()|executeUpdate().
 STEP 4: Process the query result.
 STEP 5: Close the Statement and Connection to free up the resources.

Keep the mysql server running and execute the following program:
Make sure that password for root user is set to “tiger” for the following program to execute correctly.
Java Program:

import [Link].*;

public class JdbcSelectTest {

public static void main(String[] args) {


try (

)
{

String strSelect = "select * from class101";


[Link]("The SQL statement is: " + strSelect + "\n");

ResultSet rset = [Link](strSelect);

[Link]("The records selected are:");


int rowCount = 0;

while([Link]()) {
String name = [Link]("name");
double gpa = [Link]("gpa");
int id = [Link]("id");
[Link](id + ", " + name + ", " + gpa);
++rowCount;
}
[Link]("Total number of records = " + rowCount);

} catch(SQLException ex) {
[Link]();
}
}
}

Output:
Remember:

You might also like