Main
Introduction
Message Board
Tutorials
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
About
Contact Us
II. Fundamentals of Programming

Programming languages are to the computer programmer what written languages are to the writer. Therefore, they must be good to work with. But what makes a powerful programming language? The authors of Java, the programming language with which we will work with throughout this website, claimed and summarized the language's power with these buzzwords:

Simple, object oriented, distributed, robust, secure, architecture neutral, portable, interpreted, high performance, multithreaded, and dynamic

To the beginner of computer programming, these words mean nothing and indeed do not relate to the core part of programming. In its true roots, a powerful programming language has to have at least three elements, which, in the words of Professors Harold Abelson and Gerald Sussman at MIT, are primitive expressions, means of combination, and means of abstraction.

Primitive expressions are the most basic element of a programming language. They represent the stuff we manipulate in a computer program. This "stuff" includes what are called data and procedures.

Means of combination are ways with which we put together primitive expressions to represent more complex data and procedures.

Means of abstraction are ways with which we give names to data and procedures so that we can have a more systematic and organized way of programming. There are also many other advantages to data abstraction that we will soon discover in this website.

Indeed, these three elements are the backbones of a good programming language. Most of the popular languages of today, including Java, fit these criteria. However, we picked Java for this website because it is widely popular and has many characteristics like those mentioned earlier in the "buzzwords" that might prove useful in the future but are not essential to the basis of computer science.

A. Expressions, data types, and variables

Expressions

When we program in a high-level language, we do not type in binary code. Indeed, programming languages are set-up so that they are more readily comprehensible by us humans. The four basic arithmetic operations (addition, subtraction, multiplication, and division) can be represented with +, - , *, and / in Java. There is also what is called the modulo operator % which divides two numbers and gives the integer remainder.

For example, if we want to add two numbers, 5 and 6, we would just type in the following

5+6

in Java and many other programming languages. The code 5+6 here is called an expression. As said earlier, expressions represent data and procedures. In this case, our expression represents "the result of adding the numbers 5 and 6." Likewise, 3+2*6 and 101 are expressions.

In technicality, Java expressions comprises of what are called literals, variables, operators, or a combination of them. Literals are constant values like numbers, operators are things like the adding sign + that perform a certain operation, and variables will be discussed later on in this section. 

Statements and comments

In general, when you look at Java code, it'll be lines of code ending with semicolon ';'. Every line of code until the semicolon is usually called a statement, and a semicolon in Java indicates the end of the statement. Theoretically, you can put as much empty spaces as you want between the "words" of a statement, and so the semicolon serves to tell the Java interpreter that the statement has come to an end.

Comments are words in code that are not part of the code. You indicate comments in Java by starting with //. Everything after // on a line of code will be skipped by the Java interpreter.

Data Types

We said earlier that expressions represent data and procedures. But what exactly do data and procedures mean? Here we will first talk about data. Data is basically the "stuff" we manipulate or work with in a computer program. For example, numbers are a form of data. There are many types of data, and in many programming languages, we classify data into different groups called data types. In Java, there are 8 primitive data types that are included in the language. Later on we'll learn how to create our own data types.

The first four data types are used to store numbers. More specifically, the numbers they store must be integers, which means numbers with no decimal values. For example, the number 1043 is an integer and so is 0 and -23, but 2.3 is not an integer.

Why, then, do we need four different data types for integers? That's because the four different data types have different ranges, or how big they can be. The greater the range of the data they can store, the more memory is consumed by the program. Therefore, usually it is a good programming habit to predict the range of the values of a program and use the appropriate data types to minimize the amount of memory consumed. Here is a table indicating the integer data types with their respective ranges and memory consumption.

Table: Integer Data types

Data Type

Range

Memory Consumed

int

-2,147,483,648 to 2.147.483.647

4 bytes

short

-32,768 to 32,767

2 bytes

long

-9,223,372,036
854,775,808L to 9,223,372,036,
854,775,807L*

8 bytes

byte

-128 to 127

1 byte

* When using the data type long, you must put the suffix L after the number. Otherwise, you will have a problem.

 

Similarly, there are two data types to represent "floating-point numbers," or numbers with decimals. They are:

Table: Floating-point Data Types

Data Type

Range

Memory Consumed

double

± 1.79769313486231570E+308

8 bytes

float

±3.40282347E+38F

4 bytes

When you have a floating-point number, by default Java takes it as a double. Therefore, if you want to use the float data type, you must explicitly write F after the number. Also, the E in the range denotes scientific notation, which is a method of representing numbers. saying E+308 is roughly saying "multiply by 10 to the 308," or adding 308 zeroes after the number.

 

The seventh primitive data type, the char type, in Java is used to represent single characters. Characters include letters, such as 'a' and 'z' and are surrounded by single quotes. They also include the character of the digits 0-9. However, you must surround them with single quotes (e.g. '2') for them to be of char type. Characters also include the punctuation marks and basically any single symbol you can type or see on the computer, including the copyright sign ã . Java characters are coded in a scheme called Unicode and thus are two bytes, different from the one-byte ASCII (ANSI) scheme used by some other programming languages such as C. Because Java uses Unicode, it can represent a whole lot of other characters that don't really mean anything. Usually those characters are used to code non-Roman letters, such as Chinese characters. To represent the non-common Unicode characters, we usually use the prefix \u (to represent Unicode) and then put the code number after it in hexadecimal (e.g. '\u2122'). Some of the special characters can be easily represented in Java with the following "escape sequences"

Table: Java Escape Sequences For Special Characters

Escape Sequence

Name

Unicode Value

\b

backspace

\u0008

\t

tab

\u0009

\n

linefeed

\u000a

\r

carriage return

\u000d

\"

double quote

\u0022

\'

single quote

\u0027

\\

backslash

\u005c

 

Table: The char Data Type

Data Type

Range

Memory Consumed

char

N/A (65,536 different characters possible. About 35,000 are used right now)

2 bytes

 

The last primitive data type in Java is called boolean. It expresses what are called Boolean values, which represent either true or false (and yes, you actually type in the word true or false).

 

Variables

The most basic form of data abstraction is creating variables. When we create a variable, we are basically telling the computer to allot a space in memory to hold data later on. The value of the data can change, hence the term variable. Java is what is called a type explicit programming language, so all variables you use must first be declared with its data type early on. You must also indicate the variable name or identifier by which you will reference the allocated space in memory later. The syntax ("grammar" of a programming language) of variable declaration in Java is the following:

(modifiers) ;

The optional "modifiers" will be explained later when we talk about object-oriented programming.

For example, if we wanted to make a variable indicating the age of a person, we could do the following:

short age; // declaration of variable age

Note that the semicolon at the end is required since this is a complete Java statement.

We chose the short data type because human ages are generally less than a hundred but might sometimes be over 127, the byte data types' maximum value, especially due to the improvement of technology and medical procedures.

Right now age has no particular value. In some programming languages, the starting or initial value is automatically set at 0. But others don't do anything about it and you can't be sure about the value since you have no idea what that chunk of memory indicated before you declared the variable. Therefore, we must first initialize the variable by using the equal sign = to assign a value to it.

age = 0; // assignment

This sets the initial value of age to zero. Java will not allow you to use a variable before you give it an initial value. Therefore, many people like to put the declaration and initialization together in one statement.

short age = 0; // declaration and initialization of age.

Another example can be:

char my_favorite_letter = 'v'; // declaration and initialization

Afterwards, if you want to access the variable, you just type in its identifier and you can use it freely like a literal. If you want to modify the variable's value, you can just use the assignment operator (equal sign). 

int number1 = 15;
int number2 = 10;
int number3 = 0;
number3 = number1 + number2; //now number3 = 25 

Special Assignment Operators

In addition, there are various "shortcut" assignment operators that you can use in Java. There are the +=, -=, *=, and /= operators, which works in the following manner:

number1 += 1;

which is equivalent to saying:

number = number + 1;

There are also the increment and decrement operators, ++ and --. They are equivalent to saying +=1, and -=1, respectively. For example, to increment the value of a variable by 1, you can say:

number1++;

In actuality, you can even put the increment/decrement operator in front of the variable, which will have a slightly different meaning. Either way, the variable will still be modified, but the difference can be seen when you use it to further assign another variable's value. For example:

int number1=5;
int number2=0;

number2 = number1++; // number2 is 5; number1 is 6
number2 = ++number1; // number2 is 7, number1 is 7

When the ++ is put at the back, number2 receives the value of number1 first, and then number1 is incremented by 1. Then, when the ++ is put in the front, number1 is incremented first (since the ++ is in front) and then the new value is passed to number2. The first case is called the post-increment operator, and the second is called the pre-increment operator.

B. Arrays and Strings

Arrays

Arrays are an extension to variables and its usefulness will be seen later on. But it basically allows you to have a group of variables of the same data type with the same identifier. How, then, do you differentiate between the different variables? Well, that's where the index or key come into play. The index is a number used to reference a particular variable in an array. In Java and many other languages, an index value of 0 indicates the first variable in the array and an index value of 1 indicates the second variable, and so on. An array is declared in the following manner:

[] = new [];

The complex notation is due to the fact that Java arrays are what are called "objects," which we'll discuss further in the Object-Oriented Programming section.

For example we can do this:

int[] our_first_array = new int[10]; // creates integer array with 10 slots

This creates an array with 10 slots, thus able to fit 10 variables of type int. Then to initialize, for example, the first variable in the array we do this, and afterwards we can use it just like any other variable.

our_first_array[0] = 123; // intializes first slot of array
number3 = our_first_array[0] + number1;

To find out the length of a string, just use .length. For example, typing our_first_array.length will return the integer 10.

As you can see, initializing all slots of an array would become difficult when the array size is large. But we can actually automate the process using what are called "loops," which we'll discuss later.

Multi-dimensional Arrays

Multi-dimensional arrays, or arrays of arrays, can be implemented in a straightforward manner. For example, if you want a 2D 5-by-5 array, you would write:

int[][] test = new int[5][5];

Then, to work with the array, you just do the same as before, except now there are two indices (plural of index) you have to indicate. For example, test[4][4] refers to the last slot of the array.

You don't always have to specify the length of the arrays of your array. For example you can have an array of integer arrays of length 5 and length 7. To implement this, you just specify the first number when creating your array. Then you create each member array of the array one by one.

int[][] test2 = new int[3][];  // 3 int arrays 
                               // of unknown size
test2[0] = new int[5];  // 1st member array of 
                        // test2 has 5 elements
test2[1] = new int[7];  // 2nd member array of 
                        // test2 has 7 elements

Strings

There is a special data type in Java called String (please note the capital S in String). It is not one of the primitive data types but somewhat acts like one. It is actually something called an object, which we'll discuss later. Usually in programming, a string refers to a group of characters, and so it shouldn't be surprising that in some languages, a string is implemented with an array of characters. However, this is not the case in Java, which includes a special string type that is simplified so that it can be used more or less like a primitive type. To create a string in Java, you would do the same as you create variables of primitive data types, like this:

String text1 = "To be or not to be, that is the question.";

Note that the text in a string is enclosed with double quotes (") while a char character is enclosed with single quotes ('). This is always the case for strings. Inside strings, you can also enclose the special characters using the unicode or escape sequences like '\n' for the newline symbol.

You can put two strings together by using the concatenation operator, which in Java is just the add sign (+).

String text1 = "You shall not press down upon the 
                 brow of labor this crown of thorns,\n";

String text2 = "You shall not crucify mankind upon 
                a cross of gold.\n";

String text3 = text1 + text2;  // text3 will have both 
                               // clauses together, 
                               // separated by a newline.

Just like for arrays, to find out the length of your string, you can use .length.

Sometimes you might want to access a particular character in your string. For arrays, you could just put int the index with brackets [], but you can't do this for strings. Instead you have to use, charat(). For example, if you want to access the second character of text1 (the 'o'), you type text1.charat(1) (just like in arrays, you start with 0, not 1).

To compare and see if two strings are equal, you can NOT use the == operator. This is due to the way strings are really implemented in Java. In Java, the string variable doesn't really hold the characters, it refers to some other place in memory that contains the characters. Therefore, if you try to test two strings for equality using ==, you're testing if they refer to the same place in memory, which is frequently not the case even if the two strings represent the same characters. What you should use instead is Java's equals method. For example, to test if text1 is equal to text2, type:

text1.equals(text2) // returns true if text1 and text2 are equal

You can also create arrays of strings in a similar fashion to arrays of integers and other primitive types.

C. Basic I/O (Input/Output)

Text Output in Java

One of the most first things people learn in a new programming language is how to output text to the screen and read characters from the keyboard. The output part is fairly simple in Java. To print something on the screen and a newline afterwards (so that when you output again, it will start on a new line), you simply type in:

System.out.println("your text!");

Be sure to enclose your text with double quotes "" as they are necessary. Later, when we talk about object-oriented programming, you'll understand the System.out.println part, but for now, just remember the syntax, and be sure to have the capitalization exactly the way it's printed or else it won't work. Note that for some "special" characters, like the ", you can't just type that in your code. Instead, to avoid confusion with other parts of code, you have to type in its Unicode value \u0022 or its escape sequence \".

If you ever want to print out the value of a variable, just attach it outside of the double quotes with a plus sign +, like this:

System.out.println("The value of our variable called myint is: "+myint);

Be sure not to enclose the variable with double quotes. Doing that will print the variable name "myint" not its value.

If you don't want the newline symbol automatically attached, you can use:

System.out.print("your text with no newline aftewards!");

If you ever want to manually put in the newline symbol, just use the escape sequence \n.

Basic Number Formatting (Optional Section)

Sometimes the number doesn't look good when you print it. It might have too many decimals or something. To format numbers in Java requires the use of classes, which we will discuss in more detail when we talk about Object-Oriented Programming, but for now, just follow these basic principles.

First, if you ever want to format text you have to put in the line import java.text.*; in the very beginning of your program, before everything else. Doing this tells Java to look up its prewritten libraries with the formatting instructions. Next, in your variable declarations, type in

NumberFormat nf = NumberFormat.getNumberInstance();

Now you can set the number of maximum and minimum integer and fraction (decimal) digits you want to display by typing in:

nf.setMinimumIntegerDigits(2)
nf.setMaximumFractionDigis(4);

This will set the minimum number of integer digits displayed to 2 and the maximum fractional (decimal) digits displayed to 4. Thus, if your number were 3.333333..., it would be displayed as 03.3333 You can do similar things for maximum integer digits and minimum fraction digits as well.

Actually though, there is one last step before the outputting. You would use your normal System.out.println or System.out.print but instead of just typing in the name of your variable, you would put the code nf.format like this:

System.out.println(nf.format(mynumber));

And that's basaically all there is to simple number formatting.

Input in Java

Basic input from the keyboard in Java is a little more complicated and requires more understanding of classes and object-oriented programming. Therefore, we will not discuss it right now. Now, onto control flow.

D. Control Flow

Up until now we have discussed different types of variables and how to assign values to them. Assigning and modifying values is a main part of programming, but not all of it. If all we had were assignment statements, we would get nearly nowhere. We need more types of statements that allow us to automate processes and control how our program run. These types of statements are called control flow structures. There are primarily two categories of control flow structures in Java, conditional and iterative (loops). Conditional structures are statements that allows the program to run differently depending on the results of tests you put in. Iterative structures, more commonly known as loops, allow you to run statements in a repeated fashion without having to type out the code every time. The name loop is given because of the circular and repeating nature of iterative structures.

If statements

Perhaps most basic conditional structure is the if statement. It works just like its name implies. "If" something is true, then do this, or else do something else, or translated into Java:

if () { 
    ;
}
else {
    ;
}

The "boolean expression" means you must put in something that either returns the boolean values true or false. In basic cases, this would be what is called a comparison statement, which compares two things using special comparison operators. For numbers (integers and floats), you have the following operators:

Table: Comparison Operators for Numbers

Comparison Operator Meaning
== equal to
!= unequal to
< less than
<= less than or equal to
> greater than
>= greater than or equal to

So, if we want to test whether the value of a variable we have is greater than 2, we can do the following:

if (myint > 2) {
    System.out.println("myint is greater than 2");
    System.out.println("you can have many statements 
                        inside the braces");
}
else {
    System.out.println("myint is not greater than 2");
    myint = 2; // now myint is equal to 2;
}  
  

For the char type, the comparision operators are almost identical. For example 'B'>'A' will return true while 'z'<'y' will return false. However, you should not mix up uppercase and lowercase letters as they are different. We encourage you try out some if tests to see the order of the characters. For example, are the uppercase letters "bigger" than the lowercase letters?

To combine multiple tests in one expression, you can use the "boolean operators." They are && (called AND), || (called OR), and ! (called NOT). If you connect two boolean expressions into one with the AND operator, the new expression will only return true if both original expressions are true. Similarly, the OR operator will return true only if either one or both of the expressions are true. The NOT operator negates the original value of the expression; hence, if it's originally true, the NOT will change the overall expression to false and if it's orignally false, NOT will change it to true.

For example, take a look at the following tests:

if ((myint >= 1)&&(myint <=; 10)) {
	System.out.println("myint ranges from 1 to 10");
}

if ((myint = 2)||(myint = 5)) {
	System.out.println("myint is either 2 or 5");
}

if (!(myint = 4)) {
  System.out.println("myint is not 4"); 
  // here we could have used != instead
}  
  

Switch statements

The switch statement can possibly be considered a more complex conditional structure. In it, you compare a single variable's value to a number of test values and do things accordingly if there is a match. The syntax is:

switch ()
{
  case :
    ;
    break; // this statement
    // quits the switch
	case :
    ;
    break; 
    ...
  default:
    ; 
    // these statements are executed 
    // if the interpreter gets to this point
    break; 
    // not necessary here, only 
    // put in for good programming habit
}

The syntax is more or less self-explanatory, but you have to be extra careful of the break statements. If you don't put them in after each case, the interpreter will continue to run the rest of the cases, including the default case, which can give you unwanted results. Why? Although running the other test cases would probably only slow the program, the default case, originally intended as an "otherwise do this" case, is actually run if the interpreter reaches it. Thus, if you don't put in the break's, your program could find a matching test case, execute the statements, and then continue on to the default case and execute those statements, too!

For example, try executing the following the program, setting myint equal to 2, with and without the break statements:

switch(myint)
{
  case 1:
    System.out.println("myint is 1");
    break;
  case 2:
    System.out.println("myint is 2");
    break;
  case 3:
    System.out.println("myint is 3");
    break;
  default:
    System.out.println("myint is neither 1, 2, or 3");
    break;
}

Loops/Iteration

As said before, loops allow repeated statements to be automated. In Java, there are primarly 3 different loop structures. The first is the for loop, which has the following syntax:

for (;;) {
  ;
}

The first part of the for loop can seem confusing at first. First, you have to understand how for loops work. In a for loop, we usually have a "counter" variable to be used solely for counting the cycles of the loop. In the "initialization" part of the loop, we initialize the counter variable, usually to 0. In the "end requirement" part of the loop we put in the condition with which the loop ends. The loop will continue to repeat itself until that expression is evaluated true. The "counter incrementer" part is where you put in an expression that will be executed to modify, usually increase, the value of the counter after every cycle of the loop. Here's a working example.

for (int i=0;i<10;i++) {
  System.out.println("The counter is now at "+i);
}

This program has the integer variable i as the counter. The first part initializes i to 0. The second part is the test, which tells the interpreter to test whether i is less than 10 after every cycle of the loop. The last part tells the interpreter to increment i by 1 after every cycle. Thus, the program will run a total of ten times (starting at 0, 1, 2... all the way to 9. When i is 10, the loop will no longer be executed since i<10 is false).

Another loop statement in Java is the while statement. While perhaps not as simple for in some cases, it is still very useful and has more versatility, unlike for which is very limited to iterative processes with a counter. while has the following syntax:

while () {
  ;
}

The while loop works like this: at the beginning of each cycle, the test expression is tested. If it is true, the interpreter goes on to run the statements in the loop, which should contain something to change whatever the test expression is testing. Otherwise, the test expression will always evaluate true and the loop never ends. This is in general bad programming practice and is called an infinite loop.

The following is an example of a while loop (note that the result is the same as the for loop code shown earlier):

int i=0
while (i<10) {
  System.out.println("The counter is now at " + i);
  i++;
}

Note the initialization has to be done outside of the loop. Otherwise, i will be set to 0 every time the loop executes and the loop will never end.

The last loop control flow structure in Java is the do-while. It works almost the same way as the while loop, with the following syntax.


do {
  ;
} while ();

The only difference between the two is that for the while loop, the test expression is tested before each execution of the statements, while for the do-while, the test expression is run after the statements are executed. While this might not seem to make a big difference, it does. If the test expression is false to begin with (even before the loop is executed once), the statements will not be executed in the while loop, but they will be run in the do-while loop one time.

In case you are wondering, the for statement, like the while statement, also checks the test expression before each cycle.

Using Loops to Initialize Arrays

We've said before that to avoid lots of repetitive code, we can use a loop to initialize an array. An example of how may be done is the following:

int[] myarray = new int[100];

for (int i=0;i<100;i++) {
  myarray[i]=0;
}

Jumping Out of Loops

Sometimes you want your program to quit a loop before it finishes all its cycles. For example, say you have a loop that searches through large array for a certain number. Once you've found it, you don't want the program to continue running the loop to the array's end because that would just take up unnecessary processing time. Thus, in Java there is a way to quit a loop. Remember the break statement for the switch control flow structure? Well, the same break statement can be used to quit a loop, like this.

for(int i=0;i<10;i++) {
  System.out.println(i);
  if (i==6) {
    break;
  }
}

Doing this makes the loop quit when i is 6.

But what if you have a nested loop, or a loop inside of another loop? How do you break out of the whole nested structure from the inner loop? In this case, you can also you break but there's a little more work. You will have to put what is called a label right before the whole nexted structure--the outer loop. To put a label, just choose any valid identifier name and put a colon (:) after it in a single line. Then when you break, you put break followed by the label name and end it with a semicolon (;).

Here's an example. The loop would generate a 10-by-10 multiplication table, but now it will stop when it reaches 5 times 5.

NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumIntegerDigits(2);

ourlabel:
for (int i=1; i<11; i++) {
  for (int j=1; j<11; j++) {
    if(i==5&&j==5) {
      break ourlabel;
    }
    System.out.print (nf.format(i*j) + " ");
  }
  System.out.print("\n");
}

E. A Working Java Program

Now that we've got the basics down, the question we face is: how do we put them together into a Java program that compiles and runs? We can't simply put down our variable declarations and code, can we? In fact, we always have to put in some more or less generic code in our program for it to run properly. Instead of explaining it, we will just give a working example and then discuss the parts.

public class OurFirst  // required code
{
  public static void main (String args[]) // required 
  {
    int i;
    int[] MyArray = new int[10];
	
    for(i=0;i<10;i++) {
      MyArray[i] = i+1; // initializes MyArray
    }

    for(i=0;i<10;i++) {
      if (MyArray[i]%3==0) {	// check for remainder
        System.out.println("The number "+MyArray[i]+" 
                            IS divisible by 3");
      }
      else {
        System.out.println("The number "+MyArray[i]+" 
                            ISN'T divisible by 3");
      }
    }
  }
}

So what does this all mean? The first line public class OurFirst is required. Furthermore, the name there (OutFirst in our case) has to match the name of the java file (thus, our example will have to be saved as OurFirst.java).

The next statement, public static void main(String args[]), is also required. Anything inside of the "main" braces will be run.

To begin with, we declared our variables. Then, we initialized the array with a for loop. Afterwards, we have another for loop that runs through the array, printing out the value of each element and whether or not the number is divisible by 3 (remember that the % modulo operator gives the remainder. So if the remainder is 0, it is divisible).

Lastly, to end our program, we put in all the corresponding close braces (keep in mind that the number of open braces have to equal the number of close braces).

For simple programs, just write all code inside the "main" part. But as we'll discover in the next section, we can put code outside of "main."

F. Programming With Methods

Background History

Now we will learn about splitting up programs into sizeable parts. First we will tell a little history. In the early days of computer programs, the pioneer programmers would just write out all code in one big blob with what are called "gotos" to point from one line of code to another. Because of the unstructured and clumsy nature of programming this way, that kind of code has since been named "spaghetti code." To make programming more structured, people came up with what is called "procedural programming." The fundamental idea behind procedural programming is that we can split a big program into small parts, called procedures, which are neatly arranged and named for easy reference later. So, say we have some account balance program. We might split the program up into different procedures for depositing, withdrawal, etc. The advantage to procedural programming is that we can eliminate some of the former clumsiness. Furthermore, different people can work on different procedures or modules and then at the end combine all into the complete program. But perhaps most importantly, with procedural programming, if we want to modify our program later on, we can just take out the procedure that needs change and work only with that and not touch the other good code. Most programming languages of today support some form of procedural programming.

As promising as procedural programming was, it was not enough. Later on, people came up with what is called "Object-Oriented Programming" (OOP) that extends procedural programming into a new level. Java is one of the first major languages to be completely OOP-based.

So why should we still learn procedural programming, you ask? The reason is that procedural programming is actually part of the groundwork and a subset of OOP and is also very useful. However, one thing you have to keep in mind is that because Java is a completely OOP language, even as we program "procedures" we actually have to mask them with OOP code and terminology.

The Terminology

You will probably hear people use different names for procedures, depending on their programming background, ranging from "procedures" to "functions" to "methods" to "modules."

However, they are not precisely the same, according to the common computer terminology. Procedures are code that do something but do not return any data. Functions are like procedures but return data, usually the result of whatever function it performs. A method is the OOP (hence Java) term for both procedures and functions. Lastly, the word module is a relatively informal term that refers to procedures and functions or sometimes, a file containing many procedures and functions.

To stick with correct Java terminology, from now on we will use the word method to refer to this kind of code.

So How Do You Do It?

Remember the sacred "main" thing we mentioned earlier, where all the code is put inside? Well, it turns out, when you write a method, you DON'T put it inside of "main"! In fact, "main" itself is just another method, albeit a special one. Therefore, it shouldn't surprise you that methods we create will look a lot like "main." The exact syntax is:

(modifiers)   ((arg1_type arg1), 
                                 (arg2_type arg2)...))
{
	;
}

For the optional modifiers, just put public for now. We'll discuss its meaning when we talk about OOP. The return type, however, is not optional. Some methods "return" data after performing calculations and other processing, and so you have to put in what type of data (int, double, char, etc.)the method will return beforehand. Then, usually at the end of the method, you would return the value by saying:

return somevalue;

The "somevalue" can be a literal but more likely a variable or expression. If your method does not return anything, then put the word void for the return type and don't worry about the return statement. Theoretically, you can also return an array. In that case, you will have to specify the return type with brackets [] in first line of the method. When returning the array, just type the array name with no brackets.

Some methods have what are called "arguments" or "parameters" (there is a slight difference between the terms though). That means they require some data to be passed to them when you "call" or use the method. For example, say you have a method that calculates the price of something after tax. Then, you might want the method to require the base price and tax rate as parameters so that people with different items and tax rates can all use the method.

With that said, let's write the AfterTax method.

public static double AfterTax (double price, 
                              double taxrate)
{
	double totalprice = 0;
	totalprice = price * (1 + taxrate/100.0);
	return totalprice;
}
  

Then, to use the method, you call it from, usually, another method, like main. To call it, you just type its name and the necessary parameters (if there are no parameters, then just put empty parentheses).

To sum up, here is an example of a complete program called Prices that contains and calls the AfterTax method. Note that we put AfterTax before main. Although the order does not matter in Java, it is convention to put main at the end of the program and all the manually-coded methods at the before it.

public class Prices{
	
  public static double AfterTax (double price, 
                                double taxrate)
  {
    double totalprice = 0;
    totalprice = price * (1 + taxrate/100.0);
    return totalprice;
  }
	
  public static void main(String args[])
  {
    double oldprice = 2.50, tax  = 7.5;
    double newprice = 0;
    newprice = AfterTax (oldprice, tax);
    System.out.println("The base price of the 
                        item is $"+oldprice);
    System.out.println("With a tax rate of "
                        +tax+"%,");
    System.out.println("The after tax price 
                        is $" + newprice);
  }
}

Arrays as Arguments

What if we want to pass a whole array as an argument? How can we implement that? Actually, it's very simple. All you have to do is when you write in the parameters of your method, put in the data type of your array with brackets [] following it to indicate that an array is to be passed to this method. For example, say you want to have a method that'll print out the elements of any integer array. You would write something like this:

public static void ArrayPrint(int[] a)
{
  for(int i=0;i

When you call the array, you will just call it using the array name (without the brackets).

By Value or By Reference?

Try running the following code.

public class byvalue
{
  public static void Test(int a)
  {
    System.out.println("a is originally "+a);
    a++;
    System.out.println("a is now "+a);
  }

  public static void main(String args[])
  {
    int i = 10;
    System.out.println("i is originally "+i);
    Test(i);
    System.out.println("i is now "+i);
  }
}

i is passed to the method Test. But in the Test, a is changed. The question is: did i change?

If you ran the code, you would see that i does NOT change. Why is that? To understand this, you have to learn a little about how arguments are passed in Java. When you call a method and pass in an argument, Java actually creates a copy of the value of the variable you passed in memory and that copy is used in the method and if it's modified, the original variable remains unchanged. This type of behavior is called by-value passing because you only give the method in the value of the variable and not the variable itself. The following figure illustrates by-value passing.

Although this is frequently the case, things aren't always passed by value in Java. If an argument of a method is an object (e.g. an array), which we will talk more about later, a reference or pointer to spot of the object in memory is passed. Therefore, when the object is modified in the method, the original object will also be modified since it uses the reference to look up where the original object is in memory and changes it. The following illustrates this behavior, known as by-reference passing. In this particular example, we have an integer array i that is passed to Test and in the method, an element of the array is changed. Write the code for this with output statements and you'll see that the original array will indeed be modified.

This ends our discussion of methods. Next up is recursion.

 

G. Recursion

The obvious way to use procedures or, rather, methods is to call the written method from another method in your program. But can a method call itself? At first, this might seem like an illogical thing to do, but with proper usage we can actually implement useful routines using the art of recursion.

The term recursion refers to an algorithm or process that has a method calling itself.

The classic recursion algorithm is the "factorials" algorithm. A factorial of a number (denoted by n! where n is the number) is the product of all integers from 1 to that number. Thus 3! = 3*2*1 = 6. 0! is by definition 1.

Without recursion, we can quite easily implement a factorials method using a loop, and it would look something like this:

public static int LoopFactorial(int num)
{
	int result=1;
	for (int i=1;i

Using recursion, we have to take into account the fact that the factorial of a number is just the number times the factorial of the number 1 smaller than it, and the factorial of the number 1 smaller than it is just that smaller number times the factorial of the number 2 smaller than the original number and so forth. Expressed mathematically, n! = n * (n-1)! = n * (n-1) * (n-2)!. Using this method of thought, our recursion factorial method would do the following given the number it's calculating the factorial of:

  • If the given number is 0 or 1, return 1 since 0!=1!=1.
  • If the given number is not 0 or 1, return the number * the factorial of the number 1 less than it.
We can translate this way of thought into a recursive method:
public static int RecurFactorial(int num)
{
	if((num==1)||(num==0)) {
		return 1;
	}
	else {
		return num*RecurFactorial(num-1);
	}
}

What is the benefit of recursion? Some people think speed, but actually, in general, a recursive algorithm takes more processing time and memory than its iterative counterpart, if one is possible. The key benefit to recursion then is its simplicity. Although in the factorial example, it is hard to see the recursive code being any simpler than the iterative, when we try to program more complex tasks, it is not always easy or even possible to use an iterative algorithm. Recursive algorithms are generally very straightforward in thought, and this is its advantage.

Basic Scope

The topic of scope is often discussed when learning a programming language. What is scope? Scope refers to the study of how and where data can be accessed.

For the most part, the basic fact to know now is that you cannot have one method access the variables of another variable at the same level of a hierarchy. For example, if your class only has two methods, main and Method1, you cannot access variables of Method1 directly from main, or vice versa.

And that's it for our discussion of the Fundamentals of Programming in Java. Now let's head on to Object-Oriented Programming.

 
(c) 2001 Thinkquest Team C0120962. All rights reserved.