0% found this document useful (0 votes)
72 views

Lab Manual: CLO No. Learning Outcomes Assessment Item BT Level PLO

This document contains a lab manual for a class on using classes and methods in Java. It discusses using the Arrays class to sort, fill, copy and compare arrays. It explains the difference between object code and client code, and how to create classes, objects, fields and methods in Java. Methods can be used to return values or display output. The lab manual provides examples of creating classes with fields to represent object state, and methods to calculate volume of boxes to demonstrate class and method functionality.

Uploaded by

saba doll
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

Lab Manual: CLO No. Learning Outcomes Assessment Item BT Level PLO

This document contains a lab manual for a class on using classes and methods in Java. It discusses using the Arrays class to sort, fill, copy and compare arrays. It explains the difference between object code and client code, and how to create classes, objects, fields and methods in Java. Methods can be used to return values or display output. The lab manual provides examples of creating classes with fields to represent object state, and methods to calculate volume of boxes to demonstrate class and method functionality.

Uploaded by

saba doll
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

UET TAXILA

CLO Learning Outcomes Assessment Item BT Level PLO


No.

1 Construct the experiments / Lab Task, Mid Exam, Final


projects of varying complexities. Exam, Quiz, Assignment, P2 3
Semester Project
2 Use modern tool and languages. Lab Task, Semester
P2 5
Project
3 Demonstrate an original solution of Lab Assignment, Lab
A2 8
problem under discussion. Task, Semester Project
4 Work individually as well as in Lab Task, Semester A2 9
teams Project

Lab Manual
OOP
3rdSemester Lab-06: Classes and Methods in Java

Laboratory 06:
Statement Purpose:
At the end of this lab, the students should be able to:

• Use Arrays Class in Java


• Understand the difference between object code and client code
• Create new classes and Objects
• Create fields and methods
• Create parameterized and value returning methods

Arrays Class:
The Arrays class, available in the java.util package, is a helper class that contains methods for working
with arrays. These methods can be used for modifying, sorting, copying, or searching data. These
methods that we use are static methods of the Array class. (Static methods are methods that can be
called without creating an instance of a class.)

import java.util.Arrays;
public class ArrayMethods {
public static void main(String[] args) {
int[] a = {5, 2, 4, 3, 1};
System.out.println("Before Sorting " +Arrays.toString(a));
Arrays.sort(a);
System.out.println("After Sorting " +Arrays.toString(a));
Arrays.fill(a, 8);
System.out.println("After filling the sorted array a with value 8 ->"
+Arrays.toString(a));
int[] b = Arrays.copyOf(a, 5);
System.out.println("After copying first 5 elements of array a in array b -
>" +Arrays.toString(b));
if (Arrays.equals(a, b)) {
System.out.println("Arrays a, b are equal");
} else {
System.out.println("Arrays a, b are not equal");
}
}
}
Output:

In the above code example, we have used five methods of the Arrays class.

import java.util.Arrays;

We will use the shorthand notation for the Arrays class.

int[] a = {5, 2, 4, 3, 1};


We have an array of five integers.

Engr. Sidra Shafi Lab-06 1


3rdSemester Lab-06: Classes and Methods in Java

Arrays.sort(a);
The sort() method sorts the integers in an ascending order.
System.out.println(Arrays.toString(a));

The toString() method returns a string representation of the contents of the specified array.

Arrays.fill(a, 8);

The fill() method assigns the specified integer value to each element of the array.

int[] b = Arrays.copyOf(a, 5);

The copyOf() method copies the specified number of elements to a new array.

This method copies the specified array,

if (Arrays.equals(a, b)) {
System.out.println("Arrays a, b are equal");
} else {
System.out.println("Arrays a, b are not equal");
}

The equals() method compares the two arrays. Two arrays are equal if they contain the same
elements in the same order.

What is Object Code?


Objects are another type of class, one which has both data and behavior.
So far, we've just written client code. Now we're learning how to write Object code. With client code,
the main method is run. With Object code, we're writing a blueprint so that client code can create as
many of our Object as it wants!
Up until now, we've only used Objects implemented by others (what does the code for Scanner look
like? We've never seen it!)
Next, we will create a complete Object.
Implementing Java classes, objects and methods:

Fields:
Remember that our definition of an Object is that it has both data and behavior. Fields are what allow
us to have data. They should reflect the state of the Object!

Fields are variables that are declared outside of any method/constructor, which makes them accessible
in any method/constructor. This means that fields are great for remembering information across method
calls.

public class Point {


//the x,y values represent the state of a point
int x;
int y;
public Point() {
//Constructor code
}
}

Engr. Sidra Shafi Lab-06 2


3rdSemester Lab-06: Classes and Methods in Java

Initial Field values:


When fields are declared, they automatically have default values.

Type Default Value


int 0
double 0.0
char ‘\0’ (null character)
String (or any other Object) null
boolean false

If you want a field to have a different initial value, you should reassign it in the constructor.

A Simple class:
Consider the following code, there is a class called BA that defines three instance variables: width,
height, and depth. Currently, this class does not contain any methods.

class BA {
double width;
double height;
double depth;
}

This is a complete program that uses the Box class:


//A Program that uses the BA class.
class BA {
double width;
double height;
double depth;
}

//This class declares an instance of type BA.


public class BB {
public static void main(String args[])
{
BA mybox=new BA();
double vol;

//assign values to mybox's instance variables


mybox.width=10;
mybox.height=20;
mybox.depth=15;

//compute volume of box


vol=mybox.width*mybox.height*mybox.depth;
System.out.println("Volume is " + vol);
}
}

Output:

Volume is 3000.0

Engr. Sidra Shafi Lab-06 3


3rdSemester Lab-06: Classes and Methods in Java

Methods in Object code


With client code, we implement static methods that the main method (or other methods!) call.
With Object code, we want to implement instance methods. Instance methods are non-static and are
called on an instance of an Object.
We have used instance methods before!

Adding a Method to the Box Class:


//This program includes a method inside the BA class.
class BA {
double width;
double height;
double depth;

//display volume of a box


void volume(){
System.out.print("Volume is ");
System.out.println(width*height*depth);
}
}

//This class declares an instance of type BA.


public class BB {
public static void main(String args[])
{
BA mybox1=new BA();
BA mybox2=new BA();
double vol;

//assign values to mybox1's instance variables


mybox1.width=10;
mybox1.height=20;
mybox1.depth=15;

//assign different values to mybox2's instance variables


mybox2.width=3;
mybox2.height=6;
mybox2.depth=9;

//display volume of first box


mybox1.volume();

//display volume of first box


mybox2.volume();

}
}

Output:

Volume is 3000.0

Engr. Sidra Shafi Lab-06 4


3rdSemester Lab-06: Classes and Methods in Java

Volume is 162.0

Adding a Method which returns a value:

Consider the following code, in which we create a box class with its instance variables: width, height
and depth. This class also defines a method called volume.
Another class called DemoBox is also created, which includes main method. In this class, objects of
class Box are created and with the help of these objects methods of Box class are called as
object_name.volume(), which returns the calculated volume.

Code:
//A program that uses the Box class.
//This program includes a method inside the box class which returns the volume of
a box.
public class Box {

double width;
double height;
double depth;

//compute and return volume


double volume()
{
return width*height*depth;
}
}

//This class declares two objects of type Box.


class DemoBox{
public static void main(String args[])
{
Box mybox1=new Box();
Box mybox2=new Box();
double vol;

//assign values to mybox1’s instance variables


mybox1.width=10;
mybox1.height=20;
mybox1.depth=15;

// assign different values to mybox2’s instance variables


mybox2.width=3;
mybox2.height=6;
mybox2.depth=9;

//get volume of first box


vol=mybox1.volume();
System.out.println("Volume is " + 0vol);

//get volume of second box


vol=mybox2.volume();
System.out.println("Volume is " + vol);
}
}

Output:
Volume is 3000.0
Volume is 162.0

Engr. Sidra Shafi Lab-06 5


3rdSemester Lab-06: Classes and Methods in Java

Adding a Method that Takes Parameters

Add the following parameterized method in Box class.

//sets dimensions of box


void setDim(double w, double h, double d)
{
width=w;
height=h;
depth=d;
}

Also, in DemoBox class, replace the following code


//assign values to mybox1’s instance variables
mybox1.width=10;
mybox1.height=20;
mybox1.depth=15;

// assign different values to mybox2’s instance variables


mybox2.width=3;
mybox2.height=6;
mybox2.depth=9;

with the code given below


//initialize each box
mybox1.setDim(10,20,15);
mybox1.setDim(3,6,9);

After changes in code, following output will be shown in Eclipse:


Output:

Volume is 3000.0
Volume is 162.0

Accessor:
An Accessor method is commonly known as a get method or simply a getter. They are declared
as public. They are used to return the value of a private field. The same data type is returned
by these methods depending on their private field.

Syntax:
public int getNumber() {
return number;
}

Example:
public class Employee {
private int number;
public int getNumber() {
return number;
}
public void setNumber(int newNumber) {
number = newNumber;
}
}

Engr. Sidra Shafi Lab-06 6


3rdSemester Lab-06: Classes and Methods in Java

Mutator:
A Mutator method is commonly known as a set method or simply a setter. A Mutator method
mutates things, in other words change things. It shows us the principle of encapsulation. They
are also known as modifiers. They are easily spotted because they started with the word set.
They are declared as public. Mutator methods do not have any return type and they also accept
a parameter of the same data type depending on their private field. After that it is used to set
the value of the private field.

Syntax:
public void setAge(int Age) {
this.Age = Age;

Example:
public class Employee {
private int Age;
public int getAge() {
return this.Age;
}
public void setAge(int Age) {
this.Age = Age;
}

Example:

public class Student {


private String name, major, minor;
private int hours; // creditHoursEarned
private double cumulativeGPA;

}

//Accessor Method
public String getName() {
return name;
}
//Mutator
public void changeHours(int newHours) {
if(newHours>0&&newHours<200) hours=hours+newHours;
}

//Constructor
public Student(String newStudentName) {
name=newStudentName;
major=“”;
minor=“”;
hours=0;
cumulativeGPA=0.0;
}
//objects of student class
Student s1, s2, s3;
s1=new Student(“Ali”);
Engr. Sidra Shafi Lab-06 7
3rdSemester Lab-06: Classes and Methods in Java

s2=new Student(“Sehrish”);
s3=new Student(“Ahmad”);
s1.changeHours(15);
s2.changeHours(35);

//A method which will return the proper class rank as a String.
public String getRank( ) {
if(hours>=90) return “senior”;
else if(hours>=60) return “junior”;
else if(hours>=30) return “sophomore”;
else return “freshman”;
}

/*If a class has a toString method, it will automatically be called when we attempt to output
an object of that class using println. We define the toString to return a String of the relevant
parts of the object.*/
public String toString() {
String tempMajor, tempMinor;
if(!major.equals(“”))
tempMajor=major
else
tempMajor=“undeclared”;
if(minor!=“”)
tempMinor=minor
else
tempMinor=“none”;
return name + “\t” + tempMajor + “\t” + tempMinor
+ getRank();
}

Complete Student Example:


public class Student {
private String name, major, minor;
private int hours;
private double cumulativeGPA;

public Student(String newStudentName) {


name=newStudentName;
major=“”;
minor=“”;
hours=0;
cumulativeGPA=0.0;
}

public String getName() {


return name;
}
public void changeHours(int newHours) {
if(newHours>0&&newHours<200) hours=hours+newHours;
}

public String getRank( ) {


Engr. Sidra Shafi Lab-06 8
3rdSemester Lab-06: Classes and Methods in Java

if(hours>=90) return “senior”;


else if(hours>=60) return “junior”;
else if(hours>=30) return “sophomore”;
else return “freshman”;
}

public String toString() {


String tempMajor, tempMinor;
if(!major.equals(“”)) tempMajor=major
else tempMajor=“undeclared”;
if(minor!=“”) tempMinor=minor else tempMinor=“none”;
return name + “\t” + tempMajor + “\t” + tempMinor
+ getRank();
}

Lab Exercise:
There are four errors in the following code. Find all the errors in the following Point
class.
public class Point {
int x; // Each Point object has
int y; // an int x and y inside.

public void Point(int initX, int initY) { // Constructor


initX = x;
initY = y;
}

public static double distanceFromOrigin() { // Returns this point's


int x; // distance from (0, 0).
int y;
double dist = Math.sqrt(x*x + y*y);
return dist;
}

public void translate(int dx, int dy) { // Shifts this point's x/y
int x = x + dx; // by the given amounts.
int y = y + dy;
}
}

Lab Tasks
Task 1: Marks: 5

Make a class Meters which consists of a public parameterized method named feetToMeters( ).
This method should receive from its caller the number of feet to be converted and should check that this
value is positive. It should convert that quantity to meters by multiplying it by 0.3048 and return the
resulting value to the caller.

Note that where a program typically inputs values from the keyboard, a method
typically receives values from whoever called the method. Similarly, where a program
typically outputs values to the screen, a method typically returns a value to whoever called the method.

Engr. Sidra Shafi Lab-06 9


3rdSemester Lab-06: Classes and Methods in Java

Note also that we want to try and anticipate what could go wrong. Since the method will only produce
a correct result if the value it receives is not negative, we say that this method has a precondition -- a
condition that must be true for the method to execute correctly.

The first thing that we must decide is what measurement conversions we wish our class to provide. For
example, the following are just a few of the useful conversions:

Specification:

Caller Class/ Main Class/Driver program:


Most driver programs use the same algorithm
1. Display a prompt for whatever values the method requires as arguments.
2. Read those values from the keyboard.
3. Display the result of calling the method,
using the input values as arguments (plus a descriptive label).

Task 2: Marks: 5

Make a class Rectangle which calculates the area and perimeter of rectangle according to the
following algorithm.
Step 1: Declare two private variables length and width of type double.
Step 2: Make a Parameterized method which sets the length and width according to the values it receives
as parameters.
Step 3: Make two methods getLength and getWidth which only return length and width. Their return
type is double.
Step 4: Make a value returning method perimeter which calculates the perimeter according to the
formula 2*L+2*W.
Step 5: Make a value returning method area which calculates the area according to the formula L*W.
Step 6: Make a class RectDemo which includes main method. Make an object of Rectangle class.
Step 7: Get and Print the length and width of Rectangle by using appropriate methods.
Step 8: Print the Perimeter and Area of Rectangle.

********

Engr. Sidra Shafi Lab-06 10

You might also like