Oop With Java Lab Manual
Oop With Java Lab Manual
Week 1 :
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.
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.
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.
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.
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.
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.
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:
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:
import [Link];
class Triangle
{
Program 5: Develop a Java Program to calculate Simple interest for the given principal , time and rate of
interest.
import [Link];
class SimpleInterest
{
Output:
Program 6: Develop a Java Program to convert given temperature in Fahrenheit to Celsius scale.
import [Link];
class Celsius
{
Output:
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:
class Employee
{
int empid;
double empsalary;
String empname;
String empemailid;
Employee()
{
[Link]("No arguments constructor called");
void displaydata()
{ [Link]("Employee details");
[Link]("Emp id = " + empid);
[Link]("Empsalary = " + empsalary);
[Link]("Emp name = " + empname);
[Link]("Emp emailid = " + empemailid);
}
}
class EmpTest
{
}
}
Output:
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]("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:
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;
//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);
//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.
String name ;
Sample()
{
name = val;
}
class Infinity
{
public static void main(String args[])
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{
}
}
Output:
Program 13: Develop a java program to implement Basic calculator using Switch statement.
import [Link];
class SwitchDemo
{
public static void main(String args[])
{
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
{
Output:
Program 15: Develop a java program to find the factorial of a given number.
import [Link];
class Factorial
{
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;
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 {
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;
File [Link]:
package mypack;
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);
}
}
}
}
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;
if(flag == 1)
[Link]("Search successful item is found at position " + (i+1));
else
[Link]("Search unsuccessful item is not found ");
}
Output:
class StringExample1
{
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;
double area()
{ return length * breadth;
}
}
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]();
class AreaCalculator {
public double calculateArea(Shape shape) {
return [Link]();
}
}
Output:
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;
}
}
Output:
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.
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 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 {
Output:
Program 29: Develop a java program to demonstrate unchecked exception.
import [Link];
class UncheckedException
{
public static void main( String args[])
{
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 {
int i;
while ((i = [Link]()) != -1)
{
[Link](i);
}
[Link]();
[Link]();
[Link]("File reading and writing both done");
}
catch (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();
}
Output:
Week 13: Code, execute and debug programs to connect to database through JDBC and
perform basic DB operations.
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.
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.
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.
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].*;
)
{
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: