Before Objects

The INFO1-CE9416 catalog description says that it covers all the material in INFO1-CE9614. The INFO1-CE9614 catalog desciption says that INFO1-CE9614 is a course on the Java language.

A computer is a machine that follows a list of instructions called a program. Some examples of computers are Android devices such as phones or tablets. An example of a program is an Android app.

In the future it will be possible to write programs in English, but that day has not yet come. For the time being, we have to write programs in simpler languages such as Java.

Values

A program tells a computer how to to manipulate values such as numbers or pieces of text. There are many types of values.

int Values

The simplest type of value is an int, which is an integer (whole number) in the range −2,147,483,648 to 2,147,483,647 inclusive. Therefore there are 4,294,967,296 possible int values. If you’re interested, I’ll show you where these numbers come from. They are not arbitrary:

−2,147,483,648
2,147,483,647
4,294,967,296
=
=
=
−231
231 − 1
232

Later, we’ll get the min and max values from two variables with the last name Integer, Integer.MIN_VALUE and Integer.MAX_VALUE.

Literals

A number or other value written in a program is called a literal. There are rules you have to follow when writing a literal of each type. When writing an int literal, for example, do not write the commas and do not write any decimal point after the int literal. The int value 2,147,483,647 would therefore have to be written as the literal 2147483647 in a Java program.

Variables

A variable is a container in the computer that holds a value. Every variable has a name. The name starts with a lowercase letter, and the remaining characters (if any) can be letters (upper or lowercase), digits, or underscores. Typical variable names might be i, textView, or LENGTH_LONG. Case counts. In other words, we could not use i and I as alternative names for the same variable. You have to pick one or the other and stick with it.

There are many types of variables.

int Variables

The simplest type of variable is an int variable, which is capable of holding any int value. In other words, an int variable can hold any integer (whole number) in the range −2,147,483,648 to 2,147,483,647 inclusive.

Each Java statement ends with a semicolon. I wrote a comment above our first Java statement. In a file written in the language XML, comments started with <!-- and ended with -->. In a file written in the language Java, a comment can start with // (no space betwen the slashes) and ends at the end of the line.

Case counts when you write a variable name such as i or a Java keyword such as int.

The content of a variable can change as the app is running. That’s why they’re called variables. For example, the following variable is born holding the number 10, but its content changes to 20 a fraction of a second later.

        //Create an int variable named i and store the int value 10 into it.
        int i = 10;

        //Change the value (content) of the variable i from 10 to 20.
        //This statement does not create any new variable.
        //It merely changes the value of the existing variable i.
        i = 20;

Instead of the above int i = 10;, we could write two separate statements to create the variable and put its first value into it. (Putting the first value into a newborn variable is called initializing the variable.)

        //Create an int variable named i and store the int value 10 into it.
        int i;
        i = 10;

        //Change the value (content) of the variable i from 10 to 20.
        //This statement does not create any new variable.
        //It merely changes the value of the existing variable i.
        i = 20;

But it’s less error prone to create and initialize the variable with the single statement int i = 10;.

Expressions

We could write more complicated expressions in place of the 10 and 20 in our first Java example. In the first statement below, the operators + and the * are both touching the 2. But the * gets to sink its teeth into the 2 first, because muliplication has higher precedence than addition. Pity My Dear Aunt Sally.

        int i = 4 + 2 * 3;  //a roundabout way of saying int i = 10;

        i = i + 10;         //a roundabout way of saying i = 20.  Can abbreviate to i += 10;
        int i = 10;

        //Three ways to do the same thing:
        i = i + 1;
        i += 1;
        ++i;

String values

Another type of value is a string of characters, i.e., a series of characters. A string might consist of one word, or several words, or a complete sentence, or just a single character, or even of no characters at all.

A string written in the program is another example of a literal. There are rules you have to follow when writing a literal of each type. When writing a string literal, for example, you have to surround its characters with a pair of "double quotes". The string value “Hello World!” would therefore have to be written as the string literal "Hello World!" in a Java program.

A String variable is capable of holding any value of type String. The S of String must be uppercase, even though the i of int was lowercase. When an int value such as the content of j is pasted with a plus sign onto a string value, the int automatically turns into the string of digit characters (in this case, the two digits "30") that spell out the value of the int.

        int i = 10;
        int j = 10 + 20;
        String sentence = "The value of j is " + j + ".";

        int sum = 0;
        sum += 10;   //means sum = sum + 10;
        sum += 20;
        sum += 30;
        //At this point, sum contains 60.
        String s = "cup";
        String t = "cup" + "cake";
        String sentence = "The value of t is " + t + ".";

        String sum = "";
        sum += "Chi";   //means sum = sum + "Chi";
        sum += "ca";
        sum += "go";
        //At this point, sum contains "Chicago".

Display the content of a variable.

Run the Testbed app. First, use your web browser to download the file Bed.zip in that example. Look in your Downloads folder to see what the browser downloaded. Unzip the file if the browser did not unzip it for you. Unzipping the file should create a folder named Bed. Then in Android Studio, pull down
File → Open…
and select the folder Bed. In the Android Studio project view, double click on the file app/java/edu.nyu.scps.bed/MainActivity.java to edit it.

In the onCreate method of class MainActivity, change the statements between the two
//-----------------------------
comments to the following.

        //-----------------------------
        int i = 10;
        display("i", "The value of i is " + i + ".");
        //-----------------------------

A method is a short list of instructions—in effect, a little program. This app contains a method named display. To tell the computer to execute the method, write the name of the method followed by a pair of parentheses. We can also give the method one or more parameters: values such as numbers or strings for the method to chew on and work with. Write the parameter(s) in the parentheses. If there is more than one parameter, separate them with commas.

The display method requires two parameters that are string values. We created the second parameter using two + operators to paste together three shorter string values.

Then run the app.

Input an int value and store it into a variable.

The above method display displayed a dialog box on the screen, but did nothing else. It did not give us any value when it was finished being executed.

The following method getInt will give us a value when it is finished being executed. This value is called the return value of the method. There are many types of values. The return value of the method getInt is of type int. We can therefore write the expression
getInt("Friends", "How many friends do you have?")
in any place where we could have written an expression of type int such as 10 or 5+5. For example, we could write the getInt expression to the right of the equal sign that initializes a newborn variable.

The getInt method displays a keyboard with a decimal point, but nothing will happen if you press the decimal point. getInt only lets you type in a whole number. That’s why it’s called getInt. See the android:inputType attribute of class EditText.

        //-----------------------------
        int numberOfFriends = getInt("Friends", "How many friends do you have?");
        display("Friends", "You have " + numberOfFriends + " friends.");
        //-----------------------------

What happens if you type an integer outside the range −2,147,483,648 to 2,147,483,647 inclusive? Do not type the commas.

long

A long literal ends with uppercase L. 9,223,372,036,854,775,807 is pronounced “nine quintillion, 223 quadrillion, 372 trillion, 36 billion”, etc. Later, we’ll get the min and max values from Long.MIN_VALUE and Long.MAX_VALUE.

        int minInt =            -2147483648;   //-231
        int maxInt =             2147483647;   // 231 - 1

        long minLong = -9223372036854775808L;  //-263
        long maxLong =  9223372036854775807L;  // 263 - 1

boolean

We have seen that a value of type int can be any one of 4,294,967,296 possible values. A value of type boolean can be any one of only two possible values, true and false. It’s named after the English mathematician George Boole. Use a boolean variable to hold a boolean value.

        //Create a boolean variable named verdict and put true into it.
        boolean verdict = true;

        verdict = false;

        //Toggle the verdict.  Exclamation point means "the opposite of".
        verdict = !verdict;
        //-----------------------------
        boolean verdict = true;

        display("boolean values",
                "The verdict is " + verdict + ", which is the opposite of " + !verdict + ".");
        //-----------------------------

Float and double

A float or double value is a number that can have a fraction. Storing a double takes more memory than storing a float; doing arithmetic with a double takes more time than with a float. For drawing graphics in the screen, expressions of type float will suffice. No one can see a millionth of a pixel.

A float literal ends with lowercase f. Without the f, it would be a double literal.

	int i =    3;                //cannot hold a fraction
	float f =  3.14159f;         //can hold up to  6 significant digits
	double d = 3.14159265358979; //can hold up to 15 significant digits

The division operator / will give us an int (whole number) result if both of its operands are expressions of type int.

	int i = 38;
	int j = 5;

	float quotient1 = i / j;	//Truncation: put 7.0f into quotient1.
	float quotient2 = 38 / 5;	//Truncation: put 7.0f into quotient2.

The division operator will give us a float result, which can have a fraction, if at least of its operands are expressions of type float. (For the time being, we are not thinking about double at all.)

	float f = 38.0f;
	float g = 5.0f;

	float quotient3 = f / g;        //No truncation: put 7.6f into quotient3.
	float quotient4 = 38.0f / 5.0f; //No truncation: put 7.6f into quotient4.

Type Conversion

The value of the expression dividend is of type int. To make this value appear to be of type float in the eyes of the surrounding parts of the program, write (float) in front of the expression. The (float) is called a cast.

        int dividend = 100;
        int divisor = 7;

	float quotient1 = dividend / divisor;               //Put 14.0f into quotient1.
	float quotient2 = (float)dividend / divisor;        //Put 14.285714f into quotient2.
	float quotient3 = dividend / (float)divisor;        //Put 14.285714f into quotient3.
	float quotient4 = (float)dividend / (float)divisor; //Put 14.285714f into quotient4.

Many lines of output

Humans like to count starting at 1. Computers like to count starting at 0 because array subscripts start at 0.

The \n looks like two characters, but it really stands for the newline character. This invisible characters moves us down to begin a new line.

        //-----------------------------
        //Print the numbers from 0 to 9 on ten separate lines.
        String output = "";
	output += "0\n";   //means output = output + "0\n";
	output += "1\n";
	output += "2\n";
	output += "3\n";
	output += "4\n";
	output += "5\n";
	output += "6\n";
	output += "7\n";
	output += "8\n";
	output += "9\n";
        display("List of numbers", output);
        //-----------------------------

Don’t type the same code over and over again.

The statements within the {curly braces} are called the body of the loop. The body of the loop will be executed repeatedly as long as the value of the variable i is less than 10. This won’t last forever, because the value of i increases by 1 each time the body of the loop is executed.

        //-----------------------------
        //Print the numbers from 0 to 9 on ten separate lines.
        String output = "";
        int i = 0;

        while (i < 10) {
	    output += i + "\n";   //means output = output + i + "\n";
            ++i;                  //means i = i + 1;
        }

        display("List of numbers", output);
        //-----------------------------

Put all three vital statistics on the same line.

The i = 0 is the starting point of the loop. The i < 10 is the stopping point. The ++i is the stride. A for loop collects these three vital statistics onto one line.

There’s another advantage to using a for loop. Let’s suppose that the variable i is intended for use only within the loop. It would be a waste of resources to bring the variable to life before the loop begins, or to keep it alive after the loop is over. If the variable is created after the ( of the loop, as in the following example, then the i will exist only during the duration of the loop.

        //-----------------------------
        //Print the numbers from 0 to 9 on ten separate lines.
        String output = "";

        for (int i = 0; i < 10; ++i) {
	    output += i + "\n";   //means output = output + i + "\n";
        }

        display("List of numbers", output);
        //-----------------------------

Count by twos

        //-----------------------------
        //Print the numbers from 0 to 8 by twos on five separate lines.
        String output = "";

        for (int i = 0; i < 10; i += 2) {
	    output += i + "\n";
        }

        display("List of numbers", output);
        //-----------------------------

Count down

The expression --i decreases the value of i by 1.

        //-----------------------------
        //Print the numbers from 10 down to 0 on eleven separate lines.
        String output = "";

        for (int i = 10; i >= 0; --i) {
	    output += i + "\n";
        }

        display("List of numbers", output);
        //-----------------------------

100 Bottles of Beer on the Wall

        //-----------------------------
        //Print the lyrics to "100 Bottles of beer on the Wall".
        String output = "";

        for (int b = 100; b > 0; --b) {
	    output += b + " bottles of beer on the wall,\n";
	    output += b + " bottles of beer.\n";
	    output += "If one of those bottles should happen to fall,\n";
	    output += b - 1 + " bottles of beer on the wall.\n\n";
        }

        display("List of numbers", output);
        //-----------------------------

To decrease the font size of the TextView that displays the dialog’s message, append the following two statements to the public void display(String title, String message) method of class MainActivity in the file MainActivity.xml.

        TextView textView = (TextView)alertDialog.findViewById(android.R.id.message);
        textView.setTextSize(12.0f);   //in sp's

Trace the app

See Debugging With Android Studio.

Output two or more numbers during each iteration.

        //-----------------------------
        String output = "";

        for (int h = 2; h <= 8; ++h) {
            output += 4 * h + " pierogies feed " + 2 * h
                + " people or " + h + " Hungarians.\n";
        }

        display("Pierogies", output);
        //-----------------------------
        //-----------------------------
        //The big green signs every 10 miles on the New York State Thruway.
        String output = "";

        for (int a = 98; a >= 38; a -= 10) {   //a -= 10 means a = a - 10
            output += "Albany   " + a + "\n";
            output += "Montreal " + (a + 210) + "\n";
            output += "Buffalo  " + (a + 270) + "\n\n";
        }

        display("Heading north on NYS Thruway", output);
        //-----------------------------
}

Accumulate a running total

This loop proceded silently. There is no output until the loop is over.

        //-----------------------------
        //Display the sum of the numbers from 1 to 100 inclusive.
        int sum = 0;

        for (int i = 1; i <= 100; ++i) {
            sum += i;   //means sum = sum + i;
        }

        display("Sum", "The sum of the numbers from 1 to 100 is " + sum + ".");
        //-----------------------------

Three pieces of Toast

        //-----------------------------
        //Display three pieces of Toast.
        for (int i = 0; i < 3; ++i) {
            Toast toast = Toast.makeText(this, "This is toast number " + i + ".", Toast.LENGTH_LONG);
            toast.show();
        }
        //-----------------------------

Loops with float and/or double numbers

        //-----------------------------
        //Lengths of a set of organ pipes spanning one octave.
        double factor = Math.pow(2, 1.0/12.0); // twelfth root of 2
        double length = 100;
        String output = "";

        for (int i = 0; i <= 12; ++i) {
            output += i + "\t" + length + "\n"; //means output = output + i + "\t" + length + "\n";
            length *= factor;                   //means length = length * factor;
        }

        output += "\nfactor = " + factor;
        display("One octave", output);
        //-----------------------------

Compute the length drectly by raising 2 to the i/12.0th power during each loop. Does this give you more accurate answers?

Three TextViews

In activity_main.xml, change the RelativeLayout to a LinearLayout with android:orientation="vertical".

        //-----------------------------
        //Create three TextViews and put them into the LinearLayout.
        ViewGroup viewGroup = (ViewGroup)findViewById(android.R.id.content);
        LinearLayout linearLayout = (LinearLayout)viewGroup.getChildAt(0);

        for (int i = 0; i < 3; ++i) {
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,   //width
                ViewGroup.LayoutParams.WRAP_CONTENT    //height
            );

            //Convert 16dp to pixels.
            Resources resources = getResources();
            DisplayMetrics displayMetrics = resources.getDisplayMetrics();
            float f = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16.0f, displayMetrics);
            int px = Math.round(f);
            layoutParams.setMargins(0, px, 0, 0);   //left, top, right, bottom

            TextView textView = new TextView(this);
            textView.setLayoutParams(layoutParams);
            textView.setPadding(px, px, px, px);   //left, top, right, bottom
            textView.setBackgroundColor(Color.RED);
            textView.setText("This is TextView " + i + ".");
            linearLayout.addView(textView);
        }
        //-----------------------------

Infinite loop

Do not attempt to run the following example. In any case, the display will never be executed. We will use an infinite for loop in Pong.

        //-----------------------------
        String output = "";

        for (;;) {
            output += "It was a dark and stormy night.\n";
            output += "Some Indians were siting around a campfire.\n";
            output += "The their chief rose and said:\n\n";
        }

        display("Infinite loop", output);
        //-----------------------------

if Statement

The (parentheses) are always required. The {curly braces} are required only when they enclose more than one statement (or when they encluse zero statements). But it would make your instructor happy if you always wrote the curly braces.

        //-----------------------------
        int i = getInt("Type a number.",
            "Please type an integer (whole number) in the range -2147483648 to 2147483647 inclusive.");

        if (i < 0) {
            display("Negative", "The number " + i + " is negative.");
        }

        if (i >= 0) {
            display("Nonnegative", "The number " + i + " is nonnegative.");
        }
        //-----------------------------

Repeat it forever.

        //-----------------------------
        for (;;) {
            int i = getInt("Type a number.",
                "Please type an integer (whole number) in the range -2147483648 to 2147483647 inclusive.");

            if (i < 0) {
                display("Negative", "The number " + i + " is negative.");
            }

            if (i >= 0) {
                display("Nonnegative", "The number " + i + " is nonnegative.");
            }
        }
        //-----------------------------

if-else Statement

The above pair of if statements were consecutive and mutually exclusive. No matter what the value of i is, exacly one of the if statements will be true. We can therefore combine them with the keyword else to steer the computer in one of two possible directions.

        //-----------------------------
        for (;;) {
            int i = getInt("Type a number.",
                "Please type an integer (whole number) in the range -2147483648 to 2147483647 inclusive.");

            if (i < 0) {
                display("Negative", "The number " + i + " is negative.");
            } else {
                display("Nonnegative", "The number " + i + " is nonnegative.");
            }
        }
        //-----------------------------

The last name of the variable INFINITY is Float. Another variable with the same first name is Double.POSITIVE_INFINITY.

        //-----------------------------
        for (;;) {
            float miles = getFloat("Miles", "How many miles did you drive?");
            float gallons = getFloat("Gallons", "How many gallons did you use?");

            float mpg;
            if (gallons == 0) {
                mpg = Float.POSITIVE_INFINITY;
            } else {
                mpg = miles / gallons;
            }

            display("MPG", "Miles per gallon = " + mpg);
        }
        //-----------------------------

The last name of the variable CONNECTIVITY_SERVICE is Context. && means “and”.

        //-----------------------------
        //Is the phone connected to the Internet?
        ConnectivityManager connectivityManager =
		(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
	NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        boolean isConnected = networkInfo != null && networkInfo.isConnected();

	if (isConnected == true) {                //All you need to say is if (isConnected) {
            display("Connected", "This device is connected to the Internet.");
	} else {
            display("Not connected", "This device is not connected to the Internet.");
	}
        //-----------------------------

Add the following element to the AndroidManifest.xml file immediatelty before the <application> element. See Using Permissions.

        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Without this permission, the logcat window of Android Studio will display the following error message.

06-05 11:17:06.960  17603-17603/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{edu.nyu.scps.bed/edu.nyu.scps.bed.MainActivity}: java.lang.SecurityException: ConnectivityService: Neither user 10073 nor current process has android.permission.ACCESS_NETWORK_STATE.
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.SecurityException: ConnectivityService: Neither user 10073 nor current process has android.permission.ACCESS_NETWORK_STATE.
            at android.os.Parcel.readException(Parcel.java:1425)
            at android.os.Parcel.readException(Parcel.java:1379)
            at android.net.IConnectivityManager$Stub$Proxy.getActiveNetworkInfo(IConnectivityManager.java:623)
            at android.net.ConnectivityManager.getActiveNetworkInfo(ConnectivityManager.java:425)
            at edu.nyu.scps.bed.MainActivity.onCreate(MainActivity.java:35)
            at android.app.Activity.performCreate(Activity.java:5104)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
            at dalvik.system.NativeStart.main(Native Method)
        //-----------------------------
        //Is the phone connected to the Internet?
        ConnectivityManager connectivityManager =
		(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
	NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        boolean isConnected = networkInfo != null && networkInfo.isConnected();

        ViewGroup viewGroup = (ViewGroup)findViewById(android.R.id.content);
        View rootView = viewGroup.getChildAt(0);

	if (isConnected) {
            rootView.setBackgroundColor(Color.GREEN);
	} else {
            rootView.setBackgroundColor(Color.RED);
	}
        //-----------------------------

Give the attribute android:id="@+id/textView" to the TextView in your activity_main.xml file. This will automatically create a Java variable named R.id.textView containing the TextView’s identifying number.

        //-----------------------------
        //Is the phone connected to the Internet?
        ConnectivityManager connectivityManager =
		(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
	NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        boolean isConnected = networkInfo != null && networkInfo.isConnected();

        TextView textView = (TextView)findViewById(R.id.textView);

	if (isConnected) {
            textView.setText("connected");
	} else {
            textView.setText("not connected");
	}
        //-----------------------------

Steer the computer in one of three possible directions.

else means “none of the above” or “as a last resort”.

        //-----------------------------
        for (;;) {
            int i = getInt("Type a number.",
                "Please type an integer (whole number) in the range -2147483648 to 2147483647 inclusive.");

            if (i < 0) {
                display("Negative", "The number " + i + " is negative.");
            } else if (i > 0) {
                display("Positive", "The number " + i + " is positive.");
            } else {
                display("Zero", "The number " + i + " is a big fat zero.");
            }
        }
        //-----------------------------

The last name of the variable ORIENTATION_PORTRAIT is Configuration. After pressing the dialog’ OK button, change the orientation of the phone.

        //-----------------------------
        //Display the orientation of the device.
        Resources resources = getResources();
	Configuration configuration = resources.getConfiguration();
	int orientation = configuration.orientation;

        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            display("Portrait orientation", "The device orientation is portrait.");
        } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            display("Landscape orientation", "The device orientation is landscape.");
        } else {
            display("Unknown orientation", "The device orientation is neither portrait nor landscape.");
        }
        //-----------------------------

Steer the computer in one of four possible directions.

        //-----------------------------
        for (;;) {
            int year = getInt("Type a year.", "Please type any year from 1752 onwards.");

            if (year % 400 == 0) {
                display("Leap year", year + " is a leap year.");
            } else if (year % 100 == 0) {
                display("Nonleap year", year + " is not a leap year.");
            } else if (year % 4 == 0) {
                display("Leap year", year + " is a leap year.");
            } else {
                display("Nonleap year", year + " is not a leap year.");
            }
        }
        //-----------------------------
        //-----------------------------
        for (;;) {
            int i = getInt("Type a number.", "Please type a nonnegative integer.");

            if (i == 1) {
                display("Ordinal form", "The ordinal form of " + i + " is " + i + "st.");
            } else if (i == 2) {
                display("Ordinal form", "The ordinal form of " + i + " is " + i + "nd.");
            } else if (i == 3) {
                display("Ordinal form", "The ordinal form of " + i + " is " + i + "rd.");
            } else {
                display("Ordinal form", "The ordinal form of " + i + " is " + i + "th.");
            }
        }
        //-----------------------------

Steer the computer in one of five possible directions.

&& means “and”. The first if says “if the last two digits lie between 11 and 13 inclusive”.

        //-----------------------------
        for (;;) {
            int i = getInt("Type a number.", "Please type a nonnegative integer.");
            int lastDigit = i % 10;
            int lastTwoDigits = i % 100;

            if (11 <= lastTwoDigits && lastTwoDigits <= 13) {
                display("Ordinal form", "The ordinal form of " + i + " is " + i + "th.");
            } else if (lastDigit == 1) {
                display("Ordinal form", "The ordinal form of " + i + " is " + i + "st.");
            } else if (lastDigit == 2) {
                display("Ordinal form", "The ordinal form of " + i + " is " + i + "nd.");
            } else if (lastDigit == 3) {
                display("Ordinal form", "The ordinal form of " + i + " is " + i + "rd.");
            } else {
                display("Ordinal form", "The ordinal form of " + i + " is " + i + "th.");
            }
        }
        //-----------------------------
        //-----------------------------
        for (;;) {
            int i = getInt("Type a number.", "Please type a nonnegative integer.");
            int lastDigit = i % 10;
            int lastTwoDigits = i % 100;

            String suffix;
            if (11 <= lastTwoDigits && lastTwoDigits <= 13) {
                suffix = "th";
            } else if (lastDigit == 1) {
                suffix = "st";
            } else if (lastDigit == 2) {
                suffix = "nd";
            } else if (lastDigit == 3) {
                suffix = "rd";
            } else {
                suffix = "th";
            }

            display("Ordinal form", "The ordinal form of " + i + " is " + i + suffix + ".");
        }
        //-----------------------------

An if statement in a for loop

The area of a circle is A = πr2. The Unicode code number of the character π is \u03C0. You can see it in the top row of the Greek and Coptic Code Chart in the Unicode Code Charts.

The last name of the method hypot is Math. The distance from the origin to the point (x, y) is Math.hypot(x, y).

        //-----------------------------
        //Compute the value of pi using the Monte Carlo method.
        int n = 1000000;   //total number of points
        int count = 0;     //number of points within the unit circle

        for (int i = 0; i < n; ++i) {
            double x = Math.random();   //random number >= 0 and < 1
            double y = Math.random();
            double distance = Math.hypot(x, y);

            if (distance < 1.0) {
                ++count;
            }
        }

        double pi = 4.0 * count / n;

        display("The value of \u03C0",
              "count = " + count + " out of " + n + "\n"
            + "computed \u03C0 = " + pi + "\n"
            + "actual \u03C0 = " + Math.PI + "\n"
            + "error = " + Math.abs(Math.PI - pi));
        //-----------------------------

switch, case, break

switch will be needed for Touch.

        //-----------------------------
        String output = "";

        for (int year = 2016; year <= 2036; ++year) {
            output += year + ": ";
            if (year % 4 == 0) {
                output += "presidential election year\n";
            } else if (year % 4 == 2) {
                output += "congressional election year\n";
            } else {
                output += "local election year\n";
            }
        }

        display("Election years", output);
        //-----------------------------
Election years
2016: presidential election year
2017: local election year
2018: congressional election year
2019: local election year
2020: presidential election year
2021: local election year
2022: congressional election year
2023: local election year
2024: presidential election year
2025: local election year
2026: congressional election year
2027: local election year
2028: presidential election year
2029: local election year
2030: congressional election year
2031: local election year
2032: presidential election year
2033: local election year
2034: congressional election year
2035: local election year
2036: presidential election year

The following switch statement produces the same output. It can be used when all the comparisons test the same expression (in this case, year % 4) for equality with a series of constants (in this case, 0 and 2). The expression can’t be of type float or type double.

        //-----------------------------
        String output = "";

        for (int year = 2016; year <= 2036; ++year) {
            output += year + ": ";

            switch (year % 4) {
                case 0:
                    output += "presidential election year\n";
                    break;

                case 2:
                    output += "congressional election year\n";
                    break;

                default:
                    output += "local election year\n";
                    break;
            }
        }

        display("Election years", output);
        //-----------------------------

Without the breaks:

        //-----------------------------
        String output = "";

        for (int year = 2016; year <= 2036; ++year) {
            output += year + ": ";

            switch (year % 4) {
                case 0:
                    output += "presidential/";

                case 2:
                    output += "congressional/";

                default:
                    output += "local";
            }

            output += "\n";
        }

        display("Election years", output);
        //-----------------------------
Election years
2016: presidential/congressional/local
2017: local
2018: congressional/local
2019: local
2020: presidential/congressional/local
2021: local
2022: congressional/local
2023: local
2024: presidential/congressional/local
2025: local
2026: congressional/local
2027: local
2028: presidential/congressional/local
2029: local
2030: congressional/local
2031: local
2032: presidential/congressional/local
2033: local
2034: congressional/local
2035: local
2036: presidential/congressional/local

switch acts as documentation. It calls attention to the fact that the same expression is being compared for equality to a series of constants. Often the constants will be static final fields of the same class:

        //-----------------------------
        //Press the OK button to dismiss the dialog before rotating the device.
        String output = "";
        WindowManager windowManager = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
        Display defaultDisplay = windowManager.getDefaultDisplay();

        switch (defaultDisplay.getRotation()) {
            case Surface.ROTATION_0:
                output += "right side up";
                break;

            case Surface.ROTATION_90:
                output += "bottom edge is to the right";
                break;

            case Surface.ROTATION_180:
                output += "upside down";
                break;

            case Surface.ROTATION_270:
                output += "bottom edge is to the left";
                break;

            default:
                output += "unknown rotation";
                break;
        }

        display("Rotation", output);
        //-----------------------------

Throw and catch an exception object

We try to give a value to the quotient variable inside the {curly braces} of the try block. But we had to define (create) the variable outside the braces in order to make the variable mentionable outside the braces in the call to display.

The Java continue statement makes us go back to the top of the for loop and begin another iteration. In this case, the display will not be executed.

Java float and double division by zero produces infinity (or a value that is “not a number”) instead of throwing an exception. That’s why we had to demonstrate with int.

        //-----------------------------
        //Execute the catch block if something goes wrong.
        //Skip the catch block if everything is okay.

        for (;;) {
            int dividend = getInt("Dividend", "Please type the dividend.");
            int divisor = getInt("Divisor", "Please type the divisor.");
            int quotient;
            
            try {
                quotient = dividend / divisor;
            } catch (ArithmeticException arithmeticException) {
                display("Attempted division by zero", arithmeticException.toString());
                continue;
            }
            
            display("Quotient", "quotient = " + quotient);
        }
        //-----------------------------

If the user types a divisor of 0, the output will be

Attempted division by zero
java.lang.ArithmeticException: divide by zero

I beieve that the only type of exception that can be thrown by the code in the above try block isoArithmeticException. But just in case some other type of exception could also be thrown,

        //-----------------------------
        //Execute the catch block if something goes wrong.
        //Skip the catch block if everything is okay.

        for (;;) {
            int dividend = getInt("Dividend", "Please type the dividend.");
            int divisor = getInt("Divisor", "Please type the divisor.");
            int quotient;
            
            try {
                quotient = dividend / divisor;
            } catch (ArithmeticException arithmeticException) {
                display("Attempted division by zero", arithmeticException.toString());
                continue;
            } catch (Exception exception) {   //any other type of exception
                display("Unexpected exception", exception.toString());
                continue;
            }
            
            display("Quotient", "quotient = " + quotient);
        }
        //-----------------------------

An array of strings

        //-----------------------------
        //What Chinese year is it?

        for (;;) {
            int year = getInt("Type a year.", "Please type a year.");
            int remainder = year % 12;

            if (remainder == 0) {
                display("Monkey", year + " is the Year of the Monkey.");
            } else if (remainder == 1) {
                display("Rooster", year + " is the Year of the Rooster.");
            } else if (remainder == 2) {
                display("Dog", year + " is the Year of the Dog.");
            } else if (remainder == 3) {
                display("Pig", year + " is the Year of the Pig.");
            } else if (remainder == 4) {
                display("Rat", year + " is the Year of the Rat.");
            } else if (remainder == 5) {
                display("Ox", year + " is the Year of the Ox.");
            } else if (remainder == 6) {
                display("Tiger", year + " is the Year of the Tiger.");
            } else if (remainder == 7) {
                display("Hare", year + " is the Year of the Hare.");
            } else if (remainder == 8) {
                display("Dragon", year + " is the Year of the Dragon.");
            } else if (remainder == 9) {
                display("Snake", year + " is the Year of the Snake.");
            } else if (remainder == 10) {
                display("Horse", year + " is the Year of the Horse.");
            } else if (remainder == 11) {
                display("Sheep", year + " is the Year of the Sheep.");
            } else {
                display("Unknown", year + " is the Year of the unknown.");
            }
        }
        //-----------------------------

The following program creates 12 variables of type String. The variables are named animal[0], animal[1], animal[2], etc.
animal[0] contains "Monkey".
animal[1] contains "Rooster".
animal[2] contains "Dog".
animal[11] contains "Sheep".
There is no animal[12]. The value of the expression animal.length is 12.

        //-----------------------------
        //What Chinese year is it?
        String[] animal = {
            "Monkey",    // 0
            "Rooster",   // 1
            "Dog",       // 2
            "Pig",       // 3
            "Rat",       // 4
            "Ox",        // 5
            "Tiger",     // 6
            "Hare",      // 7
            "Dragon",    // 8
            "Snake",     // 9
            "Horse",     //10
            "Sheep"      //11
        };

        for (;;) {
            int year = getInt("Type a year.", "Please type a year.");
            int remainder = year % animal.length;
            String a = animal[remainder];
            display(a, year + " is the Year of the " + a + ".");
        }
        //-----------------------------
        //-----------------------------
        //List the 12 animals.
        String[] animal = {
            "Monkey",    //  0
            "Rooster",   //  1
            "Dog",       //  2
            "Pig",       //  3
            "Rat",       //  4
            "Ox",        //  5
            "Tiger",     //  6
            "Hare",      //  7
            "Dragon",    //  8
            "Snake",     //  9
            "Horse",     // 10
            "Sheep"      // 11
        };

        String output = "";

        for (int i = 0; i < animal.length; ++i) {
            output += i + " " + animal[i] + "\n";   //means output = output + i + " " + animal[i] + "\n";
        }

        display("Chinese Zodiac", output);
        //-----------------------------
        //-----------------------------
        //Output the lyrics to "The Twelve Days of Christmas", one day per dialog.

        String[] a = {
                null,   //so that the partridge will have subscript 1
                "partridge in a pear tree.",
                "turtledoves",      // 2
                "French hens",      // 3
                "colly birds",      // 4; black as coal
                "golden rings",     // 5
                "geese a-laying",   // 6
                "swans a-swimming", // 7
                "maids a-milking",  // 8
                "ladies dancing",   // 9
                "lords a-leaping",  //10
                "pipers piping",    //11
                "drummers drumming" //12
        };

        for (int day = 1; day <= 12; ++day) {
            String title = "The " + day;
            String message = "On the " + day;

            if (day == 1) {
                title += "st";
                message += "st";
            } else if (day == 2) {
                title += "nd";
                message += "nd";
            } else if (day == 3) {
                title += "rd";
                message += "rd";
            } else {
                title += "th";
                message += "th";
            }

            title += " Day of Christmas";   //means title = title + " Day of Christmas";
            message += " day of Christmas\n";
            message += "My true love gave to me\n";

            for (int i = day; i >= 1; --i) {
                if (i > 1) {
                    message += i + " ";
                } else if (day == 1) {
                    message += "A ";
                } else {
                    message += "And a ";
                }
                message += a[i] + "\n";
            }

            display(title, message);
        }
        //-----------------------------

Three arrays of strings

We create one object of class Random with the Java keyword new. The return value of the object’s method nextInt is a random int that is ≥ 0 and < the parameter. The return value can therefore be used as a subscript into the designated array.

        //-----------------------------
        //"The Official Movie Plot Generator" by Jason and Justin Heimberg

        String[] subject = {
            "A cop who doesn't play by the rules",
            "A single mom",
            "Three naughty nurses",
            "An adorable panda cub",
            "A ruthless Mafia kingpin",
            "An ancient and powerful wizard",
            "A fraternity of lovable slobs, misfits, and drunks",
            "Adolph Hitler",
            "From a land where honor and tradition reign, comes the legend of a Samurai who",
            "A bumbling nerd",
            "Bigfoot",
            "A crackhead",
            "A flamboyantly gay hairdresser",
            "A retarded boy",
            "America's founding fathers",
            "A hockey mask-wearing psychopath",
            "A gangsta rapper",
            "An unrefined but precocious orphan girl",
            "The ultimate crime-fighting indestructible cyborg",
            "The Sesame Street puppets",
            "A small-town girl with big-time dreams",
            "A group of orthodox rabbis",
            "A burned-out hippie",
            "A Catholic priest",
            "A hooker with a heard of gold",
            "A grumpy midget",
            "A group of cantankerous senior citizens",
            "Jesus",
            "A no-nonsense Army drill sergeant",
            "A macho NFL quarterback"
        };

        String[] predicate = {
            "fight(s) crime",
            "raises(s) a baby",
            "discover(s) the wonders of self pleasure",
            "befriends(s) the creatures of the forest",
            "is/are on the run from the Mob",
            "quest(s) for a dragon's treasure",
            "indulge(s) in beer bashes, toga parties, and an assortment of ill-advised high jinks",
            "invade(s) Poland",
            "take(s) on an army of evil Ninjas",
            "become(s) immersed in hip-hop culture",
            "become(s) a nanny for a conservative aristocratic family",
            "coach(es) a hapless Little League baseball team",
            "hit(s) the Karaoke circuit",
            "grow(s) 50 times in size and goe(s) on a destructive rampage",
            "travel(s) through time",
            "hack(s) up coeds with a rusty machete",
            "becomes a pimp (become pimps)",
            "challenge(s) the social mores of upper class society",
            "command(s) a fleet of starships against a horde of insectoid aliens",
            "help(s) children learn to read",
            "get(s) transformed into (a) gorgeous sexpot(s)",
            "compete(s) in gritty inner-city street basketball tournaments",
            "go(es) on an LSD-induced psychedelic adventure",
            "discover(s) a hidden talent for dance",
            "struggle(s) to get off heroin",
            "try (tries) to lose (his/her/their) virginity",
            "battle(s) problem flatulence",
            "rise(s) from the grave",
            "rescue(s) a group of American P.O.W.'s",
            "come(s) out of the closet"
        };

        String[] modifier = {
            "with a mischievous orangutan",
            "while juggling work, parenthood, and finding personal fulfillment",
            "in two hours of the raunchiest hardcore porno action ever seen",
            "in this heartwarming animated adventure",
            "in the heart of the Amish country",
            "with a cunning elf, an obese ogre, and a belligerent dwarf",
            "despite being admonished by a crusty old dean",
            "in this documentary narrated by James Earl Jones",
            "in an action-packed epic filled with elaborate, acrobatic Kung-Fu fight sequences",
            "to win the heard of the high school dreamboat",
            "in the feel-good comedy of the year",
            "in order to pay off a gambling debt",
            "in  beat-up Buick",
            "in the middle of Downtown Tokyo (in Japanese with English subtitles)",
            "with a wise-cracking robot",
            "in a blood-filled teen slasher",
            "deep in the Compton ghetto",	//Los Angeles
            "in 1954 Baltimore (based on the Pulitzer Prize winning novel)",
            "shown in spectacular 3-D Imax",
            "in this powerful after school special",
            "set to an all-star '80's soundtrack featuring Air Supply, Journey, and Survivor",
            "to save the local synagogue",
            "with a magical talking bong, in this stoner cult classic",
            "in a rousing adaptation of the Broadway musical",
            "with the help of former tennis great Ivan Lendl (based on a true story)",
            "with the help of the ghost of Elvis",
            "set against the backdrop of a Florida retirement community",
            "in the inspiring story loosely adapted from the Bible",
            "in a Vietnamese prison camp",
            "and in the process learn(s) the true meaning of Christmas",
        };

        Random random = new Random();

        for (;;) {
            int randomSubject =   random.nextInt(subject.length);
            int randomPredicate = random.nextInt(predicate.length);
            int randomModifier =  random.nextInt(modifier.length);

            String output =
                subject[randomSubject] + "\n"
                + predicate[randomPredicate] + "\n"
                + modifier[randomModifier] + ".";

            display("Movie Plot", output);
        }
        //-----------------------------

Four arrays of strings

The i %= 1000 reduces the value of i to the range 0 to 999 inclusive.
The i %= 100 reduces the value of i to the range 0 to 99 inclusive.
The i %= 10 reduces the value of i to the range 0 to 9 inclusive.

        //-----------------------------
        //Display an integer as a roman numeral.
        String[] ones =      {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
        String[] tens =      {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
        String[] hundreds =  {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
        String[] thousands = {"", "M", "MM", "MMM"};

        for (;;) {
            int i;
            for (;;) {
                i = getInt("Type a number.", "Please type a number in the range 1 to 3999 inclusive.");
                if (1 <= i && i <= 3999) {
                    break;   //Break out of the innermost loop when valid input has been entered.
                }
                display("Invalid input", "The number " + i + " was outside the allowable range.  Please try again.");
            }
            int save = i;

            String output = thousands[i / 1000];
            i %= 1000;                   //means i = i % 1000;
            output += hundreds[i / 100]; //means output = output + hundreds[i / 100];
            i %= 100;                    //means i = i % 100;
            output += tens[i / 10];
            i %= 10;                     //means i = i % 10;
            output += ones[i / 1];

            display("Roman numeral", save + " in roman numerals is " + output + ".");
        }
        //-----------------------------