BFOIT - Introduction to Computer Programming

Types and Method Arguments/Parameters

Introduction

As I did with Logo, my objective is to get you writing programs as quickly as possible.  You've written some simple programs already.  But, the most important thing to get you up to speed on (so that you can write more complex programs) is how to invoke existing procedures and how to write you own procedures.  I just used the word "procedures" since that's what they were called in Logo - in Java you work with methods.

A major difference between Logo and Java is the way things in the languages are typed.  Compared to Logo, Java is a strongly-typed programming language.  All fields and methods in Java must be declared to be a specific type. All Literals in Java are inherently a specific type.

In this lesson, you will learn

  1. why strong typing can be a good thing to have in a programming language,
  2. the primitive Java types that are pretty much like different kinds of things you worked with in Logo,
  3. the syntax for int and String literals,
  4. what method arguments and parameters are, and
  5. the syntax for type specifications in method declarations, and
  6. how to invoke methods given method-header information, either from JavaDoc documentation or actual method definitions.

Why Have Strict Typing in a Programming Language

If you just look around, there are all sorts of things which come in many different types.  Think about the audio and video stuff; there are audio cassettes, CDs, DVDs, VHS tapes, and MP3 players.  Each is different.  It makes no sense to try to put one of these into a player that was built to accept another.  You wouldn't try to put a VHS tape into your audio cassette tape player, even if all you wanted to do was listen to the soundtrack.  Although some MP3 players accept a memory stick, they won't accept your CDs.  Each player accepts a specific type of medium which it was designed for.

We are now living in a digital world.  What this means is that we now can represent anything as a bunch of bits.  This is very powerful; it allows you exchange things like photographs, songs, videos you record, etc... in e-mail, using peer-to-peer file sharing programs, via WWW servers, FTP, etc... across the Internet.  When you are surfing the Web, you can click on a button and hear a bit of a new song by your favorite artist - and the quality of the sound is very good.

But, inside of programs, this "everything is just a bunch of bits" can be very dangerous.  Imagine some futuristic computer program that a 9-1-1 operator could have.  When a phone call is received, a standard phone could send a digital message containing the GPS location of where the call is coming from.  This would allow the 9-1-1 operator to bring up the location of the caller on his computer display.  This would, no doubt, help in directing the right aid where its needed.  But, what if a non-standard phone sends the caller's phone number instead of GPS coordinates.  To the computer it's just a bunch of bits - unless told otherwise, the computer would convert the phone number bits and end up with a bad location.  This is not good - it could cost lives.

Mistakes in software (bugs) can have disasterous consequences.  Differences that are obvious to humans can't be detected by a computer.

In older programming languages, software developers had no choice other than to represent everything as numbers.  Java's support for objects and their explicit types are a dramatic improvement.

In an attempt to produce software that is more reliable, Java forces software developers to specify the type of everything in a program.  It is very easy to create a new type whenever one is desireable.

A Sampling of Commonly Used Types

To introduce some of Java's types, I'm going to compare them to the Logo types you have been using.  Table 23.1 shows uses of literal constants for all of the data types I used in the Logo lessons.

 Logo
type
 Logo Example  Java
type
 Java Example
 number
 forward 100
 int
 obj.setFontSize(48);
 word
 if equal? :answer "y 
 char
 if ( answer == 'y' )
 word
 print "word
 String
 System.out.print("word");
 sentence
 println [Two words]
 String
 System.out.println("Two words"); 
 predicate 
 output "true
 boolean 
 return true; 
Table 23.1

Notes:

Java actually has a bunch of numeric types; I am only introducing int at this point.  The limitations of int, i.e., the subset of Integers that is encompasses, will not be a problem for the material I cover.

The first example of a Logo word that I have mapped to the char Java type is a word made up of a single character.  Just an FYI in case you didn't make the connection.

int and String Literals

From the JLS (Java Language Specification):

      A literal is the source code representation of a primitive
      type, the String type, or the null type...
			

In Table 23.1, I used literals in all of the examples.  In one case, I had the number "48" and in a couple of places I had characters surrounded by double-quote characters.  These were int and String literals, respectively.  Time for you to learn more about them.

int Literals

The Java keyword int is an abbreviation for integer. Integers are whole numbers; the negative whole numbers, zero, and the positive whole numbers.  In mathematics, there is no limit placed on integers; they go on forever in both the positive and negative directions.  But, Java explicitly defines the limits of numbers of all types that it supports. An int covers the range: -2,147,483,648 through 2,147,483,647. 

int literals are entered into source code as a sequence of decimal digits.  Multi-digit numbers (i.e. those greater-than or equal to ten (10)) must start with a digit in the range 1..9 - you can't have a leading zero.  Non-zero int literals that start with zero are expected to be in either the octal radix or the hexadecimal radix.

Some examples of int literals are:

        0       -99       16384       20050501       -459
			

Some examples of illegal int literals are:

        099       32,768       2147483648
			

String Literals

String literals are composed of a pair of double-quotation marks with characters in between them.  The value of the literal is the stuff between the quotes.

Some examples of String literals are:

        ""       "A four word String"       "numeric operators: + - * /"
			

Since there will be times when you will want to include a double-quotation character in a String, Java has <EscapeSequences> for characters that are special.  To include a double-quotation character in a String literal, you put a backslash character in front of it.  Here's an example:

        "String literal with \" in it"
			

There are a bunch of other <EscapeSequences>.  I'll cover one more you probably will need, the newline.  To construct a String that contains more than one line of characters, you include a backslash followed immediately by the lowercase 'n' character ('n' stands for newline).  For example:

        "A line of text\nfollowed by a second line of text"
			

That's enough about literals for now.  I'll cover boolean, char, null, and other numeric types when I use them in an exercise or example.

Arguments and Parameters

Time to learn a couple of computer language terms that allow us to be more specific in our discussion of method declarations and invocations.

In the Logo lessons, the name input was associated with both the variables that procedures have for values passed to them when they are invoked and the actual values passed at each invocation.  These are actually two different things.

formal parameter
Formal parameter is the name of a variable declaration that is made in a method's header.  So, when I am talking in terms of the source code that makes up the definition of a method, the variables that will hold values passed to it are called formal parameters. The term is often simply called a parameter.
actual argument
Actual argument is the name for a value associated with a method invocation - a value passed to the invoked method.  The source code for method invocations includes the actual arguments.  Actual arguments are the values place in corresponding method parameters.  The term is often simply called an argument.

The Syntax of Method Declarations

There is no magic to invoking methods in Java.  It's actually very simple; you just have to look at the method your going to invoke's declaration.  The header part of a method's declaration tells you a lot.  Here are the method-headers for a few of the methods in the EventsStuff class.

1 2 3 4 5 6 7
 optModifiers   type   methodIdentifier   (   parameterDeclaration   , ...   ) 
 public
 void
 printInWindow
(
 String message
 
)
 public
 void
 setFontSize
(
 int size
 
)
 public
 void
 setWindowHeight
(
 int height
 
)
 public
 void
 setWindowWidth
(
 int width
 
)
Table 23.2

The first row of the table is just the column numbers so that I can refer to them in this explanation.  The numbers are much shorter than the names of things.

The second row is a template where I've given names to the things that make up a method header.  For instance, column 1 is the optional modifiers component of the method header.  Column 2 is the method's type (the type of the value it returns).  Column 3 is the method's name, its identifier.  And, columns 4 and 7 are punctuation.  The parenthesis that surround the parameter declarations.

The column that I'm going to be referring to for the remainder of this section is column 5.  This column is the first input parameter that the method is expecting.  Column 6 should be interpreted as zero or more occurances of column 5, repeated as needed.  It is only here for completeness; so far, you are only working with methods that accept a single parameter.

Rows 3 through 6 are method headers.  They are the methods provided in the last lesson's class: ExtendsStuff.  Review its method summary documentation.

Check out row 3.  The printInWindow( ) method has a single parameter.  Its declaration has two parts to it: a type (in this case String - ignore the "java.lang. prefix for now) and an identifier (in this case message).  You don't need to concern yourself with the identifier, at this point you only need to know the type of the parameter, String in this case.

The rest of the rows (4-6) are methods that you probably have not invoked yet: setFontSize( ), setWindowHeight( ), and setWindowWidth( ).  These methods also expect a single parameter; but, they take a number of type int. You've seen examples of how to provide a String literal when a parameter of type String is required.  So, now that you've seen what a literal of type int looks like, you should be able to figure out how to invoke methods with int parameters.

Invoking Methods, Given Method-Header Information

So now you know how to read a method-header to determine what the type of each argument must be.  Let's wrapup with how to construct proper invocations of the methods.

As a starting point, take a look at a template for the source code that you need to write to invoke a method, and some examples; you are already familiar with two of them.

1 2 3 4 5 6 7
 objectVariable   dotOperator   methodIdentifier   (   argument   , ...   ) 
System.out
.
println
(
 "Hello World!"   
)
obj
.
printInWindow
(
 "Hello World!"   
)
obj
.
setFontSize
(
72  
)
obj
.
 setWindowHeight 
(
300  
)
obj
.
 setWindowWidth 
(
800  
)
Table 23.3

The first row of this table is just the column numbers, so that I can refer to them in this explanation.

The second row is a template where I've given names to the things that make up a method invocation.  For instance, column 1 is the object that supports the method.  Column 2 is the dotOperator which is used for invocation of a method provided by an object.  Column 3 is the name of a method, the method's identifier.  And, columns 4 and 7 are punctuation, the parenthesis that surround the parameter declarations.  The column that I are going to be talking about for the remainder of this lesson is column 5.  This column is the first input argument.  Column 6 should be interpreted as zero or more occurances of column 5, repeated as needed.  It is only here for completeness; so far, you have only been working with methods that accept a single parameter.

Rows 3 and 4 are the method invocations that you've already used.  For println( ) and printInWindow( ), each expects one argument, a String.  You provided String literals as your arguments - words surrounded by a pair of double-quote characters, e.g., "Hello World!" was your first String.

Rows 5 - 7 are examples of how you would construct invocations of the other methods provided by class: ExtendsStuff.  These methods are expecting to get numbers, arguments of type int.  In these examples, I am providing int literals.

Just knowing how to use these two types (String and int) will allow you to write some very interesting programs, as you'll see in the next lesson.  But, practice invoking the new methods in the table above by completeing the exercises below.

If you want to see examples of proper and improper argument types, click here.

Summary

Everything in Java has a type, either explicitly declared or implied (i.e. literals).

Methods may have arguments (inputs) provided to them when they are invoked.  Even if a method does not expect any input, the method header specifies this with a pair of parenthesis with nothing in them.  By looking at the documentation for any method, you can determine how to invoke/use it, more specifically, what you need to provide to it.

Exercises

Study the documentation for ExtendsStuff and invoke the methods that it provides to:

  1. change the size of the window that appears on the display
  2. change the size of the text that is displayed in the window


Back to Extending Existing Classes
Go to the Table of Contents
On to Turtle Graphics in Java

Public Domain Mark
This work (BFOIT: Introduction to Computer Programming, by Guy M. Haas),
identified by Berkeley Foundation for Opportunities in IT (BFOIT),
is free of known copyright restrictions.