Java

TOPIC 29 – FUNCTIONS & OBJECTS

 

 

LESSON NOTE

 

 

LAST LESSON

 

Last lesson, we worked on understanding function prototypes.  Then, we created our own simple functions.  These functions all had a return-type of integer.  This was done to keep things simple.

Now, we will look at functions that work with objects.  The object that we are most familiar with is a String so we will start with an example of that.

 

EXAMPLE

 

a)    Write the function called tossCoin() that returns either "H" or "T" to represent heads or tails.  Fifty percent of the time, it returns "H", otherwise, it returns "T".

b)    Test the tossCoin() function by simulating have tosses.  Your program should output to screen something like "HTHHT".  Everytime you run your program, that output should be different.

 

SOLUTION

 

Before coding, we need to write the function prototype for tossCoin().  Here is the info that we need to consider:

 

  • Return type: It will return "H" or "T".  So that is a String.
  • Function name: tossCoin
  • Parameters: none

 

With the above info, we can now write the function prototype for our work.  We can also write the main function prototype.  This gives us an idea of our setup.

 

public class Example1

{

    public static String coinToss()

    {

       

    }

   

    public static void main(String[] args)

    {

       

    }

}

 

Above, the coinToss function has a simple job.  It needs to simply return "H" or "T".  It is the main function that takes care of outputting any information to the screen.

It is time to implement the cointToss() function.  This is straightforward.  We generate a random number.  If it's less than 0.5, then we return "H".  Otherwise, we return "T".

 

    public static String coinToss()

    {

        if(Math.random() < 0.5)

        {

           return "H";

        }

        else

        {

           return "T";

        }

    }

 

Now that coinToss() has been implemented, we need to use it inside the main function. 

 

    public static void main(String[] args)

    {

        System.out.print(coinToss());

        System.out.print(coinToss());

        System.out.print(coinToss());

        System.out.print(coinToss());

        System.out.println(coinToss());

    }

 

Above in the main method, we simply call the coinToss() function five times.  The returned value from cointToss is immediately passed to the print function and then outputted to screen.

Here is the entire code together:

public class Topic29

{

    public static String coinToss()

    {

        if(Math.random() < 0.5)

        {

           return "H";

        }

        else

        {

           return "T";

        }

    }

   

    public static void main(String[] args)

    {

        System.out.print(coinToss());

        System.out.print(coinToss());

        System.out.print(coinToss());

        System.out.print(coinToss());

        System.out.println(coinToss());

    }

}

 

 

OBJECTS IN PARAMETER LISTS


We've seen that we can pass integers and doubles to functions.  We can also pass Strings. 

But we can also pass any type of object including objects that we create ourselves with our own classes.

 

EXAMPLE

 

In the example below, we have a Point class and a Practice class that creates and uses Point objects.  The quadrant function returns the quadrant in which the point is located on a graph (see image below.)

 

                                                            Image result for graph quadrants         

 

So, if the point has positive x and y values, then it is in quadrant 1.  If it has negative x and y values, it is in quadrant 3.

SOLUTION

 

public class Practice

{

    public static void main(String[] args)

    {

        Point pt1 = new Point();

        pt1.x = 5;

        pt1.y = 9;

       

        Point pt2 = new Point();

        pt2.x = 4;

        pt2.y = -8;

       

        System.out.println(quadrant(pt1));

        System.out.println(quadrant(pt2));

    }

   

    public static int quadrant(Point p)

    {

        if (p.x > 0 && p.y > 0)

        {

           return 1;

        }

        else if (p.x < 0 && p.y > 0)

        {

           return 2;

        }

        else if (p.x < 0 && p.y < 0)

        {

           return 3;

        }

        else

        {

           return 4;

        }

    }

}

 

EXECUTING THE CODE

 

The code above outputs the following to screen:

1

4

 

 

PASSING BY VALUE

 

When we pass a primitive data type (int, double, boolean, …) to a function, the function makes a copy of that value.  So, if the copy of the value is changed inside the function, then the original is not affected.  This concept is called passing by value.

 

Java applies the concept of passing by value to all non-objects such as int, double, boolean and so on…

 

 

EXAMPLE - PASS BY VALUE

 

The example below will output the value 10 twice.  It shows the concept of passing by value.  When the variable a is passed to the test function, a copy of it is made for use inside test and is called val.  Inside test, val is changed to 25 but that doesn’t affect the value of a since val is its own variable.

 

public class ExamplePBV

{

    public static void main(String[] args)

    {

        int a = 10;

        System.out.println(a);

        test(a);

        System.out.println(a);

    }

   

    public static void test(int val)

    {

        val = 25;

    }

}

 

 

PASSING BY REFERENCE

All objects in Java are passed to functions using the concept passing by reference.  When we pass an object to a function, only the reference to the object’s data is copied.  The data itself is not duplicated in memory.  The consequence is that if we change an object in the function, it is also changing the original object.

 

Below is a reminder of what an object looks like in memory when it is created.  The blue arrow is really just a number that references the address where the data is stored and is actually called a reference.

 

 

Now let’s look at an example program showing the effect of pass by reference.

 

 

EXAMPLE – PASS BY REFERENCE

 

First, we need a simple Point class:

 

public class Point

{

    public int x;

    public int y;

}

 

In the main function below, the first output statement will display 5 8 on screen but the second output statement will display 0 0 on the screen.  This is because the data of Point p is altered inside the function (where it is actually called Point tmp).

 

public class ExamplePBR

{

    public static void main(String[] args)

    {

        Point p = new Point();

        p.x = 5;

        p.y = 8;

        System.out.println(p.x + " " + p.y);

        test(p);

        System.out.println(p.x + " " + p.y);

    }

   

    public static void test(Point tmp)

    {

        tmp.x = 0;

        tmp.y = 0;

    }

}

 

As Java enters the test function, memory looks like the diagram below.  Notice the reference that p contained has been copied to tmp.  They both now refer to the same object data in memory.  So changing the data using tmp is the same as changing it using p.

 

 

And after executing the statements tmp.x = 0; and tmp.y = 0;, memory looks like this:

 

 

And, after the function ends, then tmp ceases to exist and we are left with only the reference p.

 

 

 

 

 

<EXAMPLE COMING>

Get a rectangle and return the point that represents that top right of the rectangle

 

<EXAMPLE COMING>

Distance between two points