Lab 02 09-03-2021
Lab 02 09-03-2021
Lab Manual No 02
Dated:
09 Mar, 2021 to 16th Mar, 2021
th
Semester:
Spring 2021
Lab Objective:
This lab focuses on the concept of “Functions with parameters and return types”. Also, it includes
concepts related to method and constructor overloading. All the assignments should be completed
in this lab.
Parameters
Variables should be initialized where they are declared and they should be declared in the smallest
scope possible. A null initialization is acceptable. Variable names should be short yet meaningful.
Pass-by-value
means that when a method is called, a copy of the value of each argument is passed to the method.
This copy can be changed inside the method, but such a change will have NO effect on the argument.
Example No 1:
Will the values from main be changed after being sent to this method??
NumberManeuvers(num, decimal);
}
public static void NumberManeuvers(int i, double j)
{
if (i == 10)
j = 6.2;
i = 12;
Instance variables:
These variables belong to the instance of a class, thus an object. And every instance of that class (object)
has it's own copy of that variable. Changes made to the variable don't reflect in other instances of that
class.
Example 02 :
System.out.println(prod1.Barcode);
System.out.println(prod2.Barcode);
}
Class Variable:
These are also known as static member variables and there's only one copy of that variable that is
shared with all instances of that class. If changes are made to that variable, all other instances will see
the effect of the changes.
return Barcode;
}
System.out.println(prod1.getBarcode());
System.out.println(prod2.getBarcode());
}
}
What is “this”:
this is a keyword in Java. It can be used inside the Method or constructor of Class. It (this) works as a
reference to the current Object whose Method or constructor is being invoked. The this keyword can be
used to refer to any member of the current object from within an instance Method or a constructor.
this keyword with field (Instance Variable): this keyword can be very useful in the handling of Variable
Hiding. We cannot create two instance/local variables with the same name. However, it is legal to create
one instance variable & one local variable or Method parameter with the same name. In this scenario,
the local variable will hide the instance variable this is called Variable Hiding.
class JBT {
int variable = 5;
obj.method(20);
obj.method();
}
void method() {
int variable = 40;
System.out.println("Value of variable :" + variable);
}
}
As you can see in the example above the instance variable is hiding and the value of the local variable
(or Method Parameter) is displayed not instance variable. To solve this problem, use this keyword with a
field to point to the instance variable instead of the local variable.
void method() {
int variable = 40;
System.out.println("Value of variable :" + this.variable);
}
}
Package Introduction:
Java applications often comprise a very large number of classes. In order to provide for
management of all these classes, they are arranged into groupings known as packages, with each
package containing a logical group of related classes.
Example:
package myPackage; package myPackage;
Lab Tasks:
Modify the following class to make it a part of the package named myutil. In addition to
adjusting the source file, what are the steps you need to take so that the class becomes
usable/accessible from other classes that are outside of this myutil package?
Write a program that tests the Person class defined in above program. Place this test
program outside of the myutil package and make sure you can call the constructor and the
methods of the Person class correctly.
➢ Write a class with the following functions:
➢ Function that returns a random number which lies in the range x to y.
Where, x and y passed as parameters.
➢ Function that returns the average (rounded off up to 2 decimal places) of a student
who scored marks in the courses passed as parameters.
➢ Function the returns the solution of the quadratic equation: 2.7x2+ 5.9x +2.8
➢ Function the returns the Channel Capacity using the following formula: C =
Blog2M Where, B (Bandwith) and M (Number of levels) are passed as parameters.
➢ Function that takes a parameter x is in degrees, calculate the cos, sin and tan
function.
➢ Calculate Volume
➢ Write a source class that sends the height and radius to the cylinder class and
prints the returned values of area and volume of the cylinder.
Method Overloading:
Method overloading is having multiple methods with same name but different signature. Method
signature includes method name, list of parameters and types of parameters. Following hint clears
the concept of method overloading.
Example:
Constructor Overloading
Constructor overloading is having multiple constructors with same name as class name but
different list of parameters. Following hint (given on next page) clear about constructor
overloading.
Lab Tasks:
Perform assignment2 involving method overloading. Use method overloading pass
different values to “r” and “h”. (By passing single argument, two arguments)
Perform assignment2 involving constructor overloading. Use constructor overloading pass
different values to “r” and “h”.
As an example, I'm going to use a Person class with the following state and constructor already defined:
//Private fields
private String firstName;
private String middleNames;
private String lastName;
private String address;
private String username;
//Constructor method
public Person(String firstName, String middleNames, String lastName, String address)
{
this.firstName = firstName;
this.middleNames = middleNames;
this.lastName = lastName;
this.address = address;
this.username = "";
}
}
ACCESSOR METHODS
An accessor method is used to return the value of a private field. It follows a naming scheme prefixing
the word "get" to the start of the method name. For example let's add accessor methods for firstname,
middleNames and lastname:
{
return middleNames;
}
These methods always return the same data type as their corresponding private field (e.g., String) and
then simply return the value of that private field.
We can now access their values through the methods of a Person object:
MUTATOR METHODS
A mutator method is used to set a value of a private field. It follows a naming scheme prefixing the word
"set" to the start of the method name. For example, let's add mutator fields for address and username:
These methods do not have a return type and accept a parameter that is the same data type as their
corresponding private field. The parameter is then used to set the value of that private field.
It's now possible to modify the values for the address and username inside the Person object:
Person dave = new Person("Dave", "Bob Bill", "Davidson", "12 Pall Mall");
dave.setAddress("256 Bow Street");
dave.setUsername("DDavidson");
}
}
It's easy to come to the conclusion that we could just change the private fields of the class definition to
be public and achieve the same results. It's important to remember that we want to hide the data of the
object as much as possible. The extra buffer provided by these methods allows us to:
Let's say we decide to modify how we store middle names. Instead of just one String we now use an
array of Strings:
The implementation inside the object has changed but the outside world is not affected. The way the
methods are called remains exactly the same:
Person dave = new Person("Dave", "Bob Bill", "Davidson", "12 Pall Mall");
System.out.println(dave.getFirstName() + " " + dave.getMiddlesNames() + " " + dave.getLastName());
}
}
Or, let's say the application that is using the Person object can only accept usernames that have a
maximum of ten characters. We can add validation in the setUsername mutator to make sure the
username conforms to this requirement:
Now if the username passed to the setUsername mutator is longer than ten characters it is
automatically truncated.
3.1. Select path for the javadoc.exe tool from the JDK.
3.2. Project resources for which to generate Javadoc.
3.3. Classes and methods for which to generate Javadoc based on their visibility.
3.4. Location of the Javadoc (by default it will be placed in the doc folder in the project
location).
5. At the last step you can save the settings in an Ant script for future use.
Lab Tasks
Question No.01:
Write a program that computes the total ticket sales of a concert. There are three types of
seating: A, B, and C. The program accepts the number of tickets sold and the price of a
ticket for each of the three types of seats. The total sales are computed as follows:
totalSales = numberOfA_Seats * pricePerA_Seat + numberOfB_Seats *
pricePerB_Seat +numberOfC_Seats * pricePerC_Seat
Question No.02:
Write this program, using only one class, the main class of the above program. Define a
new class named Temperature. The class has two accessors—to-Fahrenheit and
toCelsius—that return the temperature in the specified unit and two mutators—
setFahrenheit and setCelsius—that assign the temperature in the specified unit. Maintain
the temperature internally in degrees Fahrenheit.
Question No.03
Using this class, write a program that inputs temperature in degrees Fahrenheit and
outputs the temperature in equivalent degrees Celsius.
Question No.04
Create the following figure using World and Turtle classes. You have to use three different
turtles to draw each shape. Make a class MyWorld. Draw three methods createSq(),
createTri() and createRect() class. Write the codes for creating square, triangle and
rectangle in the createSq(), createTri() and createRect() methods respectively. Make a
constructor that instantiate the World class. Turtle class should be instantiated in each
method separately. Make the main() method, create an object of MyWorld class and call all
the three methods.
Question No.05
Design a class that keeps track of a student’s food purchases at the campus cafeteria. A
meal card is assigned to an individual student. When a meal card is first issued, the balance
is set to the number of points. If the student does not specify the number of points, then the
initial balance is set to 100 points. Points assigned to each food item are a whole number.
A student can purchase additional points at any time during a semester. Every time food
items are bought, points are deducted from the balance. If the balance becomes negative,
the purchase of food items is not allowed. There is obviously more than one way to
implement the MealCard class. Any design that supports the key functionalities is
acceptable. Put this class in the myutil package.
Question No.06
Write a program that tests the meal card class defined in above program. Define this test
program outside the myutil package. Create one or two meal card objects in the test
program and verify that all methods defined in the meal card class operate correctly.
Question No.07
Add javadoc comments to the following class.
classInstructor {
privateString name;
public voidsetName(String name){
this.name = name;
}
publicString getName(){
returnname;
}
}
Question No.08
Copy the Code from Book Page 410-418 and generate Java Doc?
Question No.09
Complete the following constructor.
classStudent {
privateString name;
private int age;
privateAddress address;
publicStudent(String name,intage, Address address){
//assign passed values to the data members
}
Question No.10
Consider the following class.
classModifier {
public static change(int x, int y){
x = x - 10;
y = y + 10;
}
}
What will be an output from the following code?
Int x = 40;
Int y = 20;
Modifier.change(x,y);
System.out.println("x = "+ x);
System.out.println("y = "+ y);
The End