Welcome to COMP 6 -- Programming in Java -- Mr. Batarseh -- jbatarseh@bcconline.com

Lesson Plan #1

Chapter One

"Creating Your First Java Class."

+

Chapter Two

"Using Data within a Program"

Lesson Plan Overview
Objectives Lesson Plan Lecture Notes Textbook Reading Assignments/Coverage
Lab Assignment Quiz Assignment Discussion Question

"Lesson Plan Overview"

Chapter 1:

Chapter 1 provides context for the Java language by introducing concepts from procedural and object-oriented programming. Modeled after C++, Java is a full object-oriented programming language developed by Sun Microsystems, Inc. As do all object-oriented languages, Java possesses the three trademark features of encapsulation, inheritance, and polymorphism. Java programs take one of two forms: application or applet. The application program form serves the traditional program role in scientific and commercial activities. The applet program form is Web-based and generally dependent upon browsers.

Java programs are constructed in a text editor. Translation of a Java program into executable machine statements is a two step-process. First, the source code is compiled into a virtual machine language called bytecode. Second, the bytecode is interpreted into machine language statements within the Java Virtual Machine (JVM). The JVM interfaces with the operating system of specific platforms to execute the code line by line.

Sun Microsystems provides a free utility, J2 SDK, to aid program development. The J2 SDK contains a Java compiler, interpreter, debugger, the Java API (class library), demonstrations, and documentation, among other files. Familiarity with command-line techniques is required to manipulate the J2 SDK programs because (aside from the appletviewer) there is no built-in graphical user interface to these files. There are graphical tools called IDEs (Integrated Development Environments) that bundle a text editor and other SDK utilities. However, these more complex developer tools are not used to demonstrate the introductory programs.

Chapter 2:

Chapter 2 demonstrates how to store and manipulate various forms of data. Data may take on either on a constant or a changing value. In the former case, the literal value of a data item may be hard-coded into a program or stored in a symbolic name. In the latter case, data that changes requires a special container known as a variable. A variable is a named location in memory that stores the value of a particular data type. Data types are specified by a kind of data, operations on the data, and memory requirements. Java provides for eight built-in primitive data-types: byte, short, int, long, float, double, char, and Boolean. Primitive types may form the foundation for complex reference types, such as classes.

Variables must be declared before they can be used. A declaration statement contains a data type, variable name, optional assignment of value, and a semicolon. Declarations that include an assignment are known as initializations. Arithmetic and comparison operations are defined for the various integer and floating-point types. Simple arithmetic and comparison expressions contain a binary operator and two operands. Rules of precedence and associativity specify an order of operations for complex expressions. An arithmetic expression evaluates to a number, while a comparison operation evaluates to a Boolean value of true or false.

The char type stores a single character by its Unicode binary representation. The symbol assigned to a character variable is enclosed by single quotes. Special character pairs known as escape sequences are useful for controlling output. The String class stores and manipulates character sequences. String variables and literals, as well as other types, may be input and output using the console window as well as graphical dialog boxes. The JOptionPane class provides a number of methods for creating and managing interactive dialog. Three methods demonstrated in this chapter are: showMessageDialog() , showInputDialog(), and showConfirmDialog().

"Objectives"

You will have mastered the material in this lesson plan when you can:

From Chapter 1:

From Chapter 2:

"Lesson Plan Lecture Notes"

From Chapter 1:

Learning About Programming:

This section introduces the basic concepts of computer programming. A computer program is a set of instructions that the computer can execute to solve a particular problem. The computer only understands machine language instructions (binary zeroes and ones). Modern programming languages, such as Java and C++, are abstracted from the machine level. Their high-level (natural language like) statements must be compiled or interpreted into binary code understood by the machine. All programming languages have a set of syntax (grammatical) rules that must be followed when writing programs. The Java syntax is very similar to the C/C++ language syntax. All programs also follow rules of logic (or semantics), which structure statements to produce a desired outcome.

Introducing Object-Oriented Programming Concepts:

Procedural programs consist of variables, or named memory locations, that hold values during the program execution. The program also contains Java language keywords that are combined with the variables and operators to produce a program that will manipulate the values and produce the desired output. Different operations in a computer program are often grouped into blocks of code called procedures.

Object-oriented programming languages, such as Java and C++, group program variables with procedures to create program components called objects. Objects: (1) are created in programs to model concrete objects that exist in the real world, (2) have states, also called attributes or properties, that describe the characteristics of the object, (3) have methods, or procedures, that are encapsulated with the attributes of an object and can set or modify the state of the object.

The program templates for objects are known as classes. An existing object is said to be an instance of a class. The methods and attributes encapsulated by a class may be inherited, subject to access restrictions, by other classes. There is one more critical feature of object-oriented programming, polymorphism. Polymorphic methods have the same name, but distinct sets of operations based on the objects to which they apply. They are distinguished from one another at run-time based on the context in which they are called.

Learning About Java:

Java is an architecturally neutral programming language modeled after C++. It has many built-in features that simplify programming for the Internet and make it easy to implement security features. A Java program is compiled into bytecode that is then interpreted on the machine where the program is executed by the Java Virtual Machine (JVM) specific to that platform.

There is much confusion between the Java programming language, developed by Sun Microsystems, and the JavaScript scripting language developed by Netscape. Other than a similarity in syntax, there is no relation between the two. Java is a complete object-oriented programming language. JavaScript is a scripting language that is interpreted by a Web browser and is used to enhance Web pages. The name JavaScript was only used as a marketing strategy when JavaScript was released.

Java Program Types:

You can write two kinds of programs using Java. Programs that are embedded in a Web page are called Java applets. Stand-alone programs are called Java applications. Java applications can be further subdivided into console applications, which support character output to a computer screen in a DOS window, for example, and windowed applications, which create a graphical user interface (GUI) with elements such as menus, toolbars, and dialog boxes.

Analyzing A Java Application that Uses Console Output:

Console applications offer a simple introduction to programming in Java. The First class demonstrates how to print a literal string. The sole task of the seven line program is to output "First Java Application".

Understanding the Statement That Prints the Output

Among other entities, programs contain user-defined variables, string literals, and methods. A variable specifies a memory location. A string literal consists of a sequence of characters in double quotes. Methods are activated by statement known as a call. They may be passed pieces of information referred to as arguments, which are used to perform tasks.

The statement:

System.out.println( "First Java Application");

is an example of a call to a method of the out object that is contained in the static class System. This method accepts a string as an argument, in this case, "First Java Application" which is a string literal. The argument is passed to the method that displays it on the monitor. As do all Java statements, the call to println() ends with a semi-colon (;).

Understanding the First Class:

All programming statements in Java must be part of a class. A class name must conform to specific syntax rules.

1. The class name should be the same as the file name under which the program is saved.

2. Class names (identifiers) are case sensitive, for style purposes should be capitalized, and must start with a letter, underscore, or dollar sign. The remainder of the name may contain only letters, digits, underscores or dollar signs. Letters in this case may include international characters.

3. There are 48 keywords defined in Java. Keywords may not be used as identifiers such as variables or class names.

4. A class name cannot be one of the following values: true, false, or null. These identifiers are not keywords, but they are reserved.

5. The contents of a class are contained within curly braces ( { } )

6. A class can have an access modifier, such as Public, to describe when it may be accessed.

7. A class may contain any number of variables and methods

 

Understanding the main() Method:

The line:

public static void main(String[ ] args)

is the header for the actual program. Every executable must have a main() class. The first word, public, defines access level (in this case, the least restrictive). The keyword static indicates the method may be called independently of the object. The keyword void indicates that method does not return a value. Within the parentheses, String[] specifies argument type (string class). The name args is a placeholder for an argument of type String[]. The First class may be used as a shell (or template) by replacing println( ) with block comments..

Adding Comments to a Java Class:

Java programs may contain comments, which provide explanations of the program and its details, to help programmers understand the code, and to help with program modification and maintenance. Program comments are nonexecuting statements that you add to a program for the purpose of documentation. The three types of comments are:

Saving a Java Class:

Java classes are stored in secondary memory, such as a hard disk. All public classes are saved with a .java extension. For example, First.java is an appropriate name for the file storing the first Java program demonstrated in this text. As Java is case sensitive, the class name and file name must match.

Compiling a Java Class:

Java programs are compiled and run at the operating system prompt with the SDK utilities

To compile a Java program type javac MyClass.java , where MyClass.java is the name of the text file in which the program is saved, and MyClass is the name of the public class in the Java program. After MyClass is compiled into bytecode, it may then be interpreted into executable statements in the JVM.

Though the commands may have been correctly entered, the program itself may not compile due to syntax errors. Typing errors are a typical source for syntax violations.

Running a Java Application:

To run the program, type java Myclass (with no file name extension). This will run the program Myclass.class, which is the bytecode file, created by the Java compiler. The application output will then appear in the console window. See the Technical Notes for more information about compiling and running Java programs

Modifying a Java Class:

After viewing the results of your program, you may go back and revise the source, and recompile it, following the same steps given above.

Creating a Java Application Using GUI Output:

Basic I/O is made more user-friendly with graphical user-interfaces (GUIs). Java offers several options for constructing GUI dialog boxes. JOptionPane , a member of the javax class library extension, is our preferred interface. In order to access JOptionPane , the javax package must be directly imported into your file. We implement the new tool in a class called FirstDialog . FirstDialog manipulates a literal string in much the same way as First class. This time, a procedure, showMessageDialog( ) , is invoked directly against JOptionPane .The showMessageDialog( ) takes two arguments, null and "First Java Dialog", and outputs the string value to a message dialog box. The user presses OK to terminate the program. It should also be observed that the main ( ) program contains an additional line, a call to the System class exit( ). The exit( ) method must be employed in any application using a GUI object; it returns control to the operating system.

Correcting Errors and Finding Help:

The compiler will try to report as many errors as it can find during compilation so that you can fix as many errors as possible. Sometimes one error in syntax causes subsequent errors that normally would not be errors if the first syntax error did not exist. A second kind of error occurs when the syntax of the program is correct and the program is compiled, but produces incorrect results. This is a run-time error or logic error.

A great wealth of material exists at the Sun Microsystems Web site, http://java.sun.com. Of particular value are the FAQs (Frequently Asked Questions) that you can link to from a site search of the Web site. The tutorials provide a number of readable presentations on concepts and techniques fundamental to the Java language. Of course, the J2 SDK, the Java API (class library) and related documentation are also located at the Sun site.

 

From Chapter 2:

Using Constants and Variables

Data values may be fixed or varied. Data is constant when it cannot be changed after a program is compiled. A literal constant, such as 459, may be used directly in your program. Literals may also be named, allowing for multiple references in the same program. Data is variable when its value may change during program execution. Variables are named memory locations that your program can use to store values. In addition to a name, a variable also possesses a data type. A data type specifies the contents of a variable in three ways:

The Java language provides for eight primitive data types: boolean , byte , char , double , float , int , long and short . Primitives may also be used to construct more complex reference types, such as classes.

Declaring Variables:

You name variables in your programs using the same rules for naming classes. In general, variable names must start with a letter and cannot be any reserved keyword. You must declare all variables you want to use in a program. A variable declaration includes the following:

For example, the variable declaration:

int myAge=25;

declares a variable of type int named myAge and assigns it an initial value of 25. The declaration is a complete statement that ends in a semicolon. The equals sign (=) is the assignment operator. Any value to the right of the equals sign is assigned to the variable on the left of the equals sign. An assignment made when you declare a variable is an initialization; an assignment made later is simply an assignment. You may declare multiple variables of the same type in one statement. Variables of differing types must be declared in separate statements.

Learning about the int Data Type:

Use the int data type for variables, which will store integers or whole numbers. An int variable can hold any value from -2,147,483,648 to 2,147,483,647.

The types byte , short , and long are all variations of the integer type. Use byte or short if you have a variable, which will only hold very small numbers. Use long for variables, which will store values greater than the limit for int.

Displaying Variables:

Variables may be displayed alone or with a literal string using either the print ( ) or println ( ) method. In the first case, simply include the name of a variable within the parentheses enclosing the arguments. In the second case, the variable name is joined to a string using a concatenation operator (+). For example, the statement

System.out.println ("Next bill: October " + billingDate);

concatenates "Next bill: October " to an integer variable named billingDate.

Variables may also be displayed using GUIs, such as JOptionPane.showMessageDialog() . The showMessageDialog() method requires that a string be concatenated to the variable. To achieve the comparable functionality of print() and println(), which do accept stand-alone variable arguments, simply concatenate a null (empty) String to the variable. For example, the following statement outputs the value residing in an integer variable named creditDays.

JOptionPane.showMessageDialog (null,"" + creditDays);

Unlike console output, the dialog box requires proactive dismissal. When the user no longer needs the box, he/she clicks an OK button. A subsequent call to exit() returns control back to main().

Writing Arithmetic Statements

There are five standard binary arithmetic operators in Java: add (+), subtract (-), divide (/), multiply (*), and mod (%). The values placed on either side of an operator are called operands. A basic arithmetic expression contains at least two operands and one operator; for example, 45 + 35. Integer division deserves special attention; it does not return a fractional part. The modulus operation, defined exclusively for integers, returns the remainder of integer division. For instance, 45 % 35 = 10.

When mathematical operators are combined in an expression, you must understand the effects of operator precedence. Operator precedence rules order arithmetic operations by operator type. In the absence of parentheses, multiplication, division and modulus operations will be performed before addition and subtraction operations. Parentheses prioritize embedded operations. Expressions in nested parentheses are evaluated from the inner to the outer. Consider the following:

65 + 35 – (45 + 9) / 9 * 7

This expression evaluates to 58. In the absence of parentheses, the expression evaluates to 62.

Using the Boolean Data Type

A boolean variable may contain only one of two values: true or false. The following statements declare and assign appropriate values to boolean variables:

boolean isItPayday = false;

boolean areYouBroke = true;

You can also assign values based on the result of comparisons to Boolean variables. Java supports six comparison operators to be used in comparing two data items, equal to ( == ), greater than ( > ), less than ( < ), not equal ( != ), greater or equal ( >= ), less than or equal ( <= ). Expressions, which contain comparison operators, result in a Boolean value.


Consider the following two statements:

boolean isSixBigger = (6 > 5);

boolean isOvertimePay = (hours > 40);

The first line assigns a value of true to isSixBigger , while the second assigns true or false depending on the current value of hours.

Learning about Floating-Point Data Types:

A floating-point number contains decimal positions. Floating-point data types are used to store values that contain decimal positions. Java supports two floating-point types, float and double. A float data type can represent 6 or 7 significant digits of precision, while a double can represent 14 or 15 significant digits of precision. The term significant digits refers to the mathematical accuracy of a value. The number 18.23 is a double by default. You can explicitly specify a float by typing a lowercase or uppercase F after the number. You may also explicitly specify a double by typing a lowercase or uppercase D after the number. Floating-point arithmetic includes addition subtraction, multiplication, and division. The modulus operation is excluded because division with floating-point numbers returns a floating-point result.

Understanding Numeric Type Conversion:

When performing arithmetic with variables or constants of the same type, the result of the operation retains the same type. When performing operations on operands of unlike types, Java selects a unifying type for the result. The Java programming language then implicitly (or automatically) converts the nonconforming operands to the unifying type. Consider the following statement set:

int hoursWorked = 37;

double payRate = 6.73;

double grossPay = hoursWorked * payRate;

When encountering the third statement, the Java compiler will promote hoursWorked to a double , the unifying type. Had grossPay been declared as an int type, the statement would not compile, since the operation could result in a possible loss of precision.

You can explicitly override the unifying type by placing the desired result type in parentheses before the variable to be cast. Type casting involves placing the desired result type in parentheses, followed by the variable or constant to be cast.

double bankBalance = 189.66;

float weeklyBudget = (float) bankBalance / 4;

In the second statement, the expression on the right is converted to a float before assignment to weeklyBudget . Java would not otherwise (implicitly) cast the double to a float, since the downward conversion may possibly truncate data.

Working with the char Data Type

The char data type is used to store a single character. A character assignment encloses a single symbol in single quotes. An initialization appears below:

char myMiddleInitial = 'M';

The Java String class is used to store and manipulate sequences of characters. Strings will be further discussed in Chapter 7.

All characters, including digits, are represented by binary numbers. The two major character codes in use today are ASCII or Unicode. ASCII (American Standard Code for Information Interchange) has been a longtime standard character set. It is an eight-bit code, which contains 256 characters. Java now uses the newer Unicode standard. Unicode uses a sixteen-bit encoding scheme, which supports a much wider range of international character sets and symbols. Because 16-digit numbers are difficult to read, programmers often use a shorthand notation called hexadecimal or base 16. Table 2-6 represents the first 127 Unicode values and character equivalents.

In addition to letters, digits and other visual symbols, you may store nonprinting characters such as a backspace or a tab in a char variable. To store these characters, you can use an escape sequence, which always begins with a backslash followed by a character. Consider the following:

char aNewLine = '\n';

In the declarations of aNewLine, the backslash and character pair acts as a single character; the escape sequence serves to give a new meaning to the character. This particular character, the newline , moves the cursor to the beginning of the next line. It may be used with println( ) to produces multiple lines in the command window. For example, the following statement performs the work of two printlin( ) statements.

System.out.println ("Hello\nthere");

The statement is efficient for two reasons: it condenses two lines into one and requires one method call instead of two. Table 2-7 lists some of the common escape sequences used to control output. Some of these escape sequences, such as the newline character, do work in GUI objects, such as JOptionPane.

Using the JOptionPane Class for GUI Input

Message boxes accept input as well as display output. Two dialog boxes that can be used to accept user input are:

Using Input Dialog Boxes:

An input dialog box asks a question and provides a text field in which the user can enter a response. You can create an input dialog box by calling showInputDialog() . Six overloaded versions of this method are available, we discuss two: a simple version using a single argument and a more complex version using four arguments. At minimum, the showInputDialog() method takes a prompt argument, or message requesting user input. It returns a String representing a user’s response that may be assigned to a variable.

The application in Figure 2-8 demonstrates the versatility of showInputDialog() . The program calls showInputDialog( ) , retrieves a string from the user ("Audrey") , and assigns the value to a variable named result. The variable result is subsequently passed to showMessageDialog() , which concatenates the string and outputs the value back to the user. Figures 2-9 and 2-10 represent the dialog boxes active at each stage of the program.

The more complex version of showInputDialog() that requires four arguments can be used to display a title in the dialog box title bar and a message that describes the type of dialog box. The four arguments to showInputDialog() include:

The following statement passes four arguments to the overloaded showInputDialog() :

JOptionPane.showInputDialog(null,"What is your area code?:",

"Area code information", JOptionPane.QUESTION_MESSAGE);

Often times, the String input by the user must be converted to a number of int , or double type. To accomplish this task, you may use methods from the built-in Java classes Integer and Double. Each primitive type in Java has a corresponding class contained in the java.lang package; like most classes, the names of these classes begin with uppercase letters. These classes are called type-wrapper classes. They include methods that can process primitive type values. The SalaryDialog class, Figure 2-12, implements two such methods, Double.parseDouble() and Integer.parseInt(). The application retrieves two numerical values from the user through the InputDialog box. These values are assigned to String variables and subsequently passed to the type-wrapper class parser methods. The showMessageDialog() concatenates the values in a larger message and the outputs the results to the user.

Using Confirm Dialog Boxes:

A confirm dialog box displays the options Yes, No, and Cancel; you can create one using the showConfirmDialog( ) method in the JOptionPane class. Four overloaded versions of the method are available; the simplest requires a parent component (which can be null) and the String prompt that is displayed in the box. The showConfirmDialog() method returns an integer containing one of three possible values: JOptionPane.YES_OPTION, JOptionPane.NO_OPTION , or JOptionPane.CANCEL_OPTION.

The AirlineDialog program represented in Figure 2-14 implements showConfirmDialog( ). The method is called to obtain a response to the question, "Do you want to upgrade to first class?". After the user provides one of the three choices, the value is stored in an integer variable named selection. Then, a Boolean variable is set to the result of comparing selection and JOptionPane.YES_OPTION. If the user has selected theYes button in the dialog box, this variable is set to true; otherwise, the variable is set to false. Finally, the true or false result is displayed. Figure 2-16 shows the result when a user clicks theYes button in the dialog box.

You can also create a confirm dialog box with five arguments, as follows:

When the following statement is executed, it displays an input dialog box:

JOptionPane.showConfirmDialog (null, "A data input error has occurred.

Continue?","Data input error", JOptionPane.YES_NO_OPTION,
JOptionPane.ERROR_MESSAGE);

Figure 2-17 displays the call.


"Textbook Reading Assignments/Coverage"

This lesson plan covers the following chapters from your textbook:

From your textbook, please read chapter 1 (Pages 1 through 24) + Chapter 2 (pages 35 through 64).

 

"Lab Assignment"

Perform the following labs:

Perform the following four simple programming exercises:

  • Exercise 6 on page 31.
  • Exercise 7 on page 31.
  • Exercise 5 on page 70.
  • Exercise 8 on page 70.
  • Lab Notes:

    Please email me all four (4) java files in one email message:

    • Addressjava
    • Tree.java
    • Room.java
    • Time.java

    Email me the solution to the lab assignments by the due date to jbatarseh@yahoo.com .

    The email subject should be: CBIS6_Lesson Plan1 Labs.

    Please don’t forget to mention your full name when you submit the lab solution. If you fail to mention your full name in the lab submission will result in a high possibility that you will not be given credit for that assignment.

    "Quiz Assignment"

    After you have read the assigned "Reading Assignment" from your textbook and the "Lesson Plan Lecture Notes" above, please answer the following 10 questions by the due date. The quiz assignment is taken from chapters 1 and 2.

    To submit the solution to the quizzes you simply click on the "Quizzes" link on the course homepage, and then you click on the appropriate quiz number and submit the solution by clicking on the letter choice for each and every problem. When you are done, click on "Submit Quiz" button. Make sure that you enter the correct email address to receive your grade via email almost instantly. If you do not receive your grade; that means you misspelled your email address. If this happens, just let me know and I will let you know your grade.

    Please submit the solution by the due date.

    "Discussion Question"

    Post a comment/answer, on the discussion board, regarding one of the following questions:

  • What is the meaning of the term "platform-independent"?
  • Why Java is considered robust?
  • Why do we need so many different data types?
  • What are the decisions involved in choosing the appropriate data type for some value?
  • You must post a comment/answer to any of the questions or on any student’s answer to receive credit for the discussion portion of this lesson plan. Please use the discussion guidelines explained in the syllabus to receive full credit.

    Please don't forget to take the quiz for this lesson by clicking on the quiz button below.

    click here to go to the home page click here to email your instructor click here to go to the discussion group Click here to take the quiz