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

Java Module 2 Chapter 7

The document describes a Java program to develop a stack data structure using an array of integers. It defines four methods - push(), pop(), peek(), and display() to insert, remove, view, and display elements in the stack. The push() method inserts an integer at the top if room exists. Pop() removes an integer from the top and displays it. Peek() views the top integer without removing it. Display() shows all integers in the stack order. Access modifiers should be used correctly. Another class is needed to thoroughly test the stack.

Uploaded by

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

Java Module 2 Chapter 7

The document describes a Java program to develop a stack data structure using an array of integers. It defines four methods - push(), pop(), peek(), and display() to insert, remove, view, and display elements in the stack. The push() method inserts an integer at the top if room exists. Pop() removes an integer from the top and displays it. Peek() views the top integer without removing it. Display() shows all integers in the stack order. Access modifiers should be used correctly. Another class is needed to thoroughly test the stack.

Uploaded by

2022becs190
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Lab Activity/Exercise 15

Write a Java program to develop the stack data structure. Use an array of ten integers. Ten is the
maximum size of the stack. Design the following methods with suitable parameters: push(), pop(),
peek(), and display().
• push() – inserts an integer at the top of the stack, without altering any other elements of the
existing stack only if there is room in the stack. Check if room exists before pushing.
• Pop() - pulls an integer out from the top of the stack and displays the same.
• Peek() - returns the integer from the top of the stack without removing it from the stack itself.
• Display() displays all integers in the stack, in the order they were inserted. This can be used
whenever you want to confirm the elements that are present in the stack
Use the correct access modifiers for all data members and methods. Write another class to test the
stack thoroughly.
Closer Look @ Methods & Classes
● Methods can be overloaded
● One of the ways Java supports polymorphism.
class Overload {
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
public class OverloadTest {
public static void main(String args[]) {
Overload overload = new Overload();
double result;
overload.test();
overload.test(10);
overload.test(10, 20);
result = overload.test(123.25);
System.out.println("Result of overload.test(123.25): " +
result);
}
}
Java’s automatic type conversions can play a role in overload resolution

// Automatic type conversions apply to overloading.

class Overload {

void test() {

System.out.println("No parameters");

}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}
class OverloadTest { // which exact method gets called?
public static void main(String args[]) {
Overload overload = new Overload();
int i = 88;
overload.test();
overload.test(10, 20);
overload.test(i);
overload.test(123.2);
}
}
Overloading Constructors
class Box {
double width;
double height;
double depth;

Box(double width, double height, double depth) {


this.width = width;
this.height = height;
this.depth = depth;
}
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}

Box(double length) {
width = height = depth = length;
}

double volume () {
return width * height * depth;
}
}
public class BoxTest {
public static void main(String args[]) {
Box box1 = new Box(10, 20, 15);
Box box2 = new Box();
Box box3 = new Box(7);
double volume = box1.volume();
System.out.println("Volume of box1 is " + volume);
volume = box2.volume();
System.out.println("Volume of box2 is " + volume);
volume = box3.volume();
System.out.println("Volume of cube is " + volume);
}
}
// Objects may be passed to methods.
public class Test {
int a, b;

Test(int i, int j) {
a = i;
b = j;
}

boolean equals(Test o) {
if (o.a == a && o.b == b) return true;
else return false;
}
}
class PassingObjects {
public static void main(String args[]) {
Test object1 = new Test(100, 22);
Test object2 = new Test(100, 22);
Test object3 = new Test(-1, -1);

System.out.println(" object1 == object2: " + object1.equals(object2));


System.out.println(" object1 == object3: " + object1.equals(object3));
}
}
A Closer Look at Argument Passing
●call-by-value: This approach copies the value of an
argument into the formal parameter of the subroutine
●call-by-reference:a reference to an argument (not the
value of the argument) is passed to the parameter.
Call by Value
// Primitive types are always passed by value.

class Test {

void method(int i, int j) {

i *= 2;

j /= 2;

class CallByValue {

public static void main(String args[]) {

Test test = new Test();

int a = 15, b = 20;

System.out.println("a and b before call: " +a + " " + b);

test.method(a, b);

System.out.println("a and b after call: " +a + " " + b);


class Test {
Call by reference
int a, b;

Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void method(Test o) {
o.a *= 2;
o.b /= 2;
}
}
class CallByReference {
public static void main(String args[]) {
Test test = new Test(15, 20);
System.out.println(“test.a and test.b before call: " +
test.a + " " + test.b);
test.method(test);
System.out.println(“test.a and test.b after call: " +
test.a + " " + test.b);
}
}
Returning Objects
class Test {
int a;
Test(int i) {
a = i;
}
Test incrementByTen() {
Test temp = new Test(a+10);
return temp;
}
}
class ReturnObject {
public static void main(String args[]) {
Test object1 = new Test(2);
Test object2;
object2 = object1.incrementByTen();
System.out.println("object1.a: " + object1.a);
System.out.println("object2.a: " + object2.a);
object2 = object2.incrementByTen();
System.out.println(“object2.a after second increase: “ + object2.a);
}
}
Recursion
process of defining something in terms of itself.

Advantage: they can be used to create clearer and


simpler versions of several algorithms compared to
their iterative relatives.
class Factorial { // this is a recursive method
int computeFactorial(int n) {
int result;
if (n == 1) return 1;
return result = computeFactorial(n-1) * n;
}
class Recursion {
public static void main(String args[]) {
Factorial factorial = new Factorial();

System.out.println("Factorial of 3 is " + factorial. computeFactorial (3));


System.out.println("Factorial of 4 is " + factorial. computeFactorial(4));
System.out.println("Factorial of 5 is " + factorial. computeFactorial(5));
}
}
Introducing Access Control
●encapsulation provides another important attribute:
access control.
● public, private, and protected.
class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setC(int i) { // set c's value
c = i;
}
int getC() { // get c's value
return c;
}
}
Continuation of previous program
class AccessTest {
public static void main(String args[]) {
Test object = new Test();
// These are OK, a and b may be accessed directly
object.a = 10;
object.b = 20;
// This is not OK and will cause an error
// object.c = 100; // Error!
// You must access c through its methods
object.setC(100); // OK
System.out.println("a, b, and c: " + object.a + " " + object.b + " " + object.getC());
}
}
Introducing final
● A variable can be declared as final.
● Doing so prevents its contents from being modified.
● Usually used in real-life for declaring constants – remember #define in C?
● final int FILE_NEW = 1;
● final int FILE_OPEN = 2;
● final int FILE_SAVE = 3;
● final int FILE_SAVEAS = 4;
● final int FILE_QUIT = 5;
● The keyword final can also be applied to methods.
Understanding static
● Static is a keyword.
● We can declare methods and variables to be static.
●When a member is declared static, it can be accessed
before any objects of its class are created, and without
reference to any object.
Restrictions of static Methods
● They can only call other static methods.
● They must only access static data.
● They cannot refer to this or super in any way.
// Demonstrate static variables, methods, and blocks.
class StaticTest {
static int a = 3;
static int b;
static void method(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
method(42);
}
}
Output
● Static block initialized.
● x = 42
● a=3
● b = 12
Invoking static method
●If we want to call the static method outside the class
we should use the . as in className.method( )
Arrays Revisited
●Array is implemented as objects.
● Length: attribute of an array so consider it as instance variable

class Length {

public static void main(String args[]) {


int a1[] = new int[10];
int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};
int a3[] = {4, 3, 2, 1};
System.out.println("length of a1 is + a1.length);
System.out.println("length of a2 is + a2.length);
System.out.println("length of a3 is + a3.length);
}
Lab Activity/Exercise 16
Write a class called Employee, which models an employee with
an ID (integer), first, middle, and last names as three separate
String variables, and a double salary.
Define meaningful constructors and a method called
raiseSalary(int percent), Percent lies between 1 to 10 that
increases the existing salary.
Test the Employee class and suitable main method for
demonstration
Lab Activity/Exercise 17
Design a class Point which models a 2D point with x and y coordinates as follows:
Two instance variables x (int) and y (int).
A default ("no-arg") constructor that constructs a point at the default location of (0, 0).
An overloaded constructor that constructs a point with the given x and y coordinates.
A method setXY() to set x and y.
A method getXY() which returns x and y in a 2-element int array.
A toString() method that returns a string description of the instance in the format "(x, y)".
A method called distance(int x, int y) that returns the distance from this point to a point whose
coordinates are x and y
An overloaded distance(Point another) that returns the distance from this point to the given Point

You might also like